Skip to content

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

feat(mcp): add pairing storage, the lockfile, and logging

Shahriar179f5d5075d8
diff --git a/mcp/src/auth-store.ts b/mcp/src/auth-store.ts
new file mode 100644
index 0000000..d4ac97d
--- /dev/null
+++ b/mcp/src/auth-store.ts
@@ -0,0 +1,127 @@
+import { randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
+import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { stateDir } from './lockfile';
+
+/**
+ * Persistent pairing state, deliberately separate from the lockfile: the lockfile describes a
+ * running process and is deleted on shutdown, while sessions must survive daemon and browser
+ * restarts until the user explicitly revokes them.
+ */
+const authPath = join(stateDir, 'auth.json');
+
+/** Unambiguous when read aloud or typed: no 0/O, 1/I/L, U/V. */
+const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTWXYZ23456789';
+const CODE_LENGTH = 8;
+const PAIRING_TTL_MS = 10 * 60 * 1000;
+
+export interface Session {
+ key: string;
+ origin: string;
+ extensionVersion: string;
+ pairedAt: string;
+ lastSeenAt: string;
+}
+
+interface Pairing {
+ code: string;
+ expiresAt: number;
+}
+
+interface AuthFile {
+ pairings: Pairing[];
+ sessions: Session[];
+}
+
+function read(): AuthFile {
+ try {
+ const parsed = JSON.parse(readFileSync(authPath, 'utf8')) as Partial<AuthFile>;
+ return { pairings: parsed.pairings ?? [], sessions: parsed.sessions ?? [] };
+ } catch {
+ return { pairings: [], sessions: [] };
+ }
+}
+
+function write(auth: AuthFile): void {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ writeFileSync(authPath, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 });
+ chmodSync(authPath, 0o600);
+}
+
+/** Mint a one-time pairing code for the user to type into the extension. */
+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 expiresAt = Date.now() + PAIRING_TTL_MS;
+ // One outstanding code at a time: minting a new one invalidates any earlier code.
+ write({ ...auth, pairings: [{ code, expiresAt }] });
+ return { code, expiresAt };
+}
+
+/**
+ * Redeem a pairing code. Single use — it is removed whether or not it had expired, so a
+ * leaked code cannot be replayed after the legitimate pairing consumed it.
+ */
+export function consumePairing(offered: string): boolean {
+ const auth = read();
+ const normalized = offered.replace(/[\s-]/g, '').toUpperCase();
+ const match = auth.pairings.find((pairing) => equals(pairing.code, normalized));
+ write({ ...auth, pairings: auth.pairings.filter((pairing) => pairing !== match) });
+ return !!match && match.expiresAt > Date.now();
+}
+
+export function hasPendingPairing(): boolean {
+ return read().pairings.some((pairing) => pairing.expiresAt > Date.now());
+}
+
+export function createSession(origin: string, extensionVersion: string): Session {
+ const auth = read();
+ const now = new Date().toISOString();
+ const session: Session = {
+ key: randomBytes(32).toString('base64url'),
+ origin,
+ extensionVersion,
+ pairedAt: now,
+ lastSeenAt: now,
+ };
+ // One browser at a time: a new pairing replaces any session for the same origin.
+ const sessions = auth.sessions.filter((existing) => existing.origin !== origin);
+ write({ ...auth, sessions: [...sessions, session] });
+ return session;
+}
+
+/** A session key is only valid from the origin that paired it. */
+export function validateSession(offeredKey: string, origin: string): Session | null {
+ const auth = read();
+ const session = auth.sessions.find(
+ (candidate) => candidate.origin === origin && equals(candidate.key, offeredKey),
+ );
+ if (!session) return null;
+ session.lastSeenAt = new Date().toISOString();
+ write(auth);
+ return session;
+}
+
+export function listSessions(): Session[] {
+ return read().sessions;
+}
+
+export function revokeSessions(predicate: (session: Session) => boolean): number {
+ const auth = read();
+ const keep = auth.sessions.filter((session) => !predicate(session));
+ write({ ...auth, sessions: keep });
+ return auth.sessions.length - keep.length;
+}
+
+export function clearAuth(): void {
+ rmSync(authPath, { force: true });
+}
+
+function equals(a: string, b: string): boolean {
+ const left = Buffer.from(a);
+ const right = Buffer.from(b);
+ return left.length === right.length && timingSafeEqual(left, right);
+}
diff --git a/mcp/src/lockfile.ts b/mcp/src/lockfile.ts
new file mode 100644
index 0000000..f21e521
--- /dev/null
+++ b/mcp/src/lockfile.ts
@@ -0,0 +1,46 @@
+import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+export const stateDir = process.env.VOICELINK_HOME ?? join(homedir(), '.voicelink');
+export const lockfilePath = join(stateDir, 'daemon.json');
+export const logPath = join(stateDir, 'daemon.log');
+
+export interface Lockfile {
+ pid: number;
+ port: number;
+ /** Bearer token for control clients (the CLI). Never leaves the filesystem. */
+ token: string;
+ protocolVersion: number;
+ daemonVersion: string;
+}
+
+export function readLockfile(): Lockfile | null {
+ try {
+ const lock = JSON.parse(readFileSync(lockfilePath, 'utf8')) as Lockfile;
+ return typeof lock?.port === 'number' && typeof lock?.token === 'string' ? lock : null;
+ } catch {
+ return null;
+ }
+}
+
+export function writeLockfile(lock: Lockfile): void {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ writeFileSync(lockfilePath, `${JSON.stringify(lock, null, 2)}\n`, { mode: 0o600 });
+ // writeFileSync only applies `mode` when creating; re-assert it for pre-existing files.
+ chmodSync(lockfilePath, 0o600);
+}
+
+export function clearLockfile(): void {
+ rmSync(lockfilePath, { force: true });
+}
+
+/** True when a process with this pid exists and we may signal it. */
+export function isRunning(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
+ }
+}
diff --git a/mcp/src/log.ts b/mcp/src/log.ts
new file mode 100644
index 0000000..0476bb8
--- /dev/null
+++ b/mcp/src/log.ts
@@ -0,0 +1,33 @@
+import { appendFileSync, mkdirSync, renameSync, statSync } from 'node:fs';
+import { logPath, stateDir } from './lockfile';
+
+const MAX_BYTES = 2 * 1024 * 1024;
+
+/**
+ * Daemon logging. Never write to stdout from the CLI process — stdout is the MCP
+ * JSON-RPC stream, and a stray line corrupts the session.
+ */
+export function log(message: string, detail?: unknown): void {
+ const line = `${new Date().toISOString()} ${message}${detail === undefined ? '' : ` ${format(detail)}`}\n`;
+ try {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ rotateIfLarge();
+ appendFileSync(logPath, line);
+ } catch {
+ // Logging must never take the daemon down.
+ }
+ if (process.env.VOICELINK_DEBUG) process.stderr.write(line);
+}
+
+function rotateIfLarge(): void {
+ try {
+ if (statSync(logPath).size > MAX_BYTES) renameSync(logPath, `${logPath}.1`);
+ } catch {
+ // No log file yet.
+ }
+}
+
+function format(detail: unknown): string {
+ if (detail instanceof Error) return `${detail.name}: ${detail.message}`;
+ return typeof detail === 'string' ? detail : JSON.stringify(detail);
+}