Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,22 @@ BROWSERBASE_AUTOMATION_SERVER=true npm start

When enabled, the app binds to `127.0.0.1` only and writes `automation.json` in
the app data directory. The descriptor includes `/session`, `/json/version`,
and `/json/list` endpoints. Use the returned `connectUrl` or
and `/json/list` endpoints and a per-launch `token`. On POSIX systems, the file
has owner-only permissions (`0600`). On Windows, access relies on the normal
per-user app-data directory access controls; the app does not configure or verify
Windows ACLs. Read the descriptor from your local automation client and send
`Authorization: Bearer <token>` when requesting metadata. The `/health` endpoint
does not require authentication.
Requests from browser origins or non-loopback hostnames are rejected.

Use the returned `connectUrl` or
`webSocketDebuggerUrl` with libraries that support CDP, such as Playwright's
`chromium.connectOverCDP`.

The endpoint is disabled by default because the CDP URL includes credentials for
the Browserbase session.
the Browserbase session. Treat both the descriptor token and returned connection
URLs as secrets. Clients that previously fetched metadata without authentication
must now read the descriptor and include its token.

### Accelerated Scrolling

Expand Down
63 changes: 54 additions & 9 deletions src/main/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import * as fs from "fs";
import { randomBytes, timingSafeEqual } from "crypto";
import { createServer, IncomingMessage, Server, ServerResponse } from "http";
import { AddressInfo } from "net";
import * as path from "path";
Expand Down Expand Up @@ -46,6 +47,7 @@ export function getAutomationServerPort(): number {

export class AutomationServer {
private server: Server | null = null;
private token = "";

constructor(
private readonly getSessionInfo: SessionInfoProvider,
Expand All @@ -58,18 +60,26 @@ export class AutomationServer {
return address.port;
}

this.token = randomBytes(32).toString("hex");
this.server = createServer((request, response) => {
this.handleRequest(request, response);
});

await new Promise<void>((resolve, reject) => {
this.server?.once("error", reject);
this.server?.listen(port, AUTOMATION_HOST, () => resolve());
});
try {
await new Promise<void>((resolve, reject) => {
this.server!.once("error", reject);
this.server!.listen(port, AUTOMATION_HOST, () => resolve());
});

const address = this.server.address() as AddressInfo;
this.writeDescriptor(address.port);
return address.port;
const address = this.server.address() as AddressInfo;
this.writeDescriptor(address.port);
return address.port;
} catch (error) {
this.server.close();
this.server = null;
this.token = "";
throw error;
}
}

async stop(): Promise<void> {
Expand All @@ -90,22 +100,46 @@ export class AutomationServer {
});
});

this.token = "";
this.removeDescriptor();
}

