import { app, BrowserWindow, session, shell, clipboard } from 'electron'; import { randomUUID } from 'node:crypto'; import { Store } from './store.mjs'; import { Filters } from './filters.mjs'; import { createGateway } from './gateway.mjs'; import { AgentController } from './agent.mjs'; import { loadFavicon } from './favicon.mjs'; import { listCookies, removeCookie } from './web-data.mjs'; import { addressInput, webUrl, shortText, REMOTE_PREFERENCES } from './policy.mjs'; import { FrameDelivery } from './frame-delivery.mjs'; export async function createEngine({ directory, emit = () => {}, canEmitFrame = () => true, allowedTestHosts = new Set(), openExternal = url => shell.openExternal(url) }) { const store = new Store(directory); const sessions = new Map(), tabs = new Map(); let filters = new Filters(); await filters.load(store.data.settings.personalRules, store.data.settings.filterLists, { directory }); let stopped = false; const runtimeId = randomUUID(); let revision = 0; const tab = id => { const found = tabs.get(id); if (!found) throw new Error('Unknown browser tab.'); return found; }; const pageFocusStates = new WeakMap(); async function focusPage(wc, enabled) { // Hidden offscreen windows cannot gain native focus. Chromium still needs it to paint the caret. if (!wc.debugger.isAttached()) { if (!enabled) return; wc.debugger.attach('1.3'); pageFocusStates.delete(wc); } if (pageFocusStates.get(wc) === enabled) return; await wc.debugger.sendCommand('Emulation.setFocusEmulationEnabled', { enabled }); pageFocusStates.set(wc, enabled); if (enabled) wc.focus(); } function emulateViewport(item) { if (!item.viewport) return; const { width, height } = item.viewport, scale = item.scale; item.view.setContentSize(Math.round(width * scale), Math.round(height * scale)); item.view.webContents.enableDeviceEmulation({ screenPosition: 'desktop', screenSize: { width, height }, deviceScaleFactor: scale, viewPosition: { x: 0, y: 0 }, viewSize: { width, height }, scale }); item.view.webContents.invalidate(); } const agent = new AgentController(tab); const snapshot = () => ({ runtimeId, revision: ++revision, profiles: structuredClone(store.data.profiles), settings: structuredClone(store.data.settings), bookmarks: structuredClone(store.data.bookmarks), tabs: [...tabs.values()].map(item => ({ id: item.id, profileId: item.profileId, title: item.title, favicon: item.favicon, url: item.view.webContents.getURL(), loading: item.view.webContents.isLoading(), blocked: item.blocked, find: item.find, canBack: item.view.webContents.navigationHistory.canGoBack(), canForward: item.view.webContents.navigationHistory.canGoForward() })), }); let timer; const changed = () => { if (stopped || timer) return; timer = setTimeout(() => { timer = undefined; if (!stopped) emit({ event: 'state', state: snapshot() }); }, 80); }; const login = (event, _contents, _details, auth, callback) => { event.preventDefault(); const entry = [...sessions.values()].find(item => item.gateway.port === auth.port); if (entry && auth.isProxy && auth.host === '127.0.0.1') callback(entry.gateway.username, entry.gateway.password); else callback(); }; app.on('login', login); const enabled = url => { try { return store.data.settings.adblock && !store.data.exceptions.includes(new URL(url).origin); } catch { return store.data.settings.adblock; } }; async function profile(id) { store.profile(id); if (sessions.has(id)) return sessions.get(id).session; const ses = session.fromPartition(`persist:runestone-${id}`); const gateway = await createGateway({ allowedTestHosts }); sessions.set(id, { session: ses, gateway }); await ses.setProxy({ mode: 'fixed_servers', proxyRules: `http://127.0.0.1:${gateway.port}`, proxyBypassRules: '<-loopback>' }); ses.setPermissionRequestHandler((_wc, _permission, done) => done(false)); ses.setPermissionCheckHandler(() => false); ses.setDevicePermissionHandler(() => false); ses.setDisplayMediaRequestHandler((_request, done) => done({})); ses.on('will-download', (event, download, contents) => { const current = [...tabs.values()].find(item => item.view.webContents === contents); const url = download.getURLChain()[0]; if (!current?.downloads.delete(url)) { event.preventDefault(); return; } download.setSaveDialogOptions({ title: 'Save download', defaultPath: download.getFilename() }); download.once('done', (_event, state) => { if (state === 'interrupted') emit({ event: 'error', tabId: current.id, message: 'The download failed. Try again.' }); }); }); ses.webRequest.onBeforeRequest(async (details, done) => { try { if (details.url === 'about:blank') return done({ cancel: false }); webUrl(details.url.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'), { blank: false }); const current = [...tabs.values()].find(item => item.view.webContents.id === details.webContentsId); const sourceUrl = details.frame?.url || details.initiator || current?.view.webContents.getURL() || details.url; const cancel = enabled(sourceUrl) && await filters.match({ url: details.url, sourceUrl, type: details.resourceType }); if (cancel && current) { current.blocked++; changed(); } done({ cancel }); } catch { done({ cancel: true }); } }); return ses; } async function cosmetics(item) { const wc = item.view.webContents; if (wc.isDestroyed() || !enabled(wc.getURL()) || !/^https?:/.test(wc.getURL())) return; const epoch = item.epoch; try { const selectors = await wc.executeJavaScriptInIsolatedWorld(901, [{ code: `(() => { const nodes = [...document.querySelectorAll('[class], [id]')].slice(0, 3000); return { classes: [...new Set(nodes.flatMap(n => [...n.classList]))].slice(0, 3000), ids: nodes.map(n => n.id).filter(Boolean) }; })()` }]); const css = await filters.cosmetics({ url: wc.getURL(), ...selectors }); if (css && item.epoch === epoch) await wc.insertCSS(css); } catch { /* Navigation can destroy the isolated world. */ } } async function createTab(profileId = store.data.profiles[0].id, id = randomUUID(), url = store.data.settings.homepage || 'about:blank') { url = webUrl(url); if (tabs.size >= 24) throw new Error('The browser tab limit is 24.'); const ses = await profile(profileId); const win = new BrowserWindow({ width: 1000, height: 700, show: false, frame: false, webPreferences: { ...REMOTE_PREFERENCES, session: ses, offscreen: { deviceScaleFactor: 1 }, backgroundThrottling: false } }); win.setMenu(null); const item = { id, profileId, epoch: 0, view: win, title: 'Browser', favicon: null, iconRequest: null, blocked: 0, find: null, findRequest: 0, delivery: new FrameDelivery(), context: null, downloads: new Set(), settle: null, retryFrame: null, latestImage: null, latestScale: 1, scale: 1 }; tabs.set(item.id, item); const wc = win.webContents; wc.setFrameRate(60); wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp'); wc.setWindowOpenHandler(details => { try { emit({ event: 'open-link', tabId: id, url: webUrl(details.url, { blank: false }) }); } catch { /* Reject unsupported addresses. */ } return { action: 'deny' }; }); wc.on('context-menu', (_event, params) => { const token = randomUUID(); const safe = value => { try { return webUrl(value, { blank: false }); } catch { return ''; } }; item.context = { token, epoch: item.epoch, x: params.x / item.scale, y: params.y / item.scale, linkURL: safe(params.linkURL), srcURL: safe(params.srcURL), hasImageContents: params.hasImageContents, isEditable: params.isEditable, selectionText: params.selectionText.slice(0, 100000), editFlags: params.editFlags }; emit({ event: 'context-menu', tabId: id, ...item.context }); }); wc.on('will-attach-webview', event => event.preventDefault()); const navigation = (event, url) => { try { webUrl(url); } catch { event.preventDefault(); } }; wc.on('will-navigate', navigation); wc.on('will-redirect', navigation); wc.on('will-frame-navigate', event => { if (!['about:blank', 'about:srcdoc'].includes(event.url)) navigation(event, event.url); }); wc.on('did-start-navigation', (_event, _url, inPlace, main) => { if (main && !inPlace) { item.iconRequest?.abort(); item.favicon = null; item.epoch++; item.blocked = 0; item.find = null; item.findRequest = 0; agent.revokeAll(); } changed(); }); wc.on('found-in-page', (_event, result) => { if (item.find && result.requestId === item.findRequest) { item.find = { ...item.find, matches: result.matches, activeMatch: result.activeMatchOrdinal, pending: !result.finalUpdate }; changed(); } }); wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); }); wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); }); wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); }); wc.on('page-favicon-updated', (_event, urls) => { item.iconRequest?.abort(); const request = new AbortController(); item.iconRequest = request; void loadFavicon(urls, (url, options) => ses.fetch(url, options), request.signal).then(icon => { if (request.signal.aborted || stopped || wc.isDestroyed()) return; item.favicon = icon; changed(); }); }); wc.on('destroyed', () => { item.iconRequest?.abort(); clearTimeout(item.settle); clearTimeout(item.retryFrame); }); wc.on('did-stop-loading', () => { changed(); void cosmetics(item); }); wc.on('did-finish-load', () => emulateViewport(item)); wc.on('did-fail-load', (_event, code, _description, _url, main) => { if (main && code !== -3) emit({ event: 'error', tabId: item.id, message: `Page load failed (${code}).` }); }); wc.on('paint', (_event, _dirty, image) => { // Offscreen frames can be one pixel larger than the viewport. The host shows each frame pixel on one screen pixel, so crop the extra edge. const size = image.getSize(), width = Math.min(size.width, Math.round((item.viewport?.width ?? size.width) * item.scale)), height = Math.min(size.height, Math.round((item.viewport?.height ?? size.height) * item.scale)); item.latestImage = width < size.width || height < size.height ? image.crop({ x: 0, y: 0, width, height }) : image; item.latestScale = item.scale; clearTimeout(item.settle); clearTimeout(item.retryFrame); const frame = (lossless = false) => { clearTimeout(item.retryFrame); if (stopped || wc.isDestroyed() || !wc.isPainting()) return; if (!canEmitFrame() || !item.delivery.canSend()) { // Retain the latest static frame until the host can decode it. item.retryFrame = setTimeout(() => frame(lossless), 32); return; } const data = lossless ? item.latestImage.toPNG() : item.latestImage.toJPEG(90); if (data.length && data.length <= 4_000_000) emit({ event: 'frame', tabId: item.id, frameId: item.delivery.sent(), mime: lossless ? 'image/png' : 'image/jpeg', data: data.toString('base64'), scale: item.latestScale, ...item.latestImage.getSize() }); }; frame(); // Send a lossless final frame for sharp text when the page stops changing. item.settle = setTimeout(() => frame(true), 140); }); // Navigation reports completion through events and must not hold the command queue. void wc.loadURL(url).catch(() => {}); changed(); return item.id; } function closeTab(id) { const current = tab(id); tabs.delete(id); agent.revokeAll(); current.view.destroy(); changed(); } async function command(name, args = {}) { if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('Invalid browser arguments.'); switch (name) { case 'state': return snapshot(); case 'frameAck': tab(args.tabId).delivery.acknowledge(args.frameId); return null; case 'newTab': return { tabId: await createTab(args.profileId, undefined, args.url) }; case 'closeTab': closeTab(args.tabId); break; case 'navigate': { const current = tab(args.tabId), url = addressInput(args.input, store.data.settings.search); void current.view.webContents.loadURL(url).catch(() => {}); break; } case 'back': { const history = tab(args.tabId).view.webContents.navigationHistory; if (history.canGoBack()) history.goBack(); break; } case 'forward': { const history = tab(args.tabId).view.webContents.navigationHistory; if (history.canGoForward()) history.goForward(); break; } case 'reload': tab(args.tabId).view.webContents.reload(); break; case 'stop': tab(args.tabId).view.webContents.stop(); break; case 'find': { const current = tab(args.tabId), wc = current.view.webContents; if (typeof args.text !== 'string' || args.text.length > 1000) throw new Error('Find text must contain at most 1000 characters.'); if (!args.text) { wc.stopFindInPage('clearSelection'); current.find = null; current.findRequest = 0; break; } const fresh = current.find?.text !== args.text || args.next !== true; current.find = { text: args.text, matches: current.find?.matches ?? 0, activeMatch: 0, pending: true }; current.findRequest = wc.findInPage(args.text, { forward: args.forward !== false, findNext: fresh }); break; } case 'stopFind': { const current = tab(args.tabId); current.find = null; current.findRequest = 0; current.view.webContents.stopFindInPage('clearSelection'); break; } case 'openExternal': await openExternal(webUrl(tab(args.tabId).view.webContents.getURL(), { blank: false })); break; case 'resize': { const current = tab(args.tabId); if (!Number.isInteger(args.width) || !Number.isInteger(args.height) || args.width < 100 || args.height < 100 || args.width > 5120 || args.height > 3200) throw new Error('Invalid browser size.'); const scale = Number(args.scale ?? 1); if (!Number.isFinite(scale) || scale < 1 || scale > 3) throw new Error('Invalid browser scale.'); current.scale = scale; current.viewport = { width: args.width, height: args.height }; emulateViewport(current); current.delivery.clear(); current.view.webContents.invalidate(); return null; } case 'visible': { const item = tab(args.tabId), wc = item.view.webContents; item.delivery.clear(); if (args.visible === true) { wc.startPainting(); wc.invalidate(); } else { await focusPage(wc, false); wc.stopPainting(); clearTimeout(item.settle); clearTimeout(item.retryFrame); } return null; } case 'focus': { if (typeof args.focused !== 'boolean') throw new Error('Invalid browser focus.'); await focusPage(tab(args.tabId).view.webContents, args.focused); return null; } case 'insertText': { if (typeof args.text !== 'string' || args.text.length > 100000) throw new Error('Invalid browser text.'); const wc = tab(args.tabId).view.webContents; await focusPage(wc, true); await wc.insertText(args.text); return null; } case 'edit': { const wc = tab(args.tabId).view.webContents; if (!['undo', 'redo', 'cut', 'copy', 'paste', 'pasteAndMatchStyle', 'selectAll', 'delete'].includes(args.action)) throw new Error('Invalid edit action.'); wc[args.action](); return null; } case 'contextAction': { const current = tab(args.tabId), context = current.context, wc = current.view.webContents; if (!context || context.token !== args.token || context.epoch !== current.epoch) throw new Error('This page menu is no longer available.'); switch (args.action) { case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break; case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break; case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break; case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break; case 'saveImage': case 'saveLink': { const url = args.action === 'saveImage' ? context.srcURL : context.linkURL; if (!url) throw new Error('This item has no downloadable address.'); current.downloads.add(url); wc.downloadURL(url); break; } default: throw new Error('Invalid page menu action.'); } return null; } case 'input': { const current = tab(args.tabId), wc = current.view.webContents; const input = args.input; if (!input || !['mouseDown', 'mouseUp', 'mouseMove', 'mouseWheel', 'keyDown', 'keyUp', 'char'].includes(input.type)) throw new Error('Invalid browser input.'); const modifiers = Array.isArray(input.modifiers) ? input.modifiers.filter(value => ['shift', 'control', 'alt', 'meta'].includes(value)) : []; let event; if (input.type.startsWith('mouse')) { if (![input.x, input.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.'); event = { type: input.type, x: Math.round(input.x * current.scale), y: Math.round(input.y * current.scale), modifiers }; if (input.type === 'mouseWheel') Object.assign(event, { deltaX: Math.max(-2000, Math.min(2000, Number(input.deltaX) || 0)) * current.scale, deltaY: Math.max(-2000, Math.min(2000, Number(input.deltaY) || 0)) * current.scale, canScroll: true, hasPreciseScrollingDeltas: true }); else Object.assign(event, { button: ['left', 'middle', 'right'].includes(input.button) ? input.button : 'left', clickCount: input.clickCount === 2 ? 2 : 1 }); } else { if (typeof input.keyCode !== 'string' || input.keyCode.length > 32) throw new Error('Invalid key.'); event = { type: input.type, keyCode: input.keyCode, modifiers }; } // Pointer motion and wheel events must not repeatedly activate the native window. if (input.type === 'mouseDown' || input.type === 'keyDown' || input.type === 'char') await focusPage(wc, true); wc.sendInputEvent(event); return null; } case 'createProfile': store.createProfile(args.name); break; case 'renameProfile': store.profile(args.profileId).name = shortText(args.name, 60); store.save(); break; case 'prepareDuplicate': { store.profile(args.profileId); shortText(args.name, 60); if (store.data.profiles.length >= 20) throw new Error('The profile limit is 20.'); const cookies = []; for (const [profileId, entry] of sessions) cookies.push({ profileId, cookies: await entry.session.cookies.get({}) }); return { sourceId: args.profileId, id: randomUUID(), name: args.name.trim(), cookies, tabs: snapshot().tabs.map(item => ({ id: item.id, profileId: item.profileId, url: item.url })) }; } case 'commitDuplicate': { store.duplicateMetadata(args.sourceId, args.id, args.name); for (const entry of args.cookies || []) { const destinations = entry.profileId === args.sourceId ? [entry.profileId, args.id] : [entry.profileId]; for (const profileId of destinations) { const ses = await profile(profileId); for (const cookie of entry.cookies) { await ses.cookies.set({ url: `${cookie.secure ? 'https' : 'http'}://${cookie.domain.replace(/^\./, '')}${cookie.path}`, name: cookie.name, value: cookie.value, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, ...(!cookie.hostOnly ? { domain: cookie.domain } : {}), ...(cookie.expirationDate ? { expirationDate: cookie.expirationDate } : {}) }); } } } for (const saved of args.tabs || []) await createTab(saved.profileId, saved.id, saved.url); break; } case 'bookmark': { const current = tab(args.tabId); store.bookmark(current.profileId, current.view.webContents.getURL(), current.title); break; } case 'removeBookmark': store.data.bookmarks = store.data.bookmarks.filter(item => item.id !== args.id); store.save(); break; case 'settings': { const previous = structuredClone(store.data.settings); store.configure(args, { persist: false }); const next = new Filters(); try { await next.load(store.data.settings.personalRules, store.data.settings.filterLists, { directory, download: true }); store.save(); } catch (error) { await next.close(); store.configure(previous, { persist: false }); throw error; } await filters.close(); filters = next; for (const item of tabs.values()) item.view.webContents.reload(); break; } case 'webData': { const ses = await profile(args.profileId); return { profileId: args.profileId, cookies: await listCookies(ses), history: structuredClone(store.data.history.filter(item => item.profileId === args.profileId)) }; } case 'removeCookie': await removeCookie(await profile(args.profileId), args.id); break; case 'removeHistory': store.removeHistory(args.profileId, args.id); break; case 'clearData': { const ses = await profile(args.profileId); if (!['all', 'cache', 'cookies', 'history'].includes(args.kind)) throw new Error('Invalid data type.'); for (const item of [...tabs.values()]) if (item.profileId === args.profileId) closeTab(item.id); if (args.kind !== 'history') await ses.clearData(args.kind === 'all' ? {} : { dataTypes: [args.kind] }); if (args.kind === 'all' || args.kind === 'cookies') await ses.clearAuthCache(); if (args.kind === 'all' || args.kind === 'history') store.data.history = store.data.history.filter(item => item.profileId !== args.profileId); store.save(); break; } case 'agentSnapshot': { const current = tab(args.tabId), token = agent.grant(current.id, current.profileId); try { return await agent.snapshot(token, current.id); } finally { agent.revokeAll(); } } default: throw new Error('Unknown browser command.'); } changed(); return snapshot(); } async function shutdown() { if (stopped) return; stopped = true; clearTimeout(timer); agent.revokeAll(); app.removeListener('login', login); for (const item of tabs.values()) item.view.destroy(); tabs.clear(); for (const item of sessions.values()) { item.session.flushStorageData(); await item.session.cookies.flushStore(); await item.session.closeAllConnections(); await item.gateway.close(); } await filters.close(); } return { command, snapshot, shutdown, tabs, store }; }