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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"main": "dist/main/index.js",
"scripts": {
"build": "npm run build:main && npm run build:renderer && npm run copy-assets",
"build:main": "tsc -p tsconfig.main.json",
"build:main": "tsc -p tsconfig.main.json && npm run build:preload",
"build:preload": "esbuild src/main/preload.ts --bundle --outfile=dist/main/preload.js --platform=node --format=cjs --external:electron --target=es2020",
"build:renderer": "esbuild src/renderer/app.ts --bundle --outfile=dist/renderer/app.js --platform=browser --target=es2020",
"copy-assets": "cp src/renderer/index.html dist/renderer/ && cp -r src/renderer/styles dist/renderer/",
"start": "npm run build && electron .",
Expand Down
25 changes: 5 additions & 20 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
* @module main/index
*/

import { app, BrowserWindow, session, nativeTheme, dialog, Menu, MenuItemConstructorOptions } from "electron";
import { app, BrowserWindow, nativeTheme, dialog, Menu, MenuItemConstructorOptions } from "electron";
import * as path from "path";
import * as fs from "fs";
import { sessionManager } from "./session";
import { setupIpcHandlers, removeIpcHandlers } from "./ipc";
import { IPC_CHANNELS } from "../shared/types";
import { getConfigSearchPaths, loadEnvironmentConfig } from "./config";
import { AutomationServer, getAutomationServerPort, isAutomationServerEnabled } from "./automation";
import { secureWindow } from "./security";

let mainWindow: BrowserWindow | null = null;
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
Expand Down Expand Up @@ -332,11 +333,13 @@ async function createWindow(): Promise<void> {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Required for preload script
sandbox: true,
webviewTag: true, // Enable webview tag for live view embed
},
});

secureWindow(mainWindow);

// Restore maximized state
if (windowState.isMaximized) {
mainWindow.maximize();
Expand Down Expand Up @@ -395,23 +398,6 @@ async function createWindow(): Promise<void> {
}
}

// Set up content security policy for Browserbase iframe
function setupContentSecurityPolicy(): void {
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
"Content-Security-Policy": [
"default-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.browserbase.com wss://*.browserbase.com; " +
"frame-src https://*.browserbase.com https://www.browserbase.com; " +
"img-src 'self' data: https: http:; " +
"connect-src 'self' https://*.browserbase.com wss://*.browserbase.com wss://connect.browserbase.com https://www.google.com;",
],
},
});
});
}

