#!/usr/bin/env node // Native messaging host. Chrome starts one per extension instance when the // extension calls connectNative(), and kills it when the extension goes away, // so this process's lifetime IS that browser's link. // // It waits for the extension's `hello` (deviceId, display name, platform), // then opens this browser's endpoint and descriptor (see endpoint.js) and // multiplexes any number of MCP servers onto the single native-messaging // channel. Requests are re-numbered per client so concurrent sessions can't // collide, and every reply is routed back to the client that asked. import net from "node:net"; import fs from "node:fs"; import path from "node:path"; import { APP_DIR, endpointPath, ensureSocketDir, clearStaleSocket, secureSocket, writeDescriptor, removeDescriptor, logLine } from "./endpoint.js"; // --- Native messaging framing (4-byte LE length + JSON) --- function readNativeMessages(buffer) { const messages = []; let offset = 0; while (offset + 4 <= buffer.length) { const len = buffer.readUInt32LE(offset); if (offset + 4 + len > buffer.length) break; try { messages.push(JSON.parse(buffer.subarray(offset + 4, offset + 4 + len).toString("utf-8"))); } catch {} offset += 4 + len; } return { messages, remainder: buffer.subarray(offset) }; } function writeNativeMessage(obj) { const buf = Buffer.from(JSON.stringify(obj), "utf-8"); const header = Buffer.alloc(4); header.writeUInt32LE(buf.length, 0); process.stdout.write(Buffer.concat([header, buf])); } // --- State --- let browserInfo = null; // set by the extension's hello let server = null; const clients = new Map(); // clientId -> { socket, session } const routes = new Map(); // forwarded id -> { clientId, originalId } let clientSeq = 0; let lastExtensionTraffic = Date.now(); let heartbeatsSeen = 0; // --- MCP clients --- function onConnection(socket) { socket.on("error", () => socket.destroy()); const clientId = String(++clientSeq); let buffer = Buffer.alloc(0); clients.set(clientId, { socket, session: null }); socket.on("data", (chunk) => { buffer = Buffer.concat([buffer, chunk]); let idx; while ((idx = buffer.indexOf(10)) !== -1) { const line = buffer.subarray(0, idx).toString("utf-8").trim(); buffer = buffer.subarray(idx + 1); if (!line) continue; let msg; try { msg = JSON.parse(line); } catch { continue; } handleClientMessage(clientId, msg); } }); socket.on("close", () => { const session = clients.get(clientId)?.session; clients.delete(clientId); // Let the extension turn off the "agent is working" overlay. if (session) writeNativeMessage({ type: "session_end", session }); for (const [id, r] of routes) if (r.clientId === clientId) routes.delete(id); }); } function handleClientMessage(clientId, msg) { const client = clients.get(clientId); if (!client) return; if (msg.type === "client_hello") { client.session = msg.session || null; send(client.socket, { type: "client_ack", clientId, browser: browserInfo }); return; } // Everything else goes to the extension. Anything carrying an id expects a // reply, so remember who to hand it back to. if (msg.id) { const fwdId = `c${clientId}_${msg.id}`; routes.set(fwdId, { clientId, originalId: msg.id }); writeNativeMessage({ ...msg, id: fwdId, session: msg.session || client.session }); } else { writeNativeMessage({ ...msg, session: msg.session || client.session }); } } function send(socket, obj) { try { if (!socket.destroyed) socket.write(JSON.stringify(obj) + "\n"); } catch {} } // --- Messages from the extension --- function handleExtensionMessage(msg) { if (!msg || typeof msg !== "object") return; switch (msg.type) { case "heartbeat": heartbeatsSeen++; return; case "hello": onHello(msg); return; case "rename": if (browserInfo) { browserInfo.name = String(msg.name || browserInfo.name).slice(0, 80); writeDescriptor({ ...browserInfo, pid: process.pid }); } return; case "write_temp_file": writeTempFile(msg); return; } if (msg.id && routes.has(msg.id)) { const { clientId, originalId } = routes.get(msg.id); routes.delete(msg.id); const client = clients.get(clientId); if (client) send(client.socket, { ...msg, id: originalId }); } } async function onHello(msg) { const first = !browserInfo; browserInfo = { deviceId: String(msg.deviceId), name: String(msg.name || "Chrome").slice(0, 80), browser: msg.browser || "Chrome", platform: msg.platform || process.platform, hostPlatform: process.platform, extensionVersion: msg.version || null, connectedAt: new Date().toISOString() }; writeDescriptor({ ...browserInfo, pid: process.pid }); if (first) await listen(); } async function listen() { ensureSocketDir(); const p = endpointPath(browserInfo.deviceId); await clearStaleSocket(p); server = net.createServer(onConnection); server.on("error", (err) => { logLine("host.log", `listen failed on ${p}: ${err.message}`); // Another host for the same deviceId (two profiles sharing storage is // impossible, so this is a leftover process): retry shortly. setTimeout(listen, 1500); }); server.listen(p, () => secureSocket(p)); } // Stage bytes (an in-memory screenshot or exported GIF) as a real file, so the // extension can attach it to a file input or drag it onto the page via CDP — // both of which need a path on disk. function writeTempFile(msg) { const reply = (payload) => writeNativeMessage({ id: msg.id, type: "temp_file_written", ...payload }); try { const root = path.join(APP_DIR, "tmp"); // One folder per file, so the page sees exactly the requested filename. const dir = path.join(root, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`); fs.mkdirSync(dir, { recursive: true }); const name = String(msg.filename || "upload.png").replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").slice(0, 120) || "upload.png"; const file = path.join(dir, name); const b64 = String(msg.dataUrl || "").replace(/^data:[^;]+;base64,/, ""); if (!b64) return reply({ ok: false, error: "no data" }); fs.writeFileSync(file, Buffer.from(b64, "base64")); // Prune our own staged folders older than a day. const cutoff = Date.now() - 86_400_000; for (const f of fs.readdirSync(root).slice(0, 500)) { if (!/^\d+-\w+$/.test(f)) continue; const p = path.join(root, f); try { if (fs.statSync(p).mtimeMs < cutoff) fs.rmSync(p, { recursive: true, force: true }); } catch {} } reply({ ok: true, result: file }); } catch (e) { reply({ ok: false, error: String(e && e.message) }); } } // --- Main loop --- let stdinBuffer = Buffer.alloc(0); process.stdin.on("data", (chunk) => { lastExtensionTraffic = Date.now(); stdinBuffer = Buffer.concat([stdinBuffer, chunk]); const { messages, remainder } = readNativeMessages(stdinBuffer); stdinBuffer = remainder; for (const m of messages) handleExtensionMessage(m); }); function shutdown(reason) { logLine("host.log", `exit: ${reason} (clients: ${clients.size})`); for (const { socket } of clients.values()) { try { socket.destroy(); } catch {} } if (browserInfo) { removeDescriptor(browserInfo.deviceId); if (process.platform !== "win32") { try { fs.unlinkSync(endpointPath(browserInfo.deviceId)); } catch {} } } process.exit(0); } process.stdin.on("end", () => shutdown("extension disconnected")); process.on("SIGTERM", () => shutdown("SIGTERM")); process.on("SIGINT", () => shutdown("SIGINT")); // A wedged service worker leaves a host that accepts clients but never // answers. The extension heartbeats every ~15s; long silence after we have // seen heartbeats means it's gone, and exiting lets Chrome start a fresh host. const SILENCE_LIMIT_MS = Number(process.env.OCB_SILENCE_LIMIT_MS) || 60_000; setInterval(() => { if (heartbeatsSeen < 2) return; if (Date.now() - lastExtensionTraffic > SILENCE_LIMIT_MS) shutdown("watchdog: extension silent"); }, 15_000).unref();