diff --git a/package.json b/package.json index 0e90a37..265b9e3 100644 --- a/package.json +++ b/package.json @@ -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 .", diff --git a/src/main/index.ts b/src/main/index.ts index c33384b..b8480b6 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -11,7 +11,7 @@ * @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"; @@ -19,6 +19,7 @@ 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 | null = null; @@ -332,11 +333,13 @@ async function createWindow(): Promise { 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(); @@ -395,23 +398,6 @@ async function createWindow(): Promise { } } -// 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(); @@ -435,7 +421,6 @@ app.whenReady().then(async () => { } createApplicationMenu(); - setupContentSecurityPolicy(); await createWindow(); // Handle theme changes diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 966bde1..7a78d6a 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -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; @@ -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 }; @@ -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 }; @@ -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 }; @@ -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 }; @@ -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); @@ -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; } @@ -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 }; @@ -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 }; @@ -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 }; @@ -117,16 +132,16 @@ 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 { @@ -134,35 +149,35 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void { } }); - 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); }); } diff --git a/src/main/security.ts b/src/main/security.ts new file mode 100644 index 0000000..55e0a7f --- /dev/null +++ b/src/main/security.ts @@ -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(); + }); + }); +} diff --git a/src/renderer/app.ts b/src/renderer/app.ts index 9e84136..cb71ef3 100644 --- a/src/renderer/app.ts +++ b/src/renderer/app.ts @@ -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(); @@ -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"); @@ -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") { @@ -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 diff --git a/src/renderer/components/BookmarksBar.ts b/src/renderer/components/BookmarksBar.ts index 1a36325..99c5013 100644 --- a/src/renderer/components/BookmarksBar.ts +++ b/src/renderer/components/BookmarksBar.ts @@ -38,13 +38,17 @@ export class BookmarksBar { .map( (bookmark) => ` - + ${this.escapeHtml(bookmark.title)} ` ) .join(""); + this.container.querySelectorAll(".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) => { diff --git a/src/renderer/components/ContentArea.ts b/src/renderer/components/ContentArea.ts index bbaa883..ab56c61 100644 --- a/src/renderer/components/ContentArea.ts +++ b/src/renderer/components/ContentArea.ts @@ -53,7 +53,7 @@ export class ContentArea { // Listen for debug URL changes (tab switching) window.electronAPI.onDebugUrlChanged((url: string) => { - console.log("[ContentArea] Debug URL changed:", url); + console.log("[ContentArea] Debug URL changed"); this.updateDebugView(url); }); @@ -78,7 +78,7 @@ export class ContentArea { }); this.debugView.addEventListener("did-fail-load", (event) => { - console.error("[ContentArea] Webview failed to load:", event); + console.error("[ContentArea] Webview failed to load:", (event as Electron.DidFailLoadEvent).errorCode); this.showError(`Failed to load remote browser view: ${(event as any).errorDescription || 'Unknown error'}`); }); @@ -86,10 +86,6 @@ export class ContentArea { console.log("[ContentArea] Webview DOM ready"); }); - this.debugView.addEventListener("console-message", (event) => { - console.log("[Webview Console]", (event as any).message); - }); - this.element?.addEventListener("wheel", (event) => this.handleWheel(event), { passive: false, capture: true, @@ -143,7 +139,7 @@ export class ContentArea { this.showLoading(); console.log("[ContentArea] Fetching debug URL..."); const url = await window.electronAPI.getDebugUrl(); - console.log("[ContentArea] Got debug URL:", url); + console.log("[ContentArea] Received debug URL"); if (url) { // Set a timeout to hide loading even if load event doesn't fire @@ -157,7 +153,7 @@ export class ContentArea { this.debugView.src = url; this.isLoaded = true; - console.log("[ContentArea] Debug webview src set to:", url); + console.log("[ContentArea] Debug webview source updated"); // Check dimensions after a short delay setTimeout(() => { @@ -212,11 +208,14 @@ export class ContentArea {

Connection Error

${this.escapeHtml(message)}