// App lifecycle
app.whenReady().then(async () => {
const loadedConfigFiles = loadEnvironmentConfig();
Expand All @@ -435,7 +421,6 @@ app.whenReady().then(async () => {
}

createApplicationMenu();
setupContentSecurityPolicy();
await createWindow();

// Handle theme changes
Expand Down
57 changes: 36 additions & 21 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
* @module main/ipc
*/

import { ipcMain, BrowserWindow } from "electron";
import { ipcMain, BrowserWindow, IpcMainEvent, IpcMainInvokeEvent } from "electron";
import { IPC_CHANNELS, ScrollInputEvent } from "../shared/types";
import { sessionManager } from "./session";
import { isTrustedRenderer } from "./security";

function isAcceleratedScrollEnabled(): boolean {
const value = process.env.BROWSERBASE_ACCELERATED_SCROLL;
Expand All @@ -29,8 +30,22 @@ function isAcceleratedScrollEnabled(): boolean {
* @param mainWindow - The main BrowserWindow instance
*/
export function setupIpcHandlers(mainWindow: BrowserWindow): void {
const handle = (channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => unknown) => {
ipcMain.handle(channel, (event, ...args) => {
if (!isTrustedRenderer(event, mainWindow)) {
throw new Error("Untrusted IPC sender");
}
return listener(event, ...args);
});
};
const on = (channel: string, listener: (event: IpcMainEvent, ...args: any[]) => void) => {
ipcMain.on(channel, (event, ...args) => {
if (isTrustedRenderer(event, mainWindow)) listener(event, ...args);
});
};

// Navigation handlers
ipcMain.handle(IPC_CHANNELS.NAVIGATE_TO, async (_event, url: string) => {
handle(IPC_CHANNELS.NAVIGATE_TO, async (_event, url: string) => {
try {
await sessionManager.navigateTo(url);
return { success: true };
Expand All @@ -39,7 +54,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.NAVIGATE_BACK, async () => {
handle(IPC_CHANNELS.NAVIGATE_BACK, async () => {
try {
await sessionManager.goBack();
return { success: true };
Expand All @@ -48,7 +63,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.NAVIGATE_FORWARD, async () => {
handle(IPC_CHANNELS.NAVIGATE_FORWARD, async () => {
try {
await sessionManager.goForward();
return { success: true };
Expand All @@ -57,7 +72,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.NAVIGATE_RELOAD, async () => {
handle(IPC_CHANNELS.NAVIGATE_RELOAD, async () => {
try {
await sessionManager.reload();
return { success: true };
Expand All @@ -66,7 +81,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.NAVIGATE_HOME, async () => {
handle(IPC_CHANNELS.NAVIGATE_HOME, async () => {
try {
const homeUrl = process.env.BROWSERBASE_DEFAULT_URL || "https://www.google.com";
await sessionManager.navigateTo(homeUrl);
Expand All @@ -76,11 +91,11 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.GET_ACCELERATED_SCROLL_ENABLED, () => {
handle(IPC_CHANNELS.GET_ACCELERATED_SCROLL_ENABLED, () => {
return isAcceleratedScrollEnabled();
});

ipcMain.on(IPC_CHANNELS.INPUT_SCROLL, (_event, scrollEvent: ScrollInputEvent) => {
on(IPC_CHANNELS.INPUT_SCROLL, (_event, scrollEvent: ScrollInputEvent) => {
if (!isAcceleratedScrollEnabled()) {
return;
}
Expand All @@ -89,7 +104,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
});

// Tab handlers
ipcMain.handle(IPC_CHANNELS.TAB_NEW, async () => {
handle(IPC_CHANNELS.TAB_NEW, async () => {
try {
await sessionManager.newTab();
return { success: true };
Expand All @@ -98,7 +113,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.TAB_CLOSE, async (_event, tabId: string) => {
handle(IPC_CHANNELS.TAB_CLOSE, async (_event, tabId: string) => {
try {
await sessionManager.closeTab(tabId);
return { success: true };
Expand All @@ -107,7 +122,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});

ipcMain.handle(IPC_CHANNELS.TAB_SWITCH, async (_event, tabId: string) => {
handle(IPC_CHANNELS.TAB_SWITCH, async (_event, tabId: string) => {
try {
await sessionManager.switchTab(tabId);
return { success: true };
Expand All @@ -117,52 +132,52 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
});

// Debug URL handler (Browserbase live view)
ipcMain.handle(IPC_CHANNELS.GET_DEBUG_URL, () => {
handle(IPC_CHANNELS.GET_DEBUG_URL, () => {
return sessionManager.getDebugUrl();
});

// Window control handlers
ipcMain.on(IPC_CHANNELS.WINDOW_MINIMIZE, () => {
on(IPC_CHANNELS.WINDOW_MINIMIZE, () => {
mainWindow.minimize();
});

ipcMain.on(IPC_CHANNELS.WINDOW_MAXIMIZE, () => {
on(IPC_CHANNELS.WINDOW_MAXIMIZE, () => {
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
});

ipcMain.on(IPC_CHANNELS.WINDOW_CLOSE, () => {
on(IPC_CHANNELS.WINDOW_CLOSE, () => {
mainWindow.close();
});

// Bookmarks toggle (for future implementation)
ipcMain.on(IPC_CHANNELS.BOOKMARKS_TOGGLE, () => {
on(IPC_CHANNELS.BOOKMARKS_TOGGLE, () => {
mainWindow.webContents.send(IPC_CHANNELS.BOOKMARKS_TOGGLE);
});

// Menu action handlers
ipcMain.on(IPC_CHANNELS.OPEN_DEVTOOLS, () => {
on(IPC_CHANNELS.OPEN_DEVTOOLS, () => {
mainWindow.webContents.openDevTools();
});

ipcMain.on(IPC_CHANNELS.TOGGLE_FULLSCREEN, () => {
on(IPC_CHANNELS.TOGGLE_FULLSCREEN, () => {
mainWindow.setFullScreen(!mainWindow.isFullScreen());
});

ipcMain.on(IPC_CHANNELS.ZOOM_IN, () => {
on(IPC_CHANNELS.ZOOM_IN, () => {
const currentZoom = mainWindow.webContents.getZoomLevel();
mainWindow.webContents.setZoomLevel(currentZoom + 0.5);
});

ipcMain.on(IPC_CHANNELS.ZOOM_OUT, () => {
on(IPC_CHANNELS.ZOOM_OUT, () => {
const currentZoom = mainWindow.webContents.getZoomLevel();
mainWindow.webContents.setZoomLevel(currentZoom - 0.5);
});

ipcMain.on(IPC_CHANNELS.ZOOM_RESET, () => {
on(IPC_CHANNELS.ZOOM_RESET, () => {
mainWindow.webContents.setZoomLevel(0);
});
}
Expand Down
80 changes: 80 additions & 0 deletions src/main/security.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { BrowserWindow, IpcMainEvent, IpcMainInvokeEvent, session } from "electron";
import * as path from "path";
import { pathToFileURL } from "url";

const rendererUrl = pathToFileURL(path.join(__dirname, "../renderer/index.html")).href;
const liveViewPartition = "persist:browserbase";

export function isLiveViewUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === "https:" &&
!url.username && !url.password && !url.port &&
url.hostname === "www.browserbase.com" &&
[
"/devtools/inspector.html",
"/devtools-fullscreen/inspector.html",
"/devtools-fullscreen-compiled/index.html",
].includes(url.pathname);
} catch {
return false;
}
}

export function isTrustedRenderer(
event: IpcMainEvent | IpcMainInvokeEvent,
mainWindow: BrowserWindow
): boolean {
return !mainWindow.isDestroyed() &&
event.sender === mainWindow.webContents &&
event.senderFrame === mainWindow.webContents.mainFrame &&
event.senderFrame.url === rendererUrl;
}

export function secureWindow(mainWindow: BrowserWindow): void {
const contents = mainWindow.webContents;
contents.setWindowOpenHandler(() => ({ action: "deny" }));
contents.on("will-navigate", (event) => event.preventDefault());
contents.on("will-redirect", (event) => event.preventDefault());
contents.on("will-frame-navigate", (event) => event.preventDefault());

// Remote pages run in Browserbase. The local guest only needs to display live view.
const liveViewSession = session.fromPartition(liveViewPartition);
// webview.src/loadURL changes do not emit will-navigate. Check the request too.
liveViewSession.webRequest.onBeforeRequest((details, callback) => {
callback({ cancel: details.resourceType === "mainFrame" && !isLiveViewUrl(details.url) });
});
for (const localSession of [contents.session, liveViewSession]) {
localSession.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
localSession.setPermissionCheckHandler(() => false);
}

contents.on("will-attach-webview", (event, preferences, params) => {
if (!isLiveViewUrl(params.src) || params.partition !== liveViewPartition) {
event.preventDefault();
return;
}

delete preferences.preload;
preferences.nodeIntegration = false;
preferences.nodeIntegrationInSubFrames = false;
preferences.nodeIntegrationInWorker = false;
preferences.contextIsolation = true;
preferences.sandbox = true;
preferences.webSecurity = true;
preferences.allowRunningInsecureContent = false;
preferences.webviewTag = false;
preferences.experimentalFeatures = false;
delete params.allowpopups;
});

contents.on("did-attach-webview", (_event, guest) => {
guest.setWindowOpenHandler(() => ({ action: "deny" }));
guest.on("will-navigate", (event, url) => {
if (!isLiveViewUrl(url)) event.preventDefault();
});
guest.on("will-redirect", (event, url) => {
if (!isLiveViewUrl(url)) event.preventDefault();
});
});
}
11 changes: 6 additions & 5 deletions src/renderer/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ class App {
private bookmarksBar!: BookmarksBar;
private contentArea!: ContentArea;
private downloadsBar!: DownloadsBar;
private statusBar!: HTMLElement;
private statusMessage!: HTMLElement;
private statusBar: HTMLElement | null = null;
private statusMessage: HTMLElement | null = null;

constructor() {
this.initialize();
Expand Down Expand Up @@ -41,8 +41,8 @@ class App {
this.downloadsBar = new DownloadsBar();

// Get status bar elements
this.statusBar = document.getElementById("status-bar") as HTMLElement;
this.statusMessage = document.getElementById("status-message") as HTMLElement;
this.statusBar = document.getElementById("status-bar");
this.statusMessage = document.getElementById("status-message");

// Setup status bar close button
const closeStatusBtn = document.getElementById("btn-close-status");
Expand Down Expand Up @@ -79,6 +79,7 @@ class App {
}

public showStatus(message: string, type: "info" | "error" = "info"): void {
if (!this.statusMessage || !this.statusBar) return;
this.statusMessage.textContent = message;
this.statusBar.classList.remove("hidden", "error");
if (type === "error") {
Expand All @@ -87,7 +88,7 @@ class App {
}

public hideStatus(): void {
this.statusBar.classList.add("hidden");
this.statusBar?.classList.add("hidden");
}

// Public getters for components if needed
Expand Down
6 changes: 5 additions & 1 deletion src/renderer/components/BookmarksBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ export class BookmarksBar {
.map(
(bookmark) => `
<a href="#" class="bookmark-item" data-url="${this.escapeAttr(bookmark.url)}">
<img src="https://www.google.com/s2/favicons?domain=${this.getDomain(bookmark.url)}&sz=16" alt="" class="bookmark-favicon" onerror="this.style.visibility='hidden'">
<img src="https://www.google.com/s2/favicons?domain=${this.getDomain(bookmark.url)}&sz=16" alt="" class="bookmark-favicon">
<span>${this.escapeHtml(bookmark.title)}</span>
</a>
`
)
.join("");

this.container.querySelectorAll<HTMLImageElement>(".bookmark-favicon").forEach((image) => {
image.addEventListener("error", () => { image.style.visibility = "hidden"; });
});

// Add click handlers
this.container.querySelectorAll(".bookmark-item").forEach((item) => {
item.addEventListener("click", (e) => {
Expand Down
Loading