private handleRequest(request: IncomingMessage, response: ServerResponse): void {
const port = (this.server?.address() as AddressInfo | null)?.port;
if (
![`${AUTOMATION_HOST}:${port}`, `localhost:${port}`].includes(request.headers.host || "") ||
request.headers.origin !== undefined ||
request.headers["sec-fetch-site"] !== undefined
) {
this.sendJson(response, 403, { error: "Local clients only" });
return;
}

if (request.method !== "GET") {
this.sendJson(response, 405, { error: "Method not allowed" });
return;
}

const requestUrl = new URL(request.url || "/", `http://${AUTOMATION_HOST}`);
let requestUrl: URL;
try {
requestUrl = new URL(request.url || "/", `http://${AUTOMATION_HOST}:${port}`);
} catch {
this.sendJson(response, 400, { error: "Invalid request URL" });
return;
}

if (requestUrl.pathname === "/health") {
this.sendJson(response, 200, { ok: true });
return;
}

const authorization = Buffer.from(request.headers.authorization || "");
const expected = Buffer.from(`Bearer ${this.token}`);
if (authorization.length !== expected.length || !timingSafeEqual(authorization, expected)) {
this.sendJson(response, 401, { error: "Authentication required" });
return;
}

const sessionInfo = this.getSessionInfo();
if (!sessionInfo) {
this.sendJson(response, 503, { error: "No Browserbase session is available yet" });
Expand Down Expand Up @@ -148,6 +182,7 @@ export class AutomationServer {
response.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
response.end(JSON.stringify(body, null, 2));
}
Expand All @@ -156,6 +191,7 @@ export class AutomationServer {
const baseUrl = `http://${AUTOMATION_HOST}:${port}`;
const descriptor = {
enabled: true,
token: this.token,
host: AUTOMATION_HOST,
port,
baseUrl,
Expand All @@ -165,7 +201,16 @@ export class AutomationServer {
};

fs.mkdirSync(this.userDataPath, { recursive: true });
fs.writeFileSync(this.getDescriptorPath(), JSON.stringify(descriptor, null, 2));
const temporaryPath = `${this.getDescriptorPath()}.${randomBytes(8).toString("hex")}.tmp`;
try {
fs.writeFileSync(temporaryPath, JSON.stringify(descriptor, null, 2), {
mode: 0o600,
flag: "wx",
});
fs.renameSync(temporaryPath, this.getDescriptorPath());
} finally {
fs.rmSync(temporaryPath, { force: true });
}
}

private removeDescriptor(): void {
Expand Down
66 changes: 66 additions & 0 deletions tests/automation.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const assert = require('node:assert/strict');
const { mkdtempSync, readFileSync, statSync, existsSync, rmSync, writeFileSync } = require('node:fs');
const { tmpdir } = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { test } = require('node:test');
const { AutomationServer } = require('../dist/main/automation');

function request(port, endpoint, headers = {}) {
return new Promise((resolve, reject) => {
http.get({ hostname: '127.0.0.1', port, path: endpoint, headers }, (response) => {
let body = '';
response.on('data', (chunk) => { body += chunk; });
response.on('end', () => resolve({ status: response.statusCode, body, headers: response.headers }));
}).on('error', reject);
});
}

test('automation metadata requires a private, rotating token and rejects browser origins', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'desktop-automation-test-'));
const descriptorPath = path.join(dir, 'automation.json');
const info = { sessionId: 'test', status: 'RUNNING', connectUrl: 'wss://example.test/?apiKey=synthetic', debugUrl: '', currentUrl: '', tabs: [] };
let providerCalls = 0;
const server = new AutomationServer(() => { providerCalls++; return info; }, dir);
try {
// Existing broad permissions must not survive replacing a descriptor.
writeFileSync(descriptorPath, '{}', { mode: 0o644 });
const port = await server.start();
const descriptor = JSON.parse(readFileSync(descriptorPath, 'utf8'));
if (process.platform !== 'win32') assert.equal(statSync(descriptorPath).mode & 0o777, 0o600);
const auth = { Authorization: `Bearer ${descriptor.token}` };
for (const endpoint of ['/session', '/json/version', '/json/list']) {
assert.equal((await request(port, endpoint)).status, 401);
assert.equal((await request(port, endpoint, { Authorization: 'Bearer invalid' })).status, 401);
for (const hostileHeaders of [
{ Host: `rebind.example.test:${port}` },
{ Origin: 'https://example.test' },
{ Origin: 'null' },
{ 'Sec-Fetch-Site': 'same-origin' },
]) {
const rejected = await request(port, endpoint, { ...auth, ...hostileHeaders });
assert.equal(rejected.status, 403);
assert.ok(!rejected.body.includes('synthetic'));
}
}
assert.equal(providerCalls, 0);
assert.equal((await request(port, '/health')).status, 200);
const metadata = await request(port, '/session', auth);
assert.equal(metadata.status, 200);
assert.deepEqual(JSON.parse(metadata.body), info);
assert.equal(metadata.headers['cache-control'], 'no-store');
assert.equal(metadata.headers['x-content-type-options'], 'nosniff');
assert.equal(JSON.parse((await request(port, '/json/version', auth)).body).webSocketDebuggerUrl, info.connectUrl);
assert.deepEqual(JSON.parse((await request(port, '/json/list', auth)).body), []);
await server.stop();
assert.ok(!existsSync(descriptorPath));
const nextPort = await server.start();
const nextDescriptor = JSON.parse(readFileSync(descriptorPath, 'utf8'));
assert.notEqual(nextDescriptor.token, descriptor.token);
assert.equal((await request(nextPort, '/session', auth)).status, 401);
assert.equal((await request(nextPort, '/session', { Authorization: `Bearer ${nextDescriptor.token}` })).status, 200);
} finally {
await server.stop();
rmSync(dir, { recursive: true, force: true });
}
});