RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
// Grants are issued only by trusted host UI code. Pages never receive tokens.
|
||||
export class AgentController {
|
||||
#grants = new Map();
|
||||
constructor(getTab, clock = Date.now) { this.getTab = getTab; this.clock = clock; }
|
||||
grant(tabId, profileId) {
|
||||
const tab = this.getTab(tabId);
|
||||
if (tab.profileId !== profileId) throw new Error('Profile mismatch.');
|
||||
const token = randomUUID();
|
||||
this.#grants.set(token, { tabId, profileId, epoch: tab.epoch, expires: this.clock() + 300_000 });
|
||||
return token;
|
||||
}
|
||||
revokeAll() { this.#grants.clear(); }
|
||||
authorized(token, tabId) {
|
||||
const grant = this.#grants.get(token);
|
||||
if (!grant || grant.tabId !== tabId || grant.expires <= this.clock()) throw new Error('Agent access is not authorized.');
|
||||
const tab = this.getTab(tabId);
|
||||
if (tab.profileId !== grant.profileId || tab.epoch !== grant.epoch) throw new Error('The document changed. Request a new grant.');
|
||||
return tab;
|
||||
}
|
||||
async snapshot(token, tabId) {
|
||||
const tab = this.authorized(token, tabId);
|
||||
const text = await tab.view.webContents.executeJavaScriptInIsolatedWorld(900, [{
|
||||
code: `(() => ({ title: document.title.slice(0, 200), text: (document.body?.innerText || '').slice(0, 24000) }))()`,
|
||||
}]);
|
||||
this.authorized(token, tabId);
|
||||
return { tabId, profileId: tab.profileId, document: tab.epoch, url: tab.view.webContents.getURL(), untrusted: true, ...text };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import https from 'node:https';
|
||||
import { resolvePublic, webUrl } from './policy.mjs';
|
||||
|
||||
export async function fetchList(address, redirects = 0, signal = AbortSignal.timeout(10_000)) {
|
||||
const url = new URL(webUrl(address, { blank: false }));
|
||||
if (url.protocol !== 'https:' || (url.port && url.port !== '443') || redirects > 3) throw new Error('Use a public HTTPS filter list.');
|
||||
const target = await new Promise((resolve, reject) => {
|
||||
const abort = () => reject(new Error('Filter download timed out.'));
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
if (signal.aborted) abort();
|
||||
resolvePublic(url.hostname).then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = https.get(url, {
|
||||
signal,
|
||||
lookup: (_host, options, callback) => options.all ? callback(null, [target]) : callback(null, target.address, target.family),
|
||||
headers: { 'Accept': 'text/plain', 'Accept-Encoding': 'identity' },
|
||||
}, response => {
|
||||
if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
|
||||
response.resume();
|
||||
try { fetchList(new URL(response.headers.location, url).href, redirects + 1, signal).then(resolve, reject); }
|
||||
catch (error) { reject(error); }
|
||||
return;
|
||||
}
|
||||
if (response.statusCode !== 200) { response.resume(); reject(new Error('Filter download failed.')); return; }
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
response.on('data', chunk => {
|
||||
size += chunk.length;
|
||||
if (size > 5_000_000) request.destroy(new Error('The filter list exceeds 5 MB.'));
|
||||
else chunks.push(chunk);
|
||||
});
|
||||
response.on('end', () => {
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
if (!text.trim() || /^\s*</.test(text)) reject(new Error('The download is not a filter list.'));
|
||||
else resolve(text);
|
||||
});
|
||||
response.on('error', reject);
|
||||
});
|
||||
request.setTimeout(10_000, () => request.destroy(new Error('Filter download timed out.')));
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { app } from 'electron';
|
||||
import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import { createEngine } from './engine.mjs';
|
||||
for (const flag of ['no-sandbox', 'disable-web-security', 'ignore-certificate-errors', 'remote-debugging-port', 'remote-debugging-pipe']) {
|
||||
if (app.commandLine.hasSwitch(flag)) throw new Error('Unsafe browser launch option.');
|
||||
}
|
||||
app.enableSandbox();
|
||||
app.commandLine.appendSwitch('disable-quic');
|
||||
app.commandLine.appendSwitch('disable-background-networking');
|
||||
app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE 127.0.0.1');
|
||||
app.commandLine.appendSwitch('force-webrtc-ip-handling-policy', 'disable_non_proxied_udp');
|
||||
app.on('window-all-closed', () => {});
|
||||
app.on('certificate-error', (event, _wc, _url, _error, _cert, done) => { event.preventDefault(); done(false); });
|
||||
app.on('select-client-certificate', (event, _wc, _url, _certs, done) => { event.preventDefault(); done(); });
|
||||
const root = app.commandLine.getSwitchValue('rs-browser-root');
|
||||
const port = Number(app.commandLine.getSwitchValue('rs-connect'));
|
||||
const token = process.env.RUNESTONE_BROWSER_TOKEN || '';
|
||||
delete process.env.RUNESTONE_BROWSER_TOKEN;
|
||||
if (!path.isAbsolute(root) || !Number.isInteger(port) || port < 1024 || port > 65535 || token.length < 32) app.exit(1);
|
||||
else {
|
||||
app.setPath('userData', root);
|
||||
app.whenReady().then(async () => {
|
||||
let writable = true;
|
||||
const socket = net.createConnection({ host: '127.0.0.1', port });
|
||||
socket.setEncoding('utf8'); socket.setNoDelay(true);
|
||||
socket.on('error', () => app.exit(1));
|
||||
const connected = new Promise(resolve => socket.once('connect', resolve));
|
||||
const emit = value => {
|
||||
if (socket.destroyed || (value.event === 'frame' && !writable)) return;
|
||||
writable = socket.write(JSON.stringify(value) + '\n');
|
||||
};
|
||||
socket.on('drain', () => { writable = true; });
|
||||
await connected;
|
||||
socket.write(JSON.stringify({ token }) + '\n');
|
||||
const engine = await createEngine({ directory: root, emit, canEmitFrame: () => writable && !socket.destroyed });
|
||||
let buffer = '', queued = 0, queue = Promise.resolve();
|
||||
socket.on('close', () => { void engine.shutdown().finally(() => app.exit(0)); });
|
||||
socket.on('data', chunk => {
|
||||
buffer += chunk;
|
||||
if (buffer.length > 6_000_000) { socket.destroy(); return; }
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\n')) >= 0) {
|
||||
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
||||
if (++queued > 128) { socket.destroy(); return; }
|
||||
queue = queue.then(async () => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(line);
|
||||
if (!Number.isSafeInteger(message.id) || message.id < 1) throw new Error('Invalid request.');
|
||||
if (message.command === 'shutdown') {
|
||||
await engine.shutdown();
|
||||
socket.write(JSON.stringify({ id: message.id, result: null }) + '\n', () => app.exit(0)); return;
|
||||
}
|
||||
emit({ id: message.id, result: await engine.command(message.command, message.args) });
|
||||
} catch (error) { emit({ id: message?.id, error: error.message }); }
|
||||
finally { queued--; }
|
||||
});
|
||||
}
|
||||
});
|
||||
// The host refuses an engine with another protocol. Keep PROTOCOL in src-tauri/src/browser_engine.rs the same.
|
||||
emit({ event: 'ready', protocol: 1, version: app.getVersion() });
|
||||
}).catch(error => { console.error(error); app.exit(1); });
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
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();
|
||||
}
|
||||
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
|
||||
let copied = null;
|
||||
const COPIED_PART = 3_000_000;
|
||||
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
|
||||
async function loadedImage(wc, url) {
|
||||
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
|
||||
await wc.debugger.sendCommand('Page.enable');
|
||||
try {
|
||||
const href = value => { try { return new URL(value).href; } catch { return ''; } };
|
||||
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
|
||||
for (const node of nodes) {
|
||||
// An image that opens as the page itself is the main resource of its frame.
|
||||
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
|
||||
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
|
||||
if (resource) {
|
||||
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
|
||||
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
|
||||
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
|
||||
return valid ? { mime: resource.mimeType, data } : null;
|
||||
}
|
||||
nodes.push(...(node.childFrames ?? []));
|
||||
}
|
||||
return null;
|
||||
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
|
||||
}
|
||||
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();
|
||||
}
|
||||
});
|
||||
// Each new document gets a renderer widget without device emulation. A page that replaces itself before it finishes
|
||||
// loading, as Google does, otherwise keeps a scale of 1 and grows when the next document finishes.
|
||||
wc.on('did-navigate', (_event, url) => { emulateViewport(item); 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) break;
|
||||
wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale));
|
||||
const image = context.srcURL ? await loadedImage(wc, context.srcURL).catch(() => null) : null;
|
||||
copied = image && { token: randomUUID(), tabId: current.id, url: context.srcURL, ...image };
|
||||
return copied && { copied: { token: copied.token, url: copied.url, mime: copied.mime, size: copied.data.length } };
|
||||
}
|
||||
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 'linkAt': {
|
||||
// A middle-click on a link opens it in a new tab. The isolated world keeps page scripts from changing the answer.
|
||||
if (![args.x, args.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.');
|
||||
const href = await tab(args.tabId).view.webContents.executeJavaScriptInIsolatedWorld(902, [{
|
||||
code: `document.elementFromPoint(${args.x}, ${args.y})?.closest('a[href], area[href]')?.href ?? ''`,
|
||||
}]).catch(() => '');
|
||||
try { return { url: href ? webUrl(href, { blank: false }) : null }; } catch { return { url: null }; }
|
||||
}
|
||||
case 'copiedImage': {
|
||||
// A part stays below the line limit of the host connection.
|
||||
if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) {
|
||||
throw new Error('The copied image is no longer available.');
|
||||
}
|
||||
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
|
||||
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : 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 };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { webUrl } from './policy.mjs';
|
||||
|
||||
const limit = 64 * 1024;
|
||||
const imageType = /^image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon|svg\+xml)$/;
|
||||
|
||||
export async function loadFavicon(urls, fetchImage, signal) {
|
||||
for (const url of [...new Set(urls)].slice(0, 8)) {
|
||||
if (signal.aborted) return null;
|
||||
try {
|
||||
if (typeof url !== 'string' || url.length > 90_000) continue;
|
||||
if (url.startsWith('data:image/')) {
|
||||
const comma = url.indexOf(',');
|
||||
const metadata = url.slice(5, comma).split(';');
|
||||
if (comma < 0 || !imageType.test(metadata[0])) continue;
|
||||
const bytes = Buffer.from(decodeURIComponent(url.slice(comma + 1)), metadata.includes('base64') ? 'base64' : 'utf8');
|
||||
if (bytes.length && bytes.length <= limit) return `data:${metadata[0]};base64,${bytes.toString('base64')}`;
|
||||
continue;
|
||||
}
|
||||
webUrl(url, { blank: false });
|
||||
const response = await fetchImage(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) });
|
||||
try {
|
||||
const type = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
|
||||
if (!response.ok || !imageType.test(type || '') || Number(response.headers.get('content-length')) > limit) continue;
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of response.body) {
|
||||
size += chunk.length;
|
||||
if (size > limit) throw new Error('Icon exceeds the size limit.');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
if (size) return `data:${type};base64,${Buffer.concat(chunks).toString('base64')}`;
|
||||
} finally {
|
||||
if (!response.body?.locked) await response.body?.cancel().catch(() => {});
|
||||
}
|
||||
} catch { /* Try the next icon when a request fails. */ }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
import { FiltersEngine, Request } from '@ghostery/adblocker';
|
||||
let engine;
|
||||
parentPort.on('message', ({ id, type, text, details }) => {
|
||||
try {
|
||||
let result;
|
||||
if (type === 'load') {
|
||||
if (text.length > 30_000_000) throw new Error('The combined filters exceed the limit.');
|
||||
const lines = text.split(/\r?\n/);
|
||||
const supported = lines.filter(line => !/##\+js\(|#@#\+js\(|#\$#|#\?#|:style\(|\$.*(?:csp|replace|urltransform)=/i.test(line) && line.length < 8192);
|
||||
engine = FiltersEngine.parse(supported.join('\n'), {
|
||||
loadCSPFilters: false, loadExtendedSelectors: false, enableHtmlFiltering: false,
|
||||
loadPreprocessors: false,
|
||||
});
|
||||
result = { excludedRules: lines.length - supported.length };
|
||||
} else if (type === 'match') {
|
||||
if (!engine) throw new Error('Filters are unavailable.');
|
||||
result = engine.match(Request.fromRawDetails(details)).match;
|
||||
} else if (type === 'cosmetics') {
|
||||
const request = Request.fromRawDetails({ url: details.url, type: 'main_frame' });
|
||||
const filters = engine.getCosmeticsFilters({
|
||||
url: details.url, hostname: request.hostname, domain: request.domain,
|
||||
classes: details.classes, ids: details.ids,
|
||||
getBaseRules: true, getRulesFromDOM: true, getRulesFromHostname: true,
|
||||
getInjectionRules: false, getExtendedRules: false,
|
||||
});
|
||||
result = filters.styles || '';
|
||||
// Never turn filter-list text into scripts or network-bearing CSS.
|
||||
if (/url\s*\(|@import|expression\s*\(/i.test(result)) result = '';
|
||||
} else throw new Error('Unknown filter operation.');
|
||||
parentPort.postMessage({ id, result });
|
||||
} catch (error) { parentPort.postMessage({ id, error: error.message }); }
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { DEFAULT_LISTS, loadLists } from './subscriptions.mjs';
|
||||
|
||||
export class Filters {
|
||||
constructor() {
|
||||
this.worker = new Worker(new URL('./filter-worker.mjs', import.meta.url), { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 384 } });
|
||||
this.next = 1; this.pending = new Map(); this.closed = false;
|
||||
this.worker.on('message', ({ id, result, error }) => {
|
||||
const pending = this.pending.get(id);
|
||||
if (!pending) return;
|
||||
clearTimeout(pending.timer); this.pending.delete(id);
|
||||
if (error) pending.reject(new Error(error)); else pending.resolve(result);
|
||||
});
|
||||
const fail = () => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('The filter worker stopped.')); }
|
||||
this.pending.clear();
|
||||
};
|
||||
this.worker.on('error', fail); this.worker.on('exit', fail);
|
||||
}
|
||||
call(type, payload = {}, timeout = 3000) {
|
||||
if (this.closed || this.pending.size >= 512) return Promise.reject(new Error('Filters are unavailable.'));
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = this.next++;
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('The filter operation timed out.')); }, timeout);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
this.worker.postMessage({ id, type, ...payload });
|
||||
});
|
||||
}
|
||||
async load(extra = '', addresses = DEFAULT_LISTS, options = {}) {
|
||||
const files = await loadLists(addresses, options);
|
||||
this.status = await this.call('load', { text: [...files, extra].join('\n') }, 15_000);
|
||||
return this.status;
|
||||
}
|
||||
match(details) { return this.call('match', { details }); }
|
||||
cosmetics(details) { return this.call('cosmetics', { details }); }
|
||||
close() { return this.worker.terminate(); }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Bound frames in flight so image decoding cannot delay browser input. */
|
||||
export class FrameDelivery {
|
||||
sequence = 0;
|
||||
pending = new Map();
|
||||
canSend(time = performance.now()) {
|
||||
for (const [id, started] of this.pending) if (time - started > 250) this.pending.delete(id);
|
||||
return this.pending.size < 2;
|
||||
}
|
||||
sent(time = performance.now()) { const id = ++this.sequence; this.pending.set(id, time); return id; }
|
||||
acknowledge(id) { this.pending.delete(id); }
|
||||
clear() { this.pending.clear(); }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { resolvePublic, webUrl } from './policy.mjs';
|
||||
|
||||
// A destination is resolved once and the socket connects to that exact address.
|
||||
// Never pass the original hostname to a second resolver after the policy check.
|
||||
export async function createGateway({ resolver, allowedTestHosts = new Set() } = {}) {
|
||||
const username = 'runestone';
|
||||
const password = randomBytes(32).toString('hex');
|
||||
const expected = Buffer.from(`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`);
|
||||
const sockets = new Set();
|
||||
let stopped = false;
|
||||
let resolving = 0;
|
||||
const authenticate = (req, socket) => {
|
||||
const actual = Buffer.from(req.headers['proxy-authorization'] || '');
|
||||
if (actual.length === expected.length && timingSafeEqual(actual, expected)) return true;
|
||||
socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="RuneStone"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
|
||||
return false;
|
||||
};
|
||||
const destination = async (host, port) => {
|
||||
if (stopped) throw new Error('Network gate is stopped.');
|
||||
if (![80, 443].includes(port) && !allowedTestHosts.has(host)) throw new Error('Destination port is blocked.');
|
||||
if (resolving >= 64) throw new Error('The DNS request limit was reached.');
|
||||
resolving++;
|
||||
let timer;
|
||||
try {
|
||||
return await Promise.race([
|
||||
resolvePublic(host, resolver, allowedTestHosts),
|
||||
new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('DNS lookup timed out.')), 10_000); }),
|
||||
]);
|
||||
} finally { clearTimeout(timer); resolving--; }
|
||||
};
|
||||
const track = (socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on('error', () => {});
|
||||
socket.once('close', () => sockets.delete(socket));
|
||||
socket.setTimeout(60_000, () => socket.destroy());
|
||||
};
|
||||
const server = http.createServer({ maxHeaderSize: 16_384, requestTimeout: 30_000, headersTimeout: 15_000 }, async (req, res) => {
|
||||
if (!authenticate(req, req.socket)) return;
|
||||
try {
|
||||
const url = new URL(webUrl(req.url, { blank: false }));
|
||||
if (url.protocol !== 'http:') throw new Error('HTTPS requires CONNECT.');
|
||||
const port = Number(url.port || 80);
|
||||
const target = await destination(url.hostname, port);
|
||||
if (stopped || req.destroyed) return res.destroy();
|
||||
const headers = { ...req.headers, host: url.host, connection: 'close' };
|
||||
for (const name of ['proxy-authorization', 'proxy-connection', 'upgrade', ...(req.headers.connection || '').toLowerCase().split(',').map(x => x.trim())]) delete headers[name];
|
||||
const upstream = http.request({ hostname: target.address, family: target.family, port, path: url.pathname + url.search, method: req.method, headers, agent: false }, (response) => {
|
||||
res.writeHead(response.statusCode, response.headers);
|
||||
response.pipe(res);
|
||||
});
|
||||
upstream.on('socket', track);
|
||||
upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });
|
||||
res.once('close', () => upstream.destroy());
|
||||
req.pipe(upstream);
|
||||
} catch { res.writeHead(403); res.end('Destination blocked.'); }
|
||||
});
|
||||
server.on('connect', async (req, client, head) => {
|
||||
if (!authenticate(req, client)) return;
|
||||
try {
|
||||
if (!/^(?:\[[\da-fA-F:]+\]|[^:/\s@?#]+):\d+$/.test(req.url)) throw new Error('Invalid tunnel destination.');
|
||||
const url = new URL(`https://${req.url}`);
|
||||
const port = Number(url.port || 443);
|
||||
const target = await destination(url.hostname, port);
|
||||
if (stopped || client.destroyed) return client.destroy();
|
||||
const upstream = net.connect({ host: target.address, family: target.family, port });
|
||||
track(upstream);
|
||||
upstream.once('connect', () => {
|
||||
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
||||
if (head.length) upstream.write(head);
|
||||
client.pipe(upstream); upstream.pipe(client);
|
||||
});
|
||||
upstream.once('error', () => client.destroy());
|
||||
client.once('close', () => upstream.destroy());
|
||||
} catch { client.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); }
|
||||
});
|
||||
server.on('upgrade', (_req, socket) => socket.destroy());
|
||||
server.on('connection', (socket) => {
|
||||
if (stopped || sockets.size >= 256) return socket.destroy();
|
||||
track(socket);
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
||||
return {
|
||||
port: server.address().port, username, password,
|
||||
close() {
|
||||
stopped = true;
|
||||
for (const socket of sockets) socket.destroy();
|
||||
return new Promise(resolve => server.close(resolve));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import ipaddr from 'ipaddr.js';
|
||||
import { lookup } from 'node:dns/promises';
|
||||
|
||||
export const SEARCH_PROVIDERS = Object.freeze({
|
||||
duckduckgo: 'https://duckduckgo.com/?q=',
|
||||
google: 'https://www.google.com/search?q=',
|
||||
bing: 'https://www.bing.com/search?q=',
|
||||
});
|
||||
export const MAX_INPUT = 8192;
|
||||
|
||||
export function webUrl(value, { blank = true } = {}) {
|
||||
if (typeof value !== 'string' || value.length > MAX_INPUT || /[\u0000-\u001f\u007f]/u.test(value)) {
|
||||
throw new Error('Invalid address.');
|
||||
}
|
||||
if (blank && value === 'about:blank') return value;
|
||||
const url = new URL(value);
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) {
|
||||
throw new Error('Use an HTTP or HTTPS address without embedded credentials.');
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export function addressInput(value, provider = 'duckduckgo') {
|
||||
if (typeof value !== 'string' || value.length > MAX_INPUT) throw new Error('Invalid address.');
|
||||
const input = value.trim();
|
||||
if (!input) return 'about:blank';
|
||||
if (input === 'about:blank' || /^[a-z][a-z\d+.-]*:/i.test(input)) return webUrl(input);
|
||||
if (!/\s/u.test(input) && (input.includes('.') || input === 'localhost')) return webUrl(`https://${input}`);
|
||||
if (!Object.hasOwn(SEARCH_PROVIDERS, provider)) throw new Error('Unknown search provider.');
|
||||
return SEARCH_PROVIDERS[provider] + encodeURIComponent(input);
|
||||
}
|
||||
|
||||
export function publicAddress(address) {
|
||||
try {
|
||||
const parsed = ipaddr.process(address.replace(/^\[|\]$/g, ''));
|
||||
return parsed.range() === 'unicast';
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
export async function resolvePublic(hostname, resolver = lookup, allowedTestHosts = new Set()) {
|
||||
const host = hostname.replace(/^\[|\]$/g, '');
|
||||
if (!host || host.includes('%')) throw new Error('Invalid host.');
|
||||
const answers = ipaddr.isValid(host)
|
||||
? [{ address: host, family: ipaddr.parse(host).kind() === 'ipv6' ? 6 : 4 }]
|
||||
: await resolver(host, { all: true, verbatim: true });
|
||||
if (!answers.length || (!allowedTestHosts.has(host) && answers.some(({ address }) => !publicAddress(address)))) {
|
||||
throw new Error('Local and private network access is blocked.');
|
||||
}
|
||||
return answers.find(answer => answer.family === 4) || answers[0];
|
||||
}
|
||||
|
||||
export function shortText(value, limit = 120) {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > limit) throw new Error('Invalid text.');
|
||||
return value.trim().replace(/[\u0000-\u001f\u007f]/gu, '');
|
||||
}
|
||||
|
||||
export const REMOTE_PREFERENCES = Object.freeze({
|
||||
sandbox: true, contextIsolation: true, nodeIntegration: false,
|
||||
nodeIntegrationInWorker: false, nodeIntegrationInSubFrames: false,
|
||||
webSecurity: true, allowRunningInsecureContent: false,
|
||||
webviewTag: false, devTools: false, safeDialogs: true,
|
||||
navigateOnDragDrop: false, spellcheck: false,
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { shortText, webUrl, SEARCH_PROVIDERS } from './policy.mjs';
|
||||
import { DEFAULT_LISTS, normalizeLists } from './subscriptions.mjs';
|
||||
|
||||
export class Store {
|
||||
constructor(directory) {
|
||||
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
this.file = path.join(directory, 'browser.json');
|
||||
this.data = {
|
||||
version: 1, settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [...DEFAULT_LISTS] },
|
||||
profiles: [{ id: 'user', name: 'User' }],
|
||||
bookmarks: [], history: [], exceptions: [],
|
||||
};
|
||||
try {
|
||||
const saved = JSON.parse(readFileSync(this.file, 'utf8'));
|
||||
if (saved.version !== 1 || !Array.isArray(saved.profiles) || !saved.profiles.every(p => /^[a-z0-9-]{1,64}$/.test(p.id))) throw new Error('Unsupported profile store.');
|
||||
this.data = { ...saved, settings: { ...this.data.settings, ...saved.settings } };
|
||||
// Preserve existing data. Legacy profiles become ordinary, removable profiles.
|
||||
const personal = this.data.profiles.find(profile => profile.id === 'personal');
|
||||
if (personal?.name === 'Personal') personal.name = 'User';
|
||||
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
for (const item of this.data.history) if (!item.id) item.id = randomUUID();
|
||||
}
|
||||
save() {
|
||||
writeFileSync(this.file + '.tmp', JSON.stringify(this.data, null, 2), { mode: 0o600 });
|
||||
renameSync(this.file + '.tmp', this.file);
|
||||
}
|
||||
profile(id) {
|
||||
const profile = this.data.profiles.find(p => p.id === id);
|
||||
if (!profile) throw new Error('Unknown profile.');
|
||||
return profile;
|
||||
}
|
||||
createProfile(name) {
|
||||
if (this.data.profiles.length >= 20) throw new Error('The profile limit is 20.');
|
||||
const profile = { id: randomUUID(), name: shortText(name, 60) };
|
||||
this.data.profiles.push(profile); this.save(); return profile;
|
||||
}
|
||||
duplicateMetadata(sourceId, id, name) {
|
||||
this.profile(sourceId);
|
||||
if (!/^[a-f0-9-]{36}$/.test(id) || this.data.profiles.some(profile => profile.id === id)) throw new Error('Invalid destination profile.');
|
||||
if (this.data.profiles.length >= 20) throw new Error('The profile limit is 20.');
|
||||
const profile = { id, name: shortText(name, 60) };
|
||||
this.data.profiles.push(profile);
|
||||
this.data.bookmarks.push(...this.data.bookmarks.filter(item => item.profileId === sourceId).map(item => ({ ...item, id: randomUUID(), profileId: id })));
|
||||
this.data.history.push(...this.data.history.filter(item => item.profileId === sourceId).map(item => ({ ...item, id: randomUUID(), profileId: id })));
|
||||
this.save(); return profile;
|
||||
}
|
||||
configure(input, { persist = true } = {}) {
|
||||
if (!Object.hasOwn(SEARCH_PROVIDERS, input.search) || typeof input.adblock !== 'boolean' ||
|
||||
!['internal', 'external'].includes(input.linkDestination) || typeof input.personalRules !== 'string' || input.personalRules.length > 100_000) throw new Error('Invalid browser settings.');
|
||||
const homepage = input.homepage ?? this.data.settings.homepage;
|
||||
if (typeof homepage !== 'string') throw new Error('Invalid homepage address.');
|
||||
const filterLists = normalizeLists(input.filterLists ?? this.data.settings.filterLists);
|
||||
this.data.settings = { search: input.search, adblock: input.adblock, linkDestination: input.linkDestination, personalRules: input.personalRules,
|
||||
homepage: homepage.trim() ? webUrl(homepage.trim()) : '', filterLists };
|
||||
if (persist) this.save();
|
||||
}
|
||||
visit(profileId, url, title) {
|
||||
this.profile(profileId);
|
||||
if (!/^https?:/.test(url)) return;
|
||||
this.data.history.unshift({ id: randomUUID(), profileId, url: webUrl(url), title: String(title).slice(0, 200), at: Date.now() });
|
||||
this.data.history = this.data.history.slice(0, 2000); this.save();
|
||||
}
|
||||
bookmark(profileId, url, title) {
|
||||
this.profile(profileId);
|
||||
this.data.bookmarks.push({ id: randomUUID(), profileId, url: webUrl(url, { blank: false }), title: shortText(title || url, 500) });
|
||||
this.save();
|
||||
}
|
||||
removeHistory(profileId, id) {
|
||||
this.profile(profileId);
|
||||
if (typeof id !== 'string' || !this.data.history.some(item => item.profileId === profileId && item.id === id)) throw new Error('This history entry no longer exists. Refresh the list.');
|
||||
this.data.history = this.data.history.filter(item => item.profileId !== profileId || item.id !== id);
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { webUrl } from './policy.mjs';
|
||||
import { fetchList } from './downloads.mjs';
|
||||
|
||||
export const DEFAULT_LISTS = Object.freeze([
|
||||
'https://easylist.to/easylist/easylist.txt',
|
||||
'https://easylist.to/easylist/easyprivacy.txt',
|
||||
]);
|
||||
|
||||
export function normalizeLists(value) {
|
||||
if (!Array.isArray(value) || value.length > 8) throw new Error('Use at most eight filter list URLs.');
|
||||
return [...new Set(value.map(address => {
|
||||
const url = new URL(webUrl(address, { blank: false }));
|
||||
if (url.protocol !== 'https:' || (url.port && url.port !== '443')) throw new Error('Use an HTTPS filter list URL.');
|
||||
return url.href;
|
||||
}))];
|
||||
}
|
||||
|
||||
export async function loadLists(addresses, { directory, download = false, fetch = fetchList } = {}) {
|
||||
return Promise.all(normalizeLists(addresses).map(async address => {
|
||||
const bundled = DEFAULT_LISTS.indexOf(address);
|
||||
if (bundled !== -1) return readFile(new URL(`../assets/filters/${bundled === 0 ? 'easylist' : 'easyprivacy'}.txt`, import.meta.url), 'utf8');
|
||||
const file = directory && path.join(directory, 'filter-lists', createHash('sha256').update(address).digest('hex') + '.txt');
|
||||
if (!file) throw new Error('Filter storage is unavailable.');
|
||||
try { return await readFile(file, 'utf8'); }
|
||||
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
if (!download) throw new Error('A filter list is missing. Save the browser settings to download it again.');
|
||||
const text = await fetch(address);
|
||||
await mkdir(path.dirname(file), { recursive: true });
|
||||
await writeFile(file, text, { mode: 0o600 });
|
||||
return text;
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export function cookieId(cookie) {
|
||||
return JSON.stringify([cookie.name, cookie.domain, cookie.path, !!cookie.hostOnly, !!cookie.secure]);
|
||||
}
|
||||
export async function listCookies(session) {
|
||||
return (await session.cookies.get({})).map(cookie => ({ id: cookieId(cookie), name: cookie.name,
|
||||
domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly }));
|
||||
}
|
||||
export async function removeCookie(session, id) {
|
||||
if (typeof id !== 'string' || id.length > 8192) throw new Error('Invalid cookie selection.');
|
||||
const cookie = (await session.cookies.get({})).find(item => cookieId(item) === id);
|
||||
if (!cookie) throw new Error('This cookie no longer exists. Refresh the list.');
|
||||
// Expire the exact domain/path tuple. cookies.remove(url, name) can match other paths.
|
||||
await session.cookies.set({ url: `${cookie.secure ? 'https' : 'http'}://${cookie.domain.replace(/^\./, '')}${cookie.path}`,
|
||||
name: cookie.name, value: '', ...(cookie.hostOnly ? {} : { domain: cookie.domain }), path: cookie.path,
|
||||
secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, expirationDate: 1 });
|
||||
await session.cookies.flushStore();
|
||||
}
|
||||
Reference in New Issue
Block a user