- `; + this.loadingOverlay.querySelector(".retry-connection")?.addEventListener("click", () => { + window.location.reload(); + }); } } @@ -233,7 +232,7 @@ export class ContentArea { } if (url && url !== this.debugView.src) { - console.log("[ContentArea] Updating debug view to:", url); + console.log("[ContentArea] Updating debug view"); this.showLoading("Loading tab..."); this.debugView.src = url; } diff --git a/src/renderer/components/TabBar.ts b/src/renderer/components/TabBar.ts index 02bec83..6513fd0 100644 --- a/src/renderer/components/TabBar.ts +++ b/src/renderer/components/TabBar.ts @@ -42,22 +42,32 @@ export class TabBar { } private render(): void { - this.tabsContainer.innerHTML = this.tabs - .map( - (tab) => ` -
- "}" alt="" onerror="this.style.visibility='hidden'"> - ${this.escapeHtml(tab.title || "New Tab")} - -
- ` - ) - .join(""); + this.tabsContainer.replaceChildren(...this.tabs.map((tab) => { + const element = document.createElement("div"); + element.className = `tab ${tab.active ? "active" : ""}`; + element.dataset.tabId = tab.id; + + const favicon = document.createElement("img"); + favicon.className = "tab-favicon"; + favicon.alt = ""; + favicon.src = tab.favicon || "data:image/svg+xml,"; + favicon.addEventListener("error", () => { favicon.style.visibility = "hidden"; }); + + const title = document.createElement("span"); + title.className = "tab-title"; + title.textContent = tab.title || "New Tab"; + + const close = document.createElement("button"); + close.className = "tab-close"; + close.dataset.closeTab = tab.id; + close.title = "Close tab"; + close.innerHTML = ` + + + `; + element.append(favicon, title, close); + return element; + })); // Add click handlers for tabs this.tabsContainer.querySelectorAll(".tab").forEach((tabEl) => { @@ -85,12 +95,6 @@ export class TabBar { }); } - private escapeHtml(text: string): string { - const div = document.createElement("div"); - div.textContent = text; - return div.innerHTML; - } - public getTabs(): TabInfo[] { return this.tabs; } diff --git a/src/renderer/index.html b/src/renderer/index.html index c8143bf..7f0b625 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -3,7 +3,7 @@ - + Desktop Browserbase @@ -132,7 +132,7 @@
- +

Connecting to Browserbase...

diff --git a/tests/electron-security.cjs b/tests/electron-security.cjs new file mode 100644 index 0000000..981bea6 --- /dev/null +++ b/tests/electron-security.cjs @@ -0,0 +1,159 @@ +// Run after npm run build: electron tests/electron-security.cjs +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { app, BrowserWindow, session } = require('electron'); +const { sessionManager } = require('../dist/main/session'); +const { IPC_CHANNELS } = require('../dist/shared/types'); +const config = require('../dist/main/config'); + +const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-security-test-')); +app.setPath('userData', userData); +// Keep cloud session provisioning out of this local Electron boundary test. +process.env.BROWSERBASE_API_KEY = 'synthetic-test-key'; +delete process.env.BROWSERBASE_AUTOMATION_SERVER; +config.loadEnvironmentConfig = () => []; +sessionManager.initialize = async () => ({ id: 'synthetic-session' }); +sessionManager.getDebugUrl = async () => 'https://www.browserbase.com/devtools-fullscreen/inspector.html'; +let newTabs = 0; +sessionManager.newTab = async () => { newTabs++; }; +let mainWindow; +let guest; +let done = false; +let externalFixtureRequests = 0; +const timeout = setTimeout(() => { console.error('Electron security test timed out'); app.exit(1); }, 20000); + +async function until(check) { + for (let i = 0; i < 100; i++) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error('Timed out waiting for Electron state'); +} + +app.on('web-contents-created', (_event, contents) => { + if (contents.getType() === 'webview') guest = contents; +}); +app.whenReady().then(async () => { + const fixtureSession = session.fromPartition('persist:browserbase'); + fixtureSession.protocol.handle('https', (request) => { + if (!request.url.startsWith('https://www.browserbase.com/')) externalFixtureRequests++; + // The public fullscreen inspector redirects to this compiled viewer document. + if (new URL(request.url).pathname === '/devtools-fullscreen/inspector.html') { + return new Response(null, { status: 308, headers: { location: 'https://www.browserbase.com/devtools-fullscreen-compiled/index.html' } }); + } + return new Response(` + Security test fixture +

Desktop Browserbase

Local security test fixture

+

The live-view guest is isolated from the desktop shell.

+ `, { + headers: { 'content-type': 'text/html' }, + }); + }); + try { + await until(() => { mainWindow = BrowserWindow.getAllWindows()[0]; return mainWindow; }); + await until(() => guest && guest.getURL().startsWith('https://www.browserbase.com/') && !guest.isLoading()); + assert.equal(new URL(guest.getURL()).pathname, '/devtools-fullscreen-compiled/index.html'); + const shell = mainWindow.webContents; + await until(() => shell.executeJavaScript('!!window.app && !!window.electronAPI')); + assert.equal(shell.getLastWebPreferences().sandbox, true); + assert.equal(shell.getLastWebPreferences().contextIsolation, true); + assert.equal(await shell.executeJavaScript('typeof require'), 'undefined'); + assert.equal((await shell.executeJavaScript('window.electronAPI.newTab()')).success, true); + assert.equal(newTabs, 1); + + // Untrusted remote metadata remains text/attributes, even if it contains markup. + shell.send(IPC_CHANNELS.TABS_UPDATED, [{ id: 'tab-0', targetId: 'test', title: '', url: 'https://example.test', favicon: 'x" onerror="window.__injected=true', active: true }]); + await until(() => shell.executeJavaScript('document.querySelector(".tab-title").textContent.includes("onerror")')); + assert.equal(await shell.executeJavaScript('!!window.__injected || !!document.querySelector(".tab-title img") || !!document.querySelector(".tab-favicon[onerror]")'), false); + assert.equal(await shell.executeJavaScript(`(() => { const script=document.createElement('script'); script.textContent='window.__inline=true'; document.body.append(script); return !!window.__inline; })()`), false); + assert.equal(await shell.executeJavaScript(`(() => { try { eval('1'); return false; } catch { return true; } })()`), true); + + const originalUrl = shell.getURL(); + await shell.executeJavaScript(`window.location.href = 'https://example.test/'; void 0;`); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.equal(shell.getURL(), originalUrl); + assert.equal(await shell.executeJavaScript(`window.open('https://example.test/') === null`), true); + + // A second window carrying the same preload still cannot call the shell's IPC. + const outsider = new BrowserWindow({ show: false, webPreferences: { preload: path.resolve('dist/main/preload.js'), sandbox: true, contextIsolation: true } }); + await outsider.loadURL('data:text/html,Untrusted caller'); + assert.match(await outsider.webContents.executeJavaScript('window.electronAPI.newTab().then(() => "allowed", error => error.message)'), /Untrusted IPC sender/); + assert.equal(newTabs, 1); + const initialZoom = shell.getZoomLevel(); + await outsider.webContents.executeJavaScript('window.electronAPI.zoomIn()'); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(shell.getZoomLevel(), initialZoom); + outsider.destroy(); + + // A permitted live-view guest never gets a preload, Node, or popup permissions. + const guestPreferences = guest.getLastWebPreferences(); + assert.equal(guestPreferences.sandbox, true); + assert.equal(guestPreferences.nodeIntegration, false); + assert.equal(guestPreferences.contextIsolation, true); + assert.ok(!guestPreferences.preload); + assert.equal(await guest.executeJavaScript('typeof require'), 'undefined'); + assert.equal(await guest.executeJavaScript('typeof window.electronAPI'), 'undefined'); + assert.equal(await guest.executeJavaScript(`window.open('https://example.test/') === null`), true); + assert.equal(await guest.executeJavaScript('Notification.requestPermission()'), 'denied'); + const guestUrl = guest.getURL(); + await guest.executeJavaScript(`window.location.href = 'https://example.test/'; void 0;`); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.equal(guest.getURL(), guestUrl); + + let rejectedAttachment = false; + shell.once('will-attach-webview', (event) => { rejectedAttachment = event.defaultPrevented; }); + await shell.executeJavaScript(`(() => { const view=document.createElement('webview'); view.setAttribute('partition','persist:browserbase'); view.setAttribute('preload', ${JSON.stringify(path.resolve('dist/main/preload.js'))}); view.setAttribute('nodeintegration',''); view.src='https://example.test/'; document.body.append(view); })()`); + await until(() => rejectedAttachment); + assert.equal(rejectedAttachment, true); + + const navigationError = await shell.executeJavaScript(`document.getElementById('live-view-frame').loadURL('https://example.test/').then(() => 'allowed', error => error.message)`); + assert.match(navigationError, /ERR_FAILED|ERR_BLOCKED_BY_CLIENT/); + assert.equal(externalFixtureRequests, 0); + await shell.executeJavaScript(`document.getElementById('live-view-frame').loadURL(${JSON.stringify(guestUrl)})`); + await until(() => guest.getURL() === guestUrl && !guest.isLoading()); + + await shell.executeJavaScript(`window.app.showStatus('Synthetic connection error', 'error'); window.app.hideStatus(); window.app.getContentArea().showError('')`); + assert.equal(await shell.executeJavaScript('!!document.querySelector(".retry-connection") && !document.querySelector(".retry-connection").hasAttribute("onclick") && !document.querySelector("#loading-overlay img")'), true); + await shell.executeJavaScript('window.app.getContentArea().hideLoading()'); + + shell.send(IPC_CHANNELS.TABS_UPDATED, [{ id: 'tab-0', targetId: 'test', title: 'Security test fixture', url: 'https://example.test', active: true }]); + await until(() => shell.executeJavaScript('document.querySelector(".tab-title").textContent === "Security test fixture"')); + let hardenedGuest; + shell.once('did-attach-webview', (_event, attached) => { hardenedGuest = attached; }); + await shell.executeJavaScript(`(() => { + const view=document.createElement('webview'); + view.id='hostile-options-test'; + view.setAttribute('partition','persist:browserbase'); + view.setAttribute('preload', ${JSON.stringify(path.resolve('dist/main/preload.js'))}); + view.setAttribute('nodeintegration',''); + view.setAttribute('allowpopups',''); + view.setAttribute('webpreferences','contextIsolation=no,sandbox=no,webSecurity=no'); + view.src=${JSON.stringify(guestUrl)}; + document.body.append(view); + })()`); + await until(() => hardenedGuest && !hardenedGuest.isLoading()); + const hardenedPreferences = hardenedGuest.getLastWebPreferences(); + assert.equal(hardenedPreferences.sandbox, true); + assert.equal(hardenedPreferences.nodeIntegration, false); + assert.equal(hardenedPreferences.contextIsolation, true); + assert.equal(hardenedPreferences.webSecurity, true); + assert.ok(!hardenedPreferences.preload); + assert.equal(await hardenedGuest.executeJavaScript('typeof window.electronAPI'), 'undefined'); + await shell.executeJavaScript(`document.getElementById('hostile-options-test').remove()`); + await new Promise((resolve) => setTimeout(resolve, 250)); + if (process.env.DESKTOP_TEST_SCREENSHOT) fs.writeFileSync(process.env.DESKTOP_TEST_SCREENSHOT, (await shell.capturePage()).toPNG()); + done = true; + console.log('PASS: sandboxed preload, trusted IPC, CSP, escaped metadata, navigation, popups, guest attachment and denied permissions'); + } catch (error) { + console.error(error); + } finally { + clearTimeout(timeout); + for (const window of BrowserWindow.getAllWindows()) window.destroy(); + await fixtureSession.protocol.unhandle('https'); + fs.rmSync(userData, { recursive: true, force: true }); + app.exit(done ? 0 : 1); + } +}); +require('../dist/main/index'); diff --git a/tests/security-url.test.cjs b/tests/security-url.test.cjs new file mode 100644 index 0000000..ea8a77b --- /dev/null +++ b/tests/security-url.test.cjs @@ -0,0 +1,28 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const { isLiveViewUrl } = require('../dist/main/security'); + +test('live-view URL validation rejects scheme, credential, port, and hostname confusion', () => { + for (const value of [ + 'https://www.browserbase.com/devtools-fullscreen/inspector.html', + 'https://www.browserbase.com/devtools/inspector.html', + 'https://www.browserbase.com/devtools-fullscreen-compiled/index.html', + ]) assert.equal(isLiveViewUrl(value), true, value); + for (const value of [ + 'file:///tmp/index.html', + 'javascript:alert(1)', + 'data:text/html,example', + 'http://www.browserbase.com/', + 'https://www.browserbase.com.example.test/', + 'https://example.test/?url=https://www.browserbase.com', + 'https://user:password@www.browserbase.com/', + 'https://www.browserbase.com:8443/', + 'https://browserbase.com@example.test/', + 'https://fakebrowserbase.com/', + 'https://www.browserbase.com/', + 'https://www.browserbase.com/blog/', + 'https://docs.browserbase.com/devtools/inspector.html', + 'https://www.browserbase.com/devtools/inspector.html/extra', + 'not a URL', + ]) assert.equal(isLiveViewUrl(value), false, value); +});