163 lines
5.0 KiB
JavaScript
163 lines
5.0 KiB
JavaScript
// Where native hosts and MCP servers meet.
|
|
//
|
|
// Every connected browser runs its own native host (Chrome starts one per
|
|
// extension instance), and each host listens on its own endpoint: a unix
|
|
// socket on POSIX, a named pipe on Windows. Next to it the host writes a small
|
|
// JSON descriptor (deviceId, display name, platform, pid). An MCP server finds
|
|
// browsers by reading the descriptors, which is what makes
|
|
// list_connected_browsers / select_browser possible without any broker.
|
|
//
|
|
// Everything lives in a 0700 per-user directory, so no other account on the
|
|
// machine can reach a browser holding real logged-in sessions.
|
|
|
|
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import net from "node:net";
|
|
import { createHash } from "node:crypto";
|
|
|
|
export const APP_DIR = path.join(os.homedir(), ".config", "opencode-browser");
|
|
|
|
function currentUser() {
|
|
try {
|
|
const { username } = os.userInfo();
|
|
if (username) return username;
|
|
} catch {}
|
|
return process.env.USER || process.env.USERNAME || "default";
|
|
}
|
|
|
|
// Env override first, so a test harness can stand up hosts and clients on a
|
|
// scratch directory without disturbing the live ones.
|
|
//
|
|
// Deliberately NOT os.tmpdir(): that follows $TMPDIR, and the two sides are
|
|
// started by different parents with different environments (Chrome starts the
|
|
// host; an MCP client may start the server with a minimal env), so they would
|
|
// look in different places.
|
|
export function socketDir() {
|
|
if (process.env.OCB_DIR) return process.env.OCB_DIR;
|
|
return path.join(APP_DIR, "run");
|
|
}
|
|
|
|
export function ensureSocketDir() {
|
|
const dir = socketDir();
|
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
if (process.platform !== "win32") {
|
|
try {
|
|
fs.chmodSync(dir, 0o700);
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
// deviceIds are generated by the extension; keep them filename-safe anyway.
|
|
const safeId = (id) => String(id).replace(/[^\w-]/g, "").slice(0, 64);
|
|
|
|
export function endpointPath(deviceId) {
|
|
if (process.platform === "win32") {
|
|
const user = currentUser().replace(/[^\w.-]/g, "_").slice(0, 32);
|
|
return `\\\\.\\pipe\\opencode-browser-${user}-${safeId(deviceId)}`;
|
|
}
|
|
// Unix socket paths are capped at ~104 bytes and macOS's temp dir alone is
|
|
// ~50, so the socket gets a short hash of the deviceId rather than the id.
|
|
const short = createHash("sha256").update(String(deviceId)).digest("hex").slice(0, 12);
|
|
return path.join(socketDir(), `${short}.sock`);
|
|
}
|
|
|
|
export function descriptorPath(deviceId) {
|
|
return path.join(socketDir(), `${safeId(deviceId)}.json`);
|
|
}
|
|
|
|
export function writeDescriptor(info) {
|
|
ensureSocketDir();
|
|
const file = descriptorPath(info.deviceId);
|
|
fs.writeFileSync(file, JSON.stringify(info, null, 2), { mode: 0o600 });
|
|
}
|
|
|
|
export function removeDescriptor(deviceId) {
|
|
try {
|
|
fs.unlinkSync(descriptorPath(deviceId));
|
|
} catch {}
|
|
}
|
|
|
|
// All descriptors whose owning process is still alive. A host killed without
|
|
// cleanup leaves its file behind; a dead pid is enough to ignore it (and tidy
|
|
// it up), the connect attempt in the runtime is the final word.
|
|
export function listDescriptors() {
|
|
let names = [];
|
|
try {
|
|
names = fs.readdirSync(socketDir()).filter((n) => n.endsWith(".json"));
|
|
} catch {
|
|
return [];
|
|
}
|
|
const out = [];
|
|
for (const name of names) {
|
|
const file = path.join(socketDir(), name);
|
|
try {
|
|
const info = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
if (!info.deviceId || !pidAlive(info.pid)) {
|
|
try {
|
|
fs.unlinkSync(file);
|
|
} catch {}
|
|
continue;
|
|
}
|
|
out.push(info);
|
|
} catch {}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function pidAlive(pid) {
|
|
if (!pid) return false;
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch (e) {
|
|
return e.code === "EPERM";
|
|
}
|
|
}
|
|
|
|
export function secureSocket(p) {
|
|
if (process.platform === "win32") return;
|
|
try {
|
|
fs.chmodSync(p, 0o600);
|
|
} catch {}
|
|
}
|
|
|
|
// A unix socket file outlives its process. Only unlink once a connect attempt
|
|
// proves nobody is listening — unlinking a live one would strand its clients.
|
|
export async function clearStaleSocket(p) {
|
|
if (process.platform === "win32" || !fs.existsSync(p)) return;
|
|
const alive = await new Promise((resolve) => {
|
|
const probe = net.createConnection(p);
|
|
const done = (v) => {
|
|
probe.destroy();
|
|
resolve(v);
|
|
};
|
|
probe.on("connect", () => done(true));
|
|
probe.on("error", () => done(false));
|
|
setTimeout(() => done(false), 500);
|
|
});
|
|
if (!alive) {
|
|
try {
|
|
fs.unlinkSync(p);
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
// Breadcrumbs for processes whose stderr nobody reads (Chrome discards the
|
|
// native host's). One line per event, capped so it never grows unbounded.
|
|
export function logLine(file, line) {
|
|
try {
|
|
fs.mkdirSync(APP_DIR, { recursive: true });
|
|
const p = path.join(APP_DIR, file);
|
|
let prev = "";
|
|
try {
|
|
prev = fs.readFileSync(p, "utf-8");
|
|
} catch {}
|
|
const next = (prev + `${new Date().toISOString()} pid=${process.pid} ${line}\n`)
|
|
.split("\n")
|
|
.slice(-200)
|
|
.join("\n");
|
|
fs.writeFileSync(p, next);
|
|
} catch {}
|
|
}
|