Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+12
View File
@@ -0,0 +1,12 @@
# Third-party notices
EasyList and EasyPrivacy are by [the EasyList authors](https://easylist.to/).
The bundled text files are unchanged snapshots from their published endpoints. Their headers retain authorship and version information.
This project uses those lists under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/).
See the [EasyList license page](https://easylist.to/pages/licence.html) and assets/filters/manifest.json for the source and download record.
Ghostery's filter engine uses the Mozilla Public License 2.0. The unmodified dependency retains its license and copyright notices.
Its license text is included in licenses/MPL-2.0.txt. Source is available from https://github.com/ghostery/adblocker.
Electron and Chromium notices accompany the packaged runtime. Other dependencies retain their license files in node_modules.
No project-wide distribution license is selected by this prototype.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
{
"fetchedAt": "2026-10-06T16:29:07.621Z",
"lists": [
[
"easylist.txt",
"https://easylist.to/easylist/easylist.txt"
],
[
"easyprivacy.txt",
"https://easylist.to/easylist/easyprivacy.txt"
]
]
}
+64
View File
@@ -0,0 +1,64 @@
# Browser architecture
The interface lives in `../../src/lib/browser/`. The native bridge lives in `../../src-tauri/src/browser.rs`.
This directory contains the runtime, bundled filter lists, licenses, and tests.
Electron runs in its own process, with a separate dependency lock.
Run `npm ci` in this directory to install the runtime dependencies.
Run `npm run package` and `npm run stage:host` to prepare the resource for a host installer.
No Browser plugin ZIP or sibling checkout is required.
## Page isolation
Each page has a sandboxed renderer without Node integration or a preload bridge.
Website scripts never execute inside the privileged RuneStone webview.
The native bridge accepts a fixed command list. It rejects executable paths, arbitrary JavaScript, and shell commands.
RuneStone authenticates the runtime through a temporary loopback listener and a random environment token.
The runtime removes that token before it creates pages. The listener closes after authentication.
The established connection carries commands, state, and frames. No external debugger or agent server is enabled.
The bridge checks the window session and tab ownership. It limits message sizes and routes events to the owner.
## Frames and input
Chromium paints at up to 60 FPS. JPEG frames reduce encoding and transport costs during motion.
A lossless PNG follows after the page stops changing. At most two frames await host acknowledgment.
Acknowledgments follow image decoding. Expired acknowledgments allow recovery after a view closes or moves.
Hidden tabs stop painting. The encoder skips work while the transport is busy.
The viewport uses the host pixel ratio. Device emulation keeps CSS dimensions while the offscreen window supplies physical pixels.
Pointer coordinates and wheel distances use the same scale. Native window rounding can add one or two image pixels.
The host coalesces pointer motion and wheel bursts. A reversed wheel direction replaces pending motion in the old direction.
Middle-button scrolling uses a dead zone and a speed based on distance.
Escape, another click, focus loss, and drag release stop it.
The host orders button and keyboard events. Text insertion accepts Unicode and composition text.
Clipboard shortcuts use native editing commands. Page menus use the shared RuneStone menu components.
Image and link downloads require a user menu action. Each menu has a token tied to its tab and document.
Downloads use the Chromium session and a native save dialog. Other downloads remain blocked.
## Profiles and tabs
A fresh store contains one User profile. New profiles start blank unless the user requests a copy.
Duplication stops the runtime before it copies the persistent partition. It then restores the tabs.
Cookies, site data, history, and bookmarks survive the copy. Later changes remain separate.
Profile names carry no special authority. Copies do not inherit agent grants.
The application data path remains unchanged. Old profiles and settings remain available.
Each tab belongs to one RuneStone window. A transfer token moves a live tab between windows.
Split panes open independent tabs with the same URL and profile. Find uses Chromium match counts and selection.
## Network and filters
Each profile uses an authenticated local proxy. The proxy resolves public destinations and pins the validated address.
It rejects private addresses. HTTPS retains certificate validation. A proxy failure has no direct network fallback.
QUIC is disabled. WebRTC disables non-proxied UDP. These controls do not constitute a VPN.
A bounded worker loads EasyList, EasyPrivacy, subscriptions, and personal rules through the Ghostery parser.
Missing filters block requests when ad blocking is enabled. Scriptlets and extended cosmetic selectors remain disabled.
Basic cosmetic filtering runs after the main frame loads. Dynamic-frame coverage still needs work.
## Remaining limits
Webpage screen-reader access, Linux execution, update delivery, and full media compatibility need separate acceptance checks.
Per-tab VPN tunnels remain unimplemented. Agent observation uses scoped grants, but external agent control is not connected.
+22
View File
@@ -0,0 +1,22 @@
# Browser status
The interface, runtime, tests, filters, and licenses live in the RuneStone repository.
The former Browser repository is no longer a build dependency.
| Capability | State |
| --- | --- |
| Delivery | Built into RuneStone, with an isolated Chromium process |
| Interface | Editor tabs, Bookmarks, Settings, split panes, and separate windows |
| Profiles | Default User profile, blank profiles, and independent copies |
| Page input | Pointer input, wheel scrolling, middle-button scrolling, text, clipboard shortcuts, and composition text |
| Page menus | Navigation, Find, editing, image copy and save, and link copy, save, and open |
| Rendering | Up to 60 FPS, bounded frame delivery, high-DPI pixels, and lossless still frames |
| Filters | Default lists, custom subscriptions, personal rules, and basic cosmetic filtering |
| Web data | Profile cleanup, cookie removal, and history removal |
| Agent support | Scoped observation. No external model connection or action tools |
| VPN | Not implemented |
| Accessibility | Webpage content still lacks a screen-reader bridge |
| Linux | Runtime execution requires a separate acceptance check |
The tests use temporary profiles. Native host tests require the isolated identity in `test/runestone.conf.json`.
The performance and interaction reports state the viewport, frame rate, and checks that ran.
+375
View File
@@ -0,0 +1,375 @@
Copyright (c) 2017-present Ghostery GmbH. All rights reserved.
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+1079
View File
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
{
"name": "runestone-browser",
"version": "0.1.7",
"private": true,
"description": "Isolated browser runtime included with RuneStone",
"type": "module",
"main": "src/engine-main.mjs",
"engines": {
"node": ">=24"
},
"scripts": {
"setup": "node node_modules/electron/install.js",
"stage:host": "node scripts/stage-host.mjs",
"test": "node --test test/*.test.mjs",
"test:browser": "node scripts/test-engine.mjs",
"test:packaged": "node scripts/test-engine.mjs --packaged",
"test:protocol": "node scripts/test-protocol.mjs",
"test:native": "node scripts/test-native.mjs",
"test:tab-actions": "node scripts/test-tab-actions.mjs",
"test:idle": "node scripts/test-idle.mjs",
"check": "node scripts/check.mjs",
"filters:update": "node scripts/update-filters.mjs",
"package": "node scripts/package.mjs",
"package:windows": "npm run package -- --platform=win32 --arch=x64",
"package:linux": "npm run package -- --platform=linux --arch=x64",
"test:performance": "node test/performance-smoke.mjs"
},
"dependencies": {
"@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0"
},
"devDependencies": {
"@electron/packager": "20.3.0",
"@tauri-apps/api": "2.11.1",
"electron": "44.5.1",
"playwright": "1.63.0",
"svelte": "5.57.1"
}
}
+14
View File
@@ -0,0 +1,14 @@
import { readdir } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
async function check(directory) {
for (const item of await readdir(directory, { withFileTypes: true })) {
const file = `${directory}/${item.name}`;
if (item.isDirectory()) await check(file);
else if (/\.(mjs|cjs)$/.test(file)) {
const result = spawnSync(process.execPath, ['--check', file], { stdio: 'inherit' });
if (result.status !== 0) process.exit(result.status || 1);
}
}
}
for (const directory of ['src', 'scripts', 'test']) await check(directory);
console.log('JavaScript syntax checks passed.');
@@ -0,0 +1,12 @@
const sessions = new WeakMap();
export async function nativeRequest(page, command, args = {}) {
const invoke = (name, value) => page.evaluate(({ name, value }) => window.__TAURI_INTERNALS__.invoke(name, value), { name, value });
if (command === 'browser_request') {
let session = sessions.get(page);
if (!session) { session = await invoke('browser_connect', {}); sessions.set(page, session); }
return invoke(command, { ...args, session });
}
if (command === 'browser_stop') sessions.delete(page);
return invoke(command, args);
}
+12
View File
@@ -0,0 +1,12 @@
import { packager } from '@electron/packager';
const options = Object.fromEntries(process.argv.slice(2).map(arg => {
const match = /^--(platform|arch)=(win32|linux|x64|arm64)$/.exec(arg);
if (!match) throw new Error('Use --platform=win32|linux and --arch=x64|arm64.');
return [match[1], match[2]];
}));
const outputs = await packager({
dir: '.', name: 'RuneStone-Browser', out: 'dist', overwrite: true,
platform: options.platform || process.platform, arch: options.arch || process.arch,
ignore: [/^\/(test|scripts|output|plugin|releases|\.github)(\/|$)/, /^\/src\/(ui\/|host\.mjs|main\.mjs|preload\.cjs)/],
});
for (const output of outputs) console.log(output);
+11
View File
@@ -0,0 +1,11 @@
import { cp, mkdir, access } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const project = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const host = resolve(process.env.RUNESTONE_ROOT || resolve(project, '..'));
const source = resolve(project, `dist/RuneStone-Browser-${process.platform}-${process.arch}`);
await access(resolve(source, process.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser'));
const destination = resolve(host, 'src-tauri/browser-engine');
await mkdir(destination, { recursive: true });
await cp(source, destination, { recursive: true });
console.log(`Browser runtime staged in ${destination}`);
+39
View File
@@ -0,0 +1,39 @@
import { spawn } from 'node:child_process';
import { mkdtemp, readFile, cp } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
const server = http.createServer((req, res) => {
if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
}
if (req.url === '/slow') return;
if (req.url === '/icon.svg') {
res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
return res.end('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="red"/></svg>');
}
if (req.url === '/favicon.ico') { res.writeHead(404); return res.end(); }
if (req.url === '/no-icon') return res.end('<!doctype html><title>No icon</title>');
if (req.url === '/with-icon') return res.end('<!doctype html><title>Icon fixture</title><link rel="icon" href="/icon.svg">');
res.writeHead(200, { 'Content-Type': req.url.endsWith('.js') ? 'text/javascript' : 'text/html', 'Cache-Control': 'no-store' });
res.end(req.url.endsWith('.js') ? 'window.adExecuted=true;' : '<!doctype html><title>Browser fixture</title><input style="position:absolute;left:20px;top:20px;width:200px;height:30px"><p class="advertisement">Ad</p><p style="margin-top:80px">Runestone needle. Runestone needle. Runestone needle.</p><script src="/blocked-ad.js"></script>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
async function phase(name, plan) {
const child = spawn(electron, ['test/engine-smoke.mjs'], { stdio: 'inherit', windowsHide: true,
env: { ...process.env, RS_TEST_ROOT: directory, RS_TEST_URL: `http://127.0.0.1:${server.address().port}/`, RS_TEST_PHASE: name, RS_TEST_PLAN: JSON.stringify(plan || {}),
...(process.argv.includes('--packaged') ? { RUNESTONE_TEST_PACKAGE: path.resolve(`dist/RuneStone-Browser-${process.platform}-${process.arch}/resources/app.asar`) } : {}) } });
const timer = setTimeout(() => child.kill(), 60_000);
const code = await new Promise((resolve, reject) => { child.once('exit', resolve); child.once('error', reject); }); clearTimeout(timer);
const result = JSON.parse(await readFile(`output/engine-${name}.json`, 'utf8'));
if (code !== 0 || result.exitCode !== 0) throw new Error(`Engine ${name} checks failed.`);
}
try {
await phase('initial');
const plan = JSON.parse(await readFile(path.join(directory, 'clone-plan.json'), 'utf8'));
await cp(path.join(directory, 'Partitions', `runestone-${plan.sourceId}`), path.join(directory, 'Partitions', `runestone-${plan.id}`), { recursive: true });
await phase('restore', plan);
} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
+88
View File
@@ -0,0 +1,88 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const listener = net.createServer();
await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve));
const port = listener.address().port;
await new Promise(resolve => listener.close(resolve));
const native = spawn(resolve('../src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let browser, page;
const passed = [];
const idle = () => new Promise(resolve => setTimeout(resolve, 2200));
try {
for (let attempt = 0; attempt < 60; attempt++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, 'The isolated test window must start.');
page = browser.contexts()[0].pages()[0];
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
let snapshot = await invoke('plugins_snapshot');
assert.equal(basename(dirname(snapshot.root)), 'com.runestone.browser-test');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const current = () => page.locator('.browser:visible');
const ready = () => page.waitForFunction(() => {
const view = [...document.querySelectorAll('.browser')].find(view => view.getBoundingClientRect().width > 0);
return view?.dataset.browserState === 'ready';
});
await ready();
const original = await current().getAttribute('data-browser-tab');
await idle();
const afterIdle = await invoke('browser_request', { command: 'state', args: {} });
assert.ok(afterIdle.tabs.some(tab => tab.id === original), `An idle connection must keep its original tab: ${JSON.stringify({ original, tabs: afterIdle.tabs, diagnostics: await page.locator('.diagnostics').allTextContents() })}`);
passed.push('the idle connection stays open beyond the authentication timeout');
console.log(`PASS ${passed.at(-1)}`);
for (let index = 0; index < 2; index++) {
await current().getByRole('button', { name: 'New browser tab', exact: true }).click();
await ready();
}
const ids = await page.locator('.browser').evaluateAll(views => views.map(view => view.dataset.browserTab).sort());
assert.equal(ids.length, 3);
for (let index = 0; index < 9; index++) {
await page.locator('.plugin-tab [role="tab"], [role="tab"][data-path^="plugin:"]').nth(index % 3).click();
await ready();
await idle();
const state = await invoke('browser_request', { command: 'state', args: {} });
assert.deepEqual(state.tabs.map(tab => tab.id).sort(), ids, 'Tab switches must not restart the browser.');
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
}
passed.push('nine tab switches and idle periods preserve all three runtime tabs');
console.log(`PASS ${passed.at(-1)}`);
const address = current().getByRole('textbox', { name: 'Address or search', exact: true });
await address.fill('https://example.com/');
await address.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('.browser input')].some(input => input.value === 'https://example.com/' && !input.disabled));
await current().getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
const bookmark = page.locator('.bookmarks .link[title="https://example.com/"]').first();
await bookmark.waitFor();
await idle();
await bookmark.click();
await ready();
await idle();
const finalState = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(finalState.tabs.length, 4);
assert.ok(ids.every(id => finalState.tabs.some(tab => tab.id === id)));
const opened = await current().getAttribute('data-browser-tab');
assert.equal(finalState.tabs.find(tab => tab.id === opened)?.url, 'https://example.com/');
passed.push('a bookmark opens after idle without replacing existing tabs');
console.log(`PASS ${passed.at(-1)}`);
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/browser-idle.png' });
await writeFile('output/browser-idle.json', JSON.stringify({ passed }, null, 2));
} catch (error) {
if (page) console.error(await page.locator('.diagnostics').allTextContents());
throw error;
} finally { await browser?.close().catch(() => {}); native.kill(); }
+119
View File
@@ -0,0 +1,119 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
if (process.platform !== 'win32') throw new Error('This native smoke test uses Windows WebView2.');
const host = resolve(process.env.RUNESTONE_ROOT || '..');
const portServer = net.createServer(); await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve));
const port = portServer.address().port; await new Promise(resolve => portServer.close(resolve));
const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], { windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` } });
let browser, page;
const passed = [];
try {
for (let attempt = 0; attempt < 60; attempt++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
if (!browser) throw new Error('The isolated RuneStone test window did not start.');
const context = browser.contexts()[0];
page = context.pages()[0];
if (!page) page = await context.waitForEvent('page');
page.setDefaultTimeout(30_000);
const errors = []; page.on('pageerror', error => errors.push(error.message));
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
let snapshot = await invoke('plugins_snapshot');
const pluginRoot = resolve(snapshot.root);
assert.equal(basename(pluginRoot), 'plugins');
assert.equal(basename(dirname(pluginRoot)), 'com.runestone.browser-test', 'Never modify a real RuneStone profile.');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
const initial = await invoke('browser_request', { command: 'state', args: {} });
await invoke('browser_request', { command: 'settings', args: { ...initial.settings, homepage: '', adblock: true, linkDestination: 'internal' } });
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/runestone-browser-splash.png' });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const address = page.getByRole('textbox', { name: 'Address or search', exact: true });
await address.waitFor();
await page.locator('.surface img').waitFor();
const state = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(state.profiles[0].name, 'User'); assert.ok(!state.profiles.some(item => item.id === 'agent'));
assert.equal(state.tabs[0].url, 'about:blank');
passed.push('browser opens inside the RuneStone editor with a User profile');
await address.fill('https://example.com/'); await address.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('[role=tab]')].some(tab => /Example|example/i.test(tab.textContent)), { timeout: 30_000 });
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/runestone-browser-internal.png' });
passed.push('a public HTTPS page renders inside the native RuneStone window');
await page.getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
await page.locator('.bookmarks .link').first().waitFor();
passed.push('web bookmarks appear in the existing Bookmarks pane');
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await page.getByRole('button', { name: 'Browser', exact: true }).click();
const settings = page.getByRole('dialog', { name: 'Settings', exact: true });
await settings.getByRole('button', { name: 'New blank profile', exact: true }).waitFor();
const adblockSwitch = settings.getByRole('switch', { name: 'Block ads and trackers', exact: true });
const linkSwitch = settings.getByRole('switch', { name: 'Open web links in RuneStone', exact: true });
await adblockSwitch.uncheck(); await linkSwitch.uncheck();
await settings.getByRole('textbox', { name: 'Homepage', exact: true }).fill('https://example.com/');
const lists = settings.getByRole('textbox', { name: 'Ad blocking lists', exact: true });
assert.match(await lists.inputValue(), /easylist\.txt/);
await lists.fill('https://easylist.to/easylist/easylist.txt');
await settings.getByRole('button', { name: 'Save browser settings', exact: true }).click();
await settings.getByText('Changes saved.', { exact: true }).waitFor();
let saved = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(saved.settings.homepage, 'https://example.com/');
assert.equal(saved.settings.linkDestination, 'external');
assert.equal(saved.settings.adblock, false);
assert.deepEqual(saved.settings.filterLists, ['https://easylist.to/easylist/easylist.txt']);
assert.equal(await adblockSwitch.evaluate(node => getComputedStyle(node).appearance), 'none');
await adblockSwitch.focus(); await page.keyboard.press('Space');
assert.equal(await adblockSwitch.isChecked(), true);
await settings.getByRole('button', { name: 'Save browser settings', exact: true }).click();
await settings.getByText('Changes saved.', { exact: true }).waitFor();
await settings.getByRole('textbox', { name: 'Homepage', exact: true }).scrollIntoViewIfNeeded();
await page.screenshot({ path: 'output/runestone-browser-settings.png' });
await page.evaluate(() => document.documentElement.dataset.theme = 'light');
await page.screenshot({ path: 'output/runestone-browser-settings-light.png' });
await page.evaluate(() => document.documentElement.dataset.theme = 'dark');
await page.keyboard.press('Escape');
await settings.waitFor({ state: 'detached' });
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await page.waitForFunction(() => [...document.querySelectorAll('[role=tab]')].filter(tab => /Example|example/i.test(tab.textContent)).length >= 2);
saved = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(saved.tabs.at(-1).url, 'https://example.com/');
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.waitForFunction(() => document.querySelector('input[aria-label="Homepage"]')?.value === 'https://example.com/');
assert.equal(await settings.getByRole('textbox', { name: 'Homepage', exact: true }).inputValue(), 'https://example.com/');
assert.equal(await linkSwitch.isChecked(), false);
passed.push('splash launch, sliding switches, filter-list edits and homepage persist and work in the native app');
const profileName = settings.getByRole('textbox', { name: 'New profile name', exact: true });
const suffix = Date.now().toString().slice(-6);
const research = `Research ${suffix}`, copy = `User copy ${suffix}`;
await profileName.fill(research); await settings.getByRole('button', { name: 'New blank profile', exact: true }).click();
await page.waitForFunction(name => [...document.querySelectorAll('.settings option')].some(option => option.textContent === name), research);
await settings.getByLabel('Profile', { exact: true }).selectOption('user');
await profileName.fill(copy); await settings.getByRole('button', { name: 'Duplicate profile', exact: true }).click();
await page.waitForFunction(name => [...document.querySelectorAll('.settings option')].some(option => option.textContent === name), copy);
passed.push('blank and duplicate profile actions work in RuneStone Settings');
assert.equal(await address.last().evaluate(node => getComputedStyle(node).borderRadius), await page.locator('.toolbar .icon-btn').last().evaluate(node => getComputedStyle(node).borderRadius));
passed.push('browser controls share RuneStone corner tokens in both themes');
await invoke('browser_stop');
passed.push('browser cleanup revokes the window session');
assert.deepEqual(errors, []);
await writeFile('output/native-plugin-smoke.json', JSON.stringify({ passed, errors }, null, 2));
for (const name of passed) console.log(`PASS ${name}`);
} catch (error) {
if (page) { await mkdir('output', { recursive: true }); await page.screenshot({ path: 'output/native-failure.png' }).catch(() => {}); console.error(await page.locator('body').innerText().catch(() => '')); }
throw error;
} finally {
if (browser) { await browser.close().catch(() => {}); }
native.kill();
}
+35
View File
@@ -0,0 +1,35 @@
import net from 'node:net';
import { spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { mkdtemp } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import assert from 'node:assert/strict';
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-protocol-'));
const token = randomBytes(32).toString('hex');
let socket;
const server = net.createServer(client => {
socket = client;
let buffer = '';
client.on('data', bytes => {
buffer += bytes;
let end;
while ((end = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
const message = JSON.parse(line);
if (message.token) { assert.equal(message.token, token); console.log('PASS runtime authentication'); }
if (message.event === 'ready') client.write(JSON.stringify({ id: 1, command: 'state', args: {} }) + '\n');
if (message.id === 1) { assert.deepEqual(message.result.profiles, [{ id: 'user', name: 'User' }]); client.write(JSON.stringify({ id: 2, command: 'newTab', args: {} }) + '\n'); }
if (message.id === 2) { assert.ok(message.result.tabId); console.log('PASS packaged runtime commands'); client.write(JSON.stringify({ id: 3, command: 'shutdown', args: {} }) + '\n'); }
if (message.id === 3) console.log('PASS clean shutdown response');
}
});
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const executable = path.resolve(`dist/RuneStone-Browser-${process.platform}-${process.arch}/${process.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser'}`);
const child = spawn(executable, [`--rs-connect=${server.address().port}`, `--rs-browser-root=${root}`], { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, RUNESTONE_BROWSER_TOKEN: token } });
child.stderr.on('data', chunk => process.stderr.write(chunk));
const timer = setTimeout(() => { child.kill(); process.exitCode = 1; }, 15_000);
const code = await new Promise(resolve => child.once('exit', resolve)); clearTimeout(timer);
socket?.destroy(); await new Promise(resolve => server.close(resolve));
assert.equal(code, 0);
+115
View File
@@ -0,0 +1,115 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { execFileSync, spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const listener = net.createServer();
await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve));
const port = listener.address().port;
await new Promise(resolve => listener.close(resolve));
const native = spawn(resolve('../src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let browser, page;
const passed = [];
try {
for (let i = 0; i < 60; i++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, 'Isolated test window must start.');
page = browser.contexts()[0].pages()[0];
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
const rendered = () => page.waitForFunction(() => {
const image = document.querySelector('.surface img');
return image?.complete && image.naturalWidth > 0;
});
let snapshot = await invoke('plugins_snapshot');
assert.equal(basename(dirname(snapshot.root)), 'com.runestone.browser-test');
const crashBrowser = () => {
const output = execFileSync('powershell.exe', ['-NoProfile', '-Command',
`Get-CimInstance Win32_Process -Filter "ParentProcessId = ${native.pid} AND Name = 'RuneStone-Browser.exe'" | Select-Object -ExpandProperty ProcessId`],
{ windowsHide: true, encoding: 'utf8' });
const ids = output.trim().split(/\s+/).filter(Boolean).map(Number);
assert.equal(ids.length, 1, 'Only the browser child of the isolated test window can stop.');
assert.ok(Number.isSafeInteger(ids[0]) && ids[0] > 0);
process.kill(ids[0]);
};
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
await invoke('browser_request', { command: 'state', args: {} });
crashBrowser();
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await rendered();
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
passed.push('a new tab opens after the browser process stops without manual reconnect');
await page.getByRole('textbox', { name: 'Address or search', exact: true }).fill('https://example.com/');
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
await page.getByRole('tab', { name: 'Example Domain · User', exact: true }).waitFor();
const before = await invoke('browser_request', { command: 'state', args: {} });
await invoke('browser_stop');
const reset = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(reset.tabs.length, 0);
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
if (process.argv.includes('--expect-broken')) {
await page.getByText('Unknown browser tab.', { exact: true }).waitFor();
passed.push('reproduced Unknown browser tab after a runtime restart');
} else {
await page.waitForFunction(oldId => {
const view = document.querySelector('.browser');
return view?.dataset.browserState === 'ready' && view.dataset.browserTab && view.dataset.browserTab !== oldId;
}, before.tabs[0].id);
await rendered();
await page.waitForFunction(() => document.querySelector('input[aria-label="Address or search"]')?.disabled === false);
const restored = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(restored.tabs.length, 1);
assert.notEqual(restored.tabs[0].id, before.tabs[0].id);
assert.equal(await page.getByText('Unknown browser tab.', { exact: true }).isVisible(), false);
passed.push('the open view reconnects after a runtime restart');
// A repeated failure must stop automatic retries and offer an explicit action.
await invoke('browser_stop');
await invoke('browser_request', { command: 'state', args: {} });
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
await page.getByRole('button', { name: 'Reconnect', exact: true }).waitFor();
await page.getByText('Browser error details', { exact: true }).click();
await page.getByText('Unknown browser tab.', { exact: false }).waitFor();
await page.screenshot({ path: 'output/browser-recovery-details.png' });
await page.getByRole('button', { name: 'Reconnect', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
passed.push('a repeated failure shows the cause, operation and a working Reconnect action');
// Registered plugin views remain in the host menu after their tabs close.
await page.locator('.plugin-tab .icon-btn').click();
await page.locator('.browser').waitFor({ state: 'detached' });
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
const tools = page.getByRole('group', { name: 'Plugin commands and views', exact: true }).getByRole('button');
assert.equal(await tools.count(), 2);
await tools.last().click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
passed.push('a closed browser view opens with a fresh runtime tab');
await page.getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
const bookmark = page.locator('.bookmarks .link').filter({ hasText: 'Example Domain' }).first();
await bookmark.waitFor();
crashBrowser();
await bookmark.click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
await page.waitForFunction(() => document.querySelector('input[aria-label="Address or search"]')?.value === 'https://example.com/');
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
passed.push('a bookmark opens its saved URL after the browser process stops');
}
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/browser-recovery.png' });
await writeFile('output/browser-recovery.json', JSON.stringify({ passed }, null, 2));
passed.forEach(message => console.log(`PASS ${message}`));
} catch (error) {
if (page) { console.error(await page.locator('body').innerText()); console.error(await page.locator('.diagnostics').allTextContents()); await page.screenshot({ path: 'output/browser-recovery-failure.png' }); }
throw error;
} finally { await browser?.close().catch(() => {}); native.kill(); }
@@ -0,0 +1,276 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const host = resolve(process.env.RUNESTONE_ROOT || '..');
const portServer = net.createServer();
await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve));
const port = portServer.address().port;
await new Promise(resolve => portServer.close(resolve));
const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let nativeOutput = '';
for (const stream of [native.stdout, native.stderr]) stream.on('data', chunk => nativeOutput = (nativeOutput + chunk).slice(-8000));
let browser, page;
const passed = [], errors = [];
const ipc = nativeRequest;
const state = page => ipc(page, 'browser_request', { command: 'state', args: {} });
const menuItem = (page, name) => page.getByRole('menuitem', { name: name === 'Find…' ? 'Find… Ctrl+F' : name, exact: true });
const tabs = page => page.locator('.header').getByRole('tab');
async function action(page, tab, name) {
await tab.click({ button: 'right' });
await menuItem(page, name).click();
}
async function ready(page, count) {
await page.waitForFunction(count => [...document.querySelectorAll('.browser[data-browser-state="ready"]')].filter(node => node.getBoundingClientRect().width > 0).length === count, count);
}
async function painted(page, count) {
await page.waitForFunction(count => {
const images = [...document.querySelectorAll('.surface img')].filter(img => img.getBoundingClientRect().width > 0);
return images.length === count && images.every(img => {
const bounds = img.getBoundingClientRect();
return img.naturalHeight > 0 && Math.abs(img.naturalWidth / img.naturalHeight - bounds.width / bounds.height) < 0.02;
});
}, count);
}
async function dragToWindow(context, source, sourceTab, destination) {
const targetSession = await context.newCDPSession(destination);
const before = (await state(source)).tabs.map(tab => tab.id);
await source.evaluate(() => {
window.__tabDragData = undefined;
window.addEventListener('dragstart', event => {
window.__tabDragData = {
items: [...event.dataTransfer.types].map(mimeType => ({ mimeType, data: event.dataTransfer.getData(mimeType) })),
dragOperationsMask: 16,
};
}, { once: true });
});
const bounds = await sourceTab.boundingBox();
await source.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
await source.mouse.down();
await source.mouse.move(bounds.x + bounds.width / 2 + 30, bounds.y + bounds.height / 2 + 12, { steps: 5 });
await source.waitForFunction(() => window.__tabDragData?.items.length);
const transfer = await source.evaluate(() => window.__tabDragData);
assert.ok(transfer.items.some(item => item.mimeType === 'application/x-runestone-tab' && item.data));
await source.mouse.up();
assert.deepEqual((await state(source)).tabs.map(tab => tab.id), before, 'A drag without a destination keeps the live tabs.');
const drop = await destination.locator('.header [role="tablist"]').boundingBox();
assert.ok(drop.width > 0 && drop.height > 0);
for (const type of ['dragEnter', 'dragOver', 'drop']) {
await targetSession.send('Input.dispatchDragEvent', { type, x: drop.x + 2, y: drop.y + drop.height / 2, data: transfer });
}
await targetSession.detach();
}
try {
for (let attempt = 0; attempt < 60; attempt++) {
if (native.exitCode !== null) throw new Error(`The test app exited (${native.exitCode}). ${nativeOutput}`);
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, `The isolated native app must start. ${nativeOutput}`);
const context = browser.contexts()[0];
page = context.pages()[0] || await context.waitForEvent('page');
page.setDefaultTimeout(20000);
page.on('pageerror', error => errors.push(error.message));
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
let plugins = await ipc(page, 'plugins_snapshot');
const root = resolve(plugins.root);
assert.equal(basename(dirname(root)), 'com.runestone.browser-test');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
const initial = await state(page);
await ipc(page, 'browser_request', { command: 'settings', args: { ...initial.settings, homepage: '', linkDestination: 'internal' } });
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await tabs(page).filter({ hasText: 'New tab' }).waitFor();
await action(page, tabs(page).first(), 'Pin');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await ready(page, 1);
assert.equal(await tabs(page).count(), 1);
assert.equal(await page.locator('.header .pin').count(), 1);
await action(page, tabs(page).first(), 'Unpin');
passed.push('Open browser replaces the empty tab and keeps its pin');
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
const emptyPath = await tabs(page).last().getAttribute('data-path');
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
const untouchedPath = await tabs(page).last().getAttribute('data-path');
await page.locator(`.header [role="tab"][data-path="${emptyPath}"]`).click();
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await ready(page, 1);
assert.equal(await tabs(page).count(), 3);
assert.equal(await tabs(page).last().getAttribute('data-path'), untouchedPath);
assert.match(await tabs(page).nth(1).getAttribute('data-path'), /^plugin:/);
await action(page, tabs(page).nth(1), 'Close');
await action(page, tabs(page).last(), 'Close');
assert.equal(await tabs(page).count(), 1);
passed.push('splash replacement keeps the tab position and other empty tabs');
await tabs(page).first().click({ button: 'right' });
assert.equal(await menuItem(page, 'Open in default browser').isDisabled(), true);
assert.equal(await menuItem(page, 'Bookmark').isDisabled(), true);
await page.keyboard.press('Escape');
const address = page.getByRole('textbox', { name: 'Address or search', exact: true });
await address.fill('https://example.com/'); await address.press('Enter');
await page.waitForFunction(() => document.querySelector('.header [role="tab"]')?.textContent.includes('Example'));
const firstId = (await state(page)).tabs[0].id;
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await tabs(page).first().click({ button: 'right' });
for (const label of ['Close', 'Pin', 'Move to new window', 'Split right', 'Split down', 'Find…', 'Open in default browser', 'Bookmark']) {
assert.equal(await menuItem(page, label).isEnabled(), true, label);
assert.equal(await menuItem(page, label).locator('svg').count(), 1, label);
}
await mkdir('output', { recursive: true });
await page.screenshot({ path: `output/browser-tab-menu-${theme}.png` });
await page.keyboard.press('Escape');
}
passed.push('all eight tab actions use the shared menu in both themes');
await action(page, tabs(page).first(), 'Pin');
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await ready(page, 1);
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 3);
await ready(page, 1);
await action(page, tabs(page).last(), 'Close others');
await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2);
assert.equal(await tabs(page).count(), 2);
await action(page, tabs(page).first(), 'Bookmark');
assert.ok((await state(page)).bookmarks.some(bookmark => bookmark.url === 'https://example.com/'));
await action(page, tabs(page).last(), 'Close');
await ready(page, 1);
passed.push('pins survive bulk close and inactive-tab actions target the clicked page');
await page.locator('.surface:visible').focus();
await page.keyboard.press('Control+f');
const find = page.getByRole('textbox', { name: 'Find in page', exact: true });
await find.fill('Learn more');
await page.getByText('1 of 1', { exact: true }).waitFor();
await find.press('Enter');
await find.press('Shift+Enter');
await find.fill('no such phrase exists');
await page.getByText('No matches', { exact: true }).waitFor();
await find.press('Escape');
await find.waitFor({ state: 'detached' });
await address.focus(); await page.keyboard.press('Control+f');
await find.waitFor(); await page.getByText('No matches', { exact: true }).waitFor(); await find.press('Escape');
await action(page, tabs(page).first(), 'Find…');
await find.fill('Learn more');
await page.getByText('1 of 1', { exact: true }).waitFor();
await find.press('Escape');
passed.push('Ctrl+F works from the page and address bar, with counts, navigation, and Escape');
await action(page, tabs(page).first(), 'Split right');
await ready(page, 2);
assert.equal((await state(page)).tabs[0].id, firstId);
const surfaces = page.locator('.surface:visible');
const a = await surfaces.nth(0).boundingBox(), b = await surfaces.nth(1).boundingBox();
assert.ok(b.x > a.x + a.width - 5);
await action(page, tabs(page).last(), 'Split down');
await ready(page, 3);
const c = await surfaces.nth(2).boundingBox(), upper = await surfaces.nth(1).boundingBox();
assert.ok(c.y > upper.y + upper.height - 5);
assert.equal((await state(page)).tabs.length, 3);
await painted(page, 3);
await page.screenshot({ path: 'output/browser-split-panes.png' });
await action(page, tabs(page).last(), 'Close');
await ready(page, 2);
passed.push('nested splits preserve the source tab and closing a pane fills its space');
const movingId = (await state(page)).tabs.find(tab => tab.id !== firstId).id;
await action(page, tabs(page).last(), 'Pin');
const opened = context.waitForEvent('page');
await action(page, tabs(page).last(), 'Move to new window');
const target = await opened;
target.setDefaultTimeout(20000);
target.on('pageerror', error => errors.push(error.message));
await ready(target, 1);
await target.evaluate(async () => {
window.__browserStates = [];
const handler = window.__TAURI_INTERNALS__.transformCallback(event => {
window.__browserStates.push({ revision: event.payload.state?.revision, tabs: event.payload.state?.tabs });
window.__browserStates = window.__browserStates.slice(-5);
});
await window.__TAURI_INTERNALS__.invoke('plugin:event|listen', { event: 'browser-state', target: { kind: 'WebviewWindow', label: window.__TAURI_INTERNALS__.metadata.currentWindow.label }, handler });
});
await ready(page, 1);
assert.equal(await target.getByRole('application', { name: 'RuneStone browser', exact: true }).count(), 1);
assert.equal(await target.getByRole('application', { name: 'RuneStone workbench', exact: true }).count(), 0);
assert.equal(await target.getByRole('button', { name: 'Files', exact: true }).count(), 0);
assert.equal(await target.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).count(), 0);
assert.equal((await state(target)).tabs[0].id, movingId);
assert.equal((await state(page)).tabs.length, 1);
assert.equal((await state(target)).tabs[0].url, 'https://example.com/');
assert.equal(await target.locator('.header .pin').count(), 1);
await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: movingId } }), /another window/);
await target.locator('.surface:visible').focus(); await target.keyboard.press('Control+f');
await target.getByRole('textbox', { name: 'Find in page', exact: true }).fill('Learn more');
await target.getByText('1 of 1', { exact: true }).waitFor();
await target.screenshot({ path: 'output/browser-moved-window.png' });
assert.equal(await tabs(target).first().getAttribute('draggable'), 'true');
const beforeDrop = (await state(target)).tabs[0];
await assert.rejects(ipc(page, 'browser_request', { command: 'adoptTab', args: { tabId: movingId, transferToken: 'invalid-token' } }), /valid transfer/);
const updates = await target.evaluate(() => window.__browserStates);
assert.ok(updates.length > 0 && updates.every(update => update.tabs.every(tab => tab.id === movingId)));
const closed = target.waitForEvent('close');
await dragToWindow(context, target, tabs(target).first(), page);
await closed;
await ready(page, 1);
await page.waitForFunction(() => document.querySelectorAll('.browser[data-browser-state="ready"]').length === 2);
const returned = (await state(page)).tabs.find(tab => tab.id === movingId);
assert.equal(returned.url, beforeDrop.url);
assert.equal(returned.profileId, beforeDrop.profileId);
assert.equal(returned.canBack, beforeDrop.canBack);
assert.equal(returned.canForward, beforeDrop.canForward);
assert.notEqual(returned.transferToken, beforeDrop.transferToken);
assert.equal(await page.locator('.header .tab').first().locator('.pin').count(), 1);
assert.equal(await page.locator('.browser:visible').getAttribute('data-browser-tab'), movingId);
assert.equal((await state(page)).tabs.length, 2);
await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: 'missing-tab' } }), /Unknown browser tab/);
await painted(page, 1);
await page.screenshot({ path: 'output/browser-returned-tab.png' });
passed.push('the browser-only window returns its live tab by drag and closes when empty');
await action(page, tabs(page).first(), 'Close');
assert.equal((await state(page)).tabs[0].id, firstId);
const another = context.waitForEvent('page');
await action(page, tabs(page).first(), 'Move to new window');
const secondWindow = await another;
secondWindow.setDefaultTimeout(20000);
secondWindow.on('pageerror', error => errors.push(error.message));
await ready(secondWindow, 1);
assert.equal(await tabs(page).count(), 0);
await secondWindow.locator('.surface:visible').focus();
await secondWindow.keyboard.press('Control+t');
await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2);
await ready(secondWindow, 1);
await dragToWindow(context, secondWindow, tabs(secondWindow).first(), page);
await ready(page, 1);
await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 1);
assert.equal((await state(page)).tabs[0].id, firstId);
assert.equal((await state(secondWindow)).tabs.length, 1);
const secondClosed = secondWindow.waitForEvent('close');
await secondWindow.keyboard.press('Control+w');
await secondClosed;
assert.equal((await state(page)).tabs[0].id, firstId);
passed.push('an empty RuneStone tab bar accepts a tab, and the source window keeps its remaining tab');
await action(page, tabs(page).first(), 'Close');
await page.waitForFunction(() => !document.querySelector('.browser'));
assert.equal((await state(page)).tabs.length, 0);
assert.deepEqual(errors, []);
await writeFile('output/browser-tab-actions.json', JSON.stringify({ passed, errors }, null, 2));
for (const label of passed) console.log(`PASS ${label}`);
} catch (error) {
for (const current of browser?.contexts()[0]?.pages() || []) {
if (current !== page) {
console.error(await current.locator('body').innerText().catch(() => ''));
console.error(JSON.stringify((await state(current).catch(() => ({ tabs: [] }))).tabs));
console.error(JSON.stringify(await current.evaluate(() => window.__browserStates).catch(() => [])));
await current.screenshot({ path: 'output/browser-window-failure.png' }).catch(() => {});
}
}
if (page) { await mkdir('output', { recursive: true }); await page.screenshot({ path: 'output/browser-tab-actions-failure.png' }).catch(() => {}); console.error(await page.locator('body').innerText().catch(() => '')); }
throw error;
} finally {
if (page) await ipc(page, 'browser_stop').catch(() => {});
if (browser) await browser.close().catch(() => {});
native.kill();
}
@@ -0,0 +1,14 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { fetchList } from '../src/downloads.mjs';
const directory = new URL('../assets/filters/', import.meta.url);
await mkdir(directory, { recursive: true });
const lists = [
['easylist.txt', 'https://easylist.to/easylist/easylist.txt'],
['easyprivacy.txt', 'https://easylist.to/easylist/easyprivacy.txt'],
];
for (const [file, url] of lists) {
const text = await fetchList(url);
await writeFile(new URL(file, directory), text);
console.log(`${file}: ${Buffer.byteLength(text)} bytes`);
}
await writeFile(new URL('manifest.json', directory), JSON.stringify({ fetchedAt: new Date().toISOString(), lists }, null, 2));
+30
View File
@@ -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 };
}
}
+43
View File
@@ -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);
});
}
+63
View File
@@ -0,0 +1,63 @@
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--; }
});
}
});
emit({ event: 'ready' });
}).catch(error => { console.error(error); app.exit(1); });
}
+319
View File
@@ -0,0 +1,319 @@
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 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, 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-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) => {
item.latestImage = image;
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'), ...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.view.setContentSize(Math.round(args.width * scale), Math.round(args.height * scale));
current.view.webContents.enableDeviceEmulation({ screenPosition: 'desktop', screenSize: { width: args.width, height: args.height },
deviceScaleFactor: scale, viewPosition: { x: 0, y: 0 }, viewSize: { width: args.width, height: args.height }, scale });
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 { wc.stopPainting(); clearTimeout(item.settle); clearTimeout(item.retryFrame); } return null; }
case 'insertText': {
if (typeof args.text !== 'string' || args.text.length > 100000) throw new Error('Invalid browser text.');
await tab(args.tabId).view.webContents.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') wc.focus();
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 };
}
+38
View File
@@ -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;
}
+33
View File
@@ -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 }); }
});
+38
View File
@@ -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(); }
}
+12
View File
@@ -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(); }
}
+93
View File
@@ -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));
},
};
}
+63
View File
@@ -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,
});
+77
View File
@@ -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();
}
}
+35
View File
@@ -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;
}));
}
+17
View File
@@ -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();
}
+18
View File
@@ -0,0 +1,18 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AgentController } from '../src/agent.mjs';
test('agent grants bind profile, tab, document and expiry', () => {
let now = 100;
const tabs = new Map([['a', { profileId: 'agent', epoch: 1 }], ['p', { profileId: 'personal', epoch: 1 }]]);
const agent = new AgentController(id => tabs.get(id), () => now);
assert.throws(() => agent.grant('p', 'agent'));
const token = agent.grant('a', 'agent');
assert.throws(() => agent.authorized(token, 'p'));
assert.equal(agent.authorized(token, 'a'), tabs.get('a'));
tabs.get('a').epoch++;
assert.throws(() => agent.authorized(token, 'a'));
const next = agent.grant('a', 'agent'); now += 300_001;
assert.throws(() => agent.authorized(next, 'a'));
const last = agent.grant('a', 'agent'); agent.revokeAll();
assert.throws(() => agent.authorized(last, 'a'));
});
+187
View File
@@ -0,0 +1,187 @@
import { app, BrowserWindow } from 'electron';
import assert from 'node:assert/strict';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const { createEngine } = await import(process.env.RUNESTONE_TEST_PACKAGE ? pathToFileURL(path.join(process.env.RUNESTONE_TEST_PACKAGE, 'src/engine.mjs')).href : '../src/engine.mjs');
app.enableSandbox();
app.on('window-all-closed', () => {});
app.commandLine.appendSwitch('disable-quic');
app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE 127.0.0.1');
app.setPath('userData', process.env.RS_TEST_ROOT);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const until = async predicate => { for (let attempt = 0; attempt < 100; attempt++) { if (await predicate()) return; await wait(50); } throw new Error('Browser condition timed out.'); };
app.whenReady().then(async () => {
let engine, exitCode = 0;
const passed = [];
try {
const frames = [], external = [], events = [];
engine = await createEngine({ directory: process.env.RS_TEST_ROOT, allowedTestHosts: new Set(['127.0.0.1']), openExternal: async url => { external.push(url); }, emit: value => { if (value.event === 'frame') { frames.push(value); void engine?.command('frameAck', { tabId: value.tabId, frameId: value.frameId }); } else events.push(value); } });
if (process.env.RS_TEST_PHASE === 'restore') {
const plan = JSON.parse(process.env.RS_TEST_PLAN);
await engine.command('commitDuplicate', plan);
const made = await engine.command('newTab', { profileId: plan.id });
await engine.command('navigate', { tabId: made.tabId, input: process.env.RS_TEST_URL });
const wc = engine.tabs.get(made.tabId).view.webContents;
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.match(await wc.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(await wc.executeJavaScript("localStorage.getItem('identity')"), 'source');
await wc.executeJavaScript("localStorage.setItem('identity', 'copy'); document.cookie='login=copy; path=/'; true");
const original = engine.tabs.get(plan.tabs[0].id).view.webContents;
await until(async () => await original.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await original.executeJavaScript("localStorage.getItem('identity')"), 'source');
assert.match(await original.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === plan.id).length, 1);
passed.push('duplicate preserves cookies, local storage and bookmarks without sharing later changes');
} else {
assert.deepEqual(engine.snapshot().profiles, [{ id: 'user', name: 'User' }]);
const first = (await engine.command('newTab')).tabId;
const wc = engine.tabs.get(first).view.webContents;
await until(() => wc.getURL() === 'about:blank');
assert.equal(wc.getURL(), 'about:blank');
await assert.rejects(engine.command('openExternal', { tabId: first }));
assert.deepEqual(external, []);
assert.ok(BrowserWindow.getAllWindows().every(win => !win.isVisible()));
passed.push('one default User profile and no standalone browser window');
assert.equal(engine.snapshot().tabs.find(tab => tab.id === first).favicon, null);
const iconTab = (await engine.command('newTab', { url: process.env.RS_TEST_URL + 'with-icon' })).tabId;
const iconContents = engine.tabs.get(iconTab).view.webContents;
const favicon = () => engine.snapshot().tabs.find(tab => tab.id === iconTab)?.favicon;
await until(() => favicon()?.startsWith('data:image/svg+xml;base64,'));
const originalIcon = favicon();
await iconContents.executeJavaScript(`document.querySelector('link').href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a6XcAAAAASUVORK5CYII='; true`);
await until(() => favicon()?.startsWith('data:image/png;base64,'));
assert.notEqual(favicon(), originalIcon);
await engine.command('navigate', { tabId: iconTab, input: process.env.RS_TEST_URL + 'no-icon' });
await until(() => iconContents.getURL().endsWith('/no-icon') && !iconContents.isLoading());
assert.equal(favicon(), null);
await engine.command('back', { tabId: iconTab });
await until(() => favicon() === originalIcon);
await engine.command('closeTab', { tabId: iconTab });
passed.push('site icons load, update dynamically, clear on navigation, and return with history');
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL + 'slow' });
const slow = await Promise.race([
engine.command('newTab'),
wait(2000).then(() => { throw new Error('Slow homepage blocked the new-tab response.'); }),
]);
const slowContents = engine.tabs.get(slow.tabId).view.webContents;
await until(() => slowContents.isLoading());
assert.ok((await engine.command('state')).tabs.some(tab => tab.id === slow.tabId));
await engine.command('stop', { tabId: slow.tabId });
await engine.command('closeTab', { tabId: slow.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL });
const home = await engine.command('newTab');
const homeContents = engine.tabs.get(home.tabId).view.webContents;
await until(() => homeContents.getURL() === process.env.RS_TEST_URL);
await engine.command('closeTab', { tabId: home.tabId });
const explicit = await engine.command('newTab', { url: 'about:blank' });
await until(() => engine.tabs.get(explicit.tabId).view.webContents.getURL() === 'about:blank');
await engine.command('closeTab', { tabId: explicit.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: '' });
passed.push('homepage loads in new tabs, explicit links override it, and slow pages do not block commands');
await engine.command('settings', { ...engine.snapshot().settings, personalRules: '/blocked-ad.js\n127.0.0.1##.advertisement' });
await engine.command('navigate', { tabId: first, input: process.env.RS_TEST_URL });
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.deepEqual(await wc.executeJavaScript('[typeof require,typeof process,typeof browserHost,typeof window.__TAURI_INTERNALS__]'), ['undefined','undefined','undefined','undefined']);
passed.push('remote content has no Node, native bridge or terminal access');
await until(() => frames.some(frame => frame.tabId === first));
assert.ok(frames.some(frame => frame.width > 100 && frame.height > 100 && frame.data.length > 100 && ['image/png', 'image/jpeg'].includes(frame.mime)));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'char', keyCode: 'x' } });
await until(async () => await wc.executeJavaScript("document.querySelector('input').value") === 'x');
passed.push('offscreen frames and forwarded pointer and keyboard input work');
await engine.command('insertText', { tabId: first, text: '日本語 🙂' });
await until(async () => (await wc.executeJavaScript("document.querySelector('input').value")).endsWith('日本語 🙂'));
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="save-image" src="${process.env.RS_TEST_URL}picture.png" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#save-image").complete'));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.some(event => event.event === 'context-menu' && event.hasImageContents));
const context = events.findLast(event => event.event === 'context-menu');
const downloadPath = path.join(process.env.RS_TEST_ROOT, 'saved-image.png');
const saved = new Promise((resolve, reject) => wc.session.once('will-download', (_event, download) => {
download.setSavePath(downloadPath);
download.once('done', (_event, state) => state === 'completed' ? resolve() : reject(new Error(`Image download: ${state}`)));
}));
await engine.command('contextAction', { tabId: first, token: context.token, action: 'saveImage' });
await saved;
assert.equal((await readFile(downloadPath)).subarray(1, 4).toString(), 'PNG');
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active');
const finding = () => engine.snapshot().tabs.find(tab => tab.id === first).find;
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await until(() => finding()?.matches === 3 && !finding()?.pending);
assert.equal(finding().activeMatch, 1);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true });
await until(() => finding()?.activeMatch === 2 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true, forward: false });
await until(() => finding()?.activeMatch === 1 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'missing phrase' });
await until(() => finding()?.text === 'missing phrase' && !finding()?.pending);
assert.equal(finding().matches, 0);
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await engine.command('stopFind', { tabId: first });
await wait(100);
assert.equal(finding(), null);
await engine.command('find', { tabId: first, text: '' });
assert.equal(finding(), null);
await assert.rejects(engine.command('find', { tabId: first, text: 'x'.repeat(1001) }));
await engine.command('openExternal', { tabId: first });
assert.deepEqual(external, [process.env.RS_TEST_URL]);
passed.push('Find counts matches, moves both ways, clears results, and external opening uses the current web URL');
await wc.executeJavaScript("document.cookie='login=kept; path=/'; localStorage.setItem('identity','source'); true");
await engine.command('bookmark', { tabId: first });
const created = await engine.command('createProfile', { name: 'Research' });
const second = (await engine.command('newTab', { profileId: created.profiles.at(-1).id })).tabId;
await engine.command('navigate', { tabId: second, input: process.env.RS_TEST_URL });
const other = engine.tabs.get(second).view.webContents;
await until(async () => await other.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await other.executeJavaScript('document.cookie'), '');
assert.equal(await other.executeJavaScript("localStorage.getItem('identity')"), null);
const observation = await engine.command('agentSnapshot', { tabId: first });
assert.equal(observation.untrusted, true); assert.equal(observation.profileId, 'user');
passed.push('blank profiles are isolated and agent observation has no special profile name');
await wc.executeJavaScript("document.cookie='selected=root; path=/'; document.cookie='selected=nested; path=/nested'; document.cookie='keep=unchanged; path=/'; true");
await other.executeJavaScript("document.cookie='selected=other-profile; path=/'; true");
let webData = await engine.command('webData', { profileId: 'user' });
assert.ok(webData.cookies.every(cookie => !Object.hasOwn(cookie, 'value')));
const nestedCookie = webData.cookies.find(cookie => cookie.name === 'selected' && cookie.path === '/nested');
assert.ok(nestedCookie);
const openTabs = engine.snapshot().tabs.map(tab => tab.id);
await engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id });
webData = await engine.command('webData', { profileId: 'user' });
assert.ok(!webData.cookies.some(cookie => cookie.id === nestedCookie.id));
assert.ok(webData.cookies.some(cookie => cookie.name === 'selected' && cookie.path === '/'));
assert.ok(webData.cookies.some(cookie => cookie.name === 'keep'));
assert.match(await other.executeJavaScript('document.cookie'), /selected=other-profile/);
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
await assert.rejects(engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id }), /no longer exists/);
await assert.rejects(engine.command('webData', { profileId: 'missing' }), /Unknown profile/);
const visit = webData.history[0];
assert.ok(visit.id);
const otherProfile = created.profiles.at(-1).id;
await assert.rejects(engine.command('removeHistory', { profileId: otherProfile, id: visit.id }), /no longer exists/);
await engine.command('removeHistory', { profileId: 'user', id: visit.id });
const afterRemoval = await engine.command('webData', { profileId: 'user' });
assert.equal(afterRemoval.history.length, webData.history.length - 1);
assert.ok(!afterRemoval.history.some(item => item.id === visit.id));
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === 'user').length, 1);
passed.push('individual cookie and history removal preserves other paths, entries, profiles, bookmarks and tabs');
const plan = await engine.command('prepareDuplicate', { profileId: 'user', name: 'User copy' });
await writeFile(process.env.RS_TEST_ROOT + '/clone-plan.json', JSON.stringify(plan));
}
} catch (error) { console.error(error); exitCode = 1; }
finally {
if (engine) await engine.shutdown();
for (const name of passed) console.log(`PASS ${name}`);
await mkdir('output', { recursive: true });
await writeFile(`output/engine-${process.env.RS_TEST_PHASE || 'initial'}.json`, JSON.stringify({ exitCode, passed, platform: process.platform }, null, 2));
app.exit(exitCode);
}
});
+28
View File
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadFavicon } from '../src/favicon.mjs';
test('icons reject unsafe URLs and non-image responses, then use the next image', async () => {
const requested = [];
const icon = await loadFavicon(['file:///secret.png', 'javascript:alert(1)', 'https://example.com/bad', 'https://example.com/icon'], async url => {
requested.push(url);
return new Response('image', { headers: { 'content-type': url.endsWith('bad') ? 'text/html' : 'image/x-icon' } });
}, new AbortController().signal);
assert.deepEqual(requested, ['https://example.com/bad', 'https://example.com/icon']);
assert.equal(icon, 'data:image/x-icon;base64,aW1hZ2U=');
});
test('icons bound streamed data even without a content-length header', async () => {
const icon = await loadFavicon(['https://example.com/icon'], async () => new Response(new Uint8Array(65537), { headers: { 'content-type': 'image/png' } }), new AbortController().signal);
assert.equal(icon, null);
});
test('cancelled icon work does not make more requests', async () => {
const controller = new AbortController();
let calls = 0;
const icon = await loadFavicon(['https://example.com/one', 'https://example.com/two'], async () => {
calls++; controller.abort(); throw new Error('Aborted');
}, controller.signal);
assert.equal(icon, null);
assert.equal(calls, 1);
});
+14
View File
@@ -0,0 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Filters } from '../src/filters.mjs';
test('bundled filters block ads, apply exceptions and produce CSS without scripts', async () => {
const filters = new Filters();
try {
await filters.load('||ads.fixture.test^\n@@||ads.fixture.test/allowed.js\nfixture.test##.fixture-ad\nfixture.test##+js(alert, injected)');
assert.equal(await filters.match({ url: 'https://ads.fixture.test/ads.js', sourceUrl: 'https://fixture.test', type: 'script' }), true);
assert.equal(await filters.match({ url: 'https://ads.fixture.test/allowed.js', sourceUrl: 'https://fixture.test', type: 'script' }), false);
assert.equal(await filters.match({ url: 'https://google-analytics.com/analytics.js', sourceUrl: 'https://fixture.test', type: 'script' }), true);
const css = await filters.cosmetics({ url: 'https://fixture.test', classes: ['fixture-ad'], ids: [] });
assert.match(css, /fixture-ad/); assert.doesNotMatch(css, /alert|injected/);
} finally { await filters.close(); }
});
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { createGateway } from '../src/gateway.mjs';
function request(gateway, url, authenticated = true) {
return new Promise((resolve, reject) => {
const req = http.get({ host: '127.0.0.1', port: gateway.port, path: url, headers: authenticated ? { 'Proxy-Authorization': `Basic ${Buffer.from(`${gateway.username}:${gateway.password}`).toString('base64')}` } : {} }, res => {
const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString() }));
}); req.on('error', reject);
});
}
test('gateway denies unauthenticated requests, loopback and invalid schemes', async () => {
const gateway = await createGateway();
try {
assert.equal((await request(gateway, 'http://127.0.0.1/', false)).status, 407);
assert.equal((await request(gateway, 'http://127.0.0.1/')).status, 403);
assert.equal((await request(gateway, 'file:///etc/passwd')).status, 403);
assert.equal((await request(gateway, 'http://1.1.1.1:1234/')).status, 403);
} finally { await gateway.close(); }
});
test('gateway connects to the validated address and strips proxy credentials', async () => {
const server = http.createServer((req, res) => { assert.equal(req.headers['proxy-authorization'], undefined); res.end(req.headers.host); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let lookups = 0;
const gateway = await createGateway({ allowedTestHosts: new Set(['fixture.test']), resolver: async () => { lookups++; return [{ address: '127.0.0.1', family: 4 }]; } });
try {
const result = await request(gateway, `http://fixture.test:${server.address().port}/`);
assert.equal(result.status, 200); assert.match(result.body, /^fixture.test:/); assert.equal(lookups, 1);
await gateway.close();
await assert.rejects(request(gateway, 'http://fixture.test/'));
} finally { await new Promise(resolve => server.close(resolve)); }
});
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { WheelQueue } from '../../src/lib/browser/inputQueue.ts';
import { AutoScroll } from '../../src/lib/browser/autoScroll.ts';
import { FrameDelivery } from '../src/frame-delivery.mjs';
test('wheel bursts keep one pending call and discard stale direction', async () => {
const calls = [], releases = [];
const queue = new WheelQueue(input => { calls.push(input); return new Promise(resolve => releases.push(resolve)); });
const wheel = deltaY => ({ type: 'mouseWheel', x: 10, y: 10, deltaX: 0, deltaY });
queue.push(wheel(-100));
for (let index = 0; index < 500; index++) queue.push(wheel(-100));
queue.push(wheel(120));
assert.equal(calls.length, 1);
releases.shift()(); await Promise.resolve();
assert.equal(calls.length, 2);
assert.equal(calls[1].deltaY, 120);
queue.push(wheel(100)); queue.clear(); releases.shift()(); await Promise.resolve();
assert.equal(calls.length, 2);
queue.close(); queue.push(wheel(100)); assert.equal(calls.length, 2);
});
test('middle scrolling retains useful speed and has a quiet center', () => {
const scroll = new AutoScroll(); scroll.start({ x: 100, y: 100 }); scroll.delta(1000);
scroll.move({ x: 105, y: 105 }); assert.deepEqual(scroll.delta(1016), { x: 0, y: 0 });
scroll.move({ x: 100, y: 200 }); assert.ok(scroll.delta(1032).y >= 25);
scroll.release(); assert.equal(scroll.anchor, null);
});
test('frame delivery bounds the backlog and recovers after an abandoned view', () => {
const frames = new FrameDelivery(); const first = frames.sent(0); frames.sent(1);
assert.equal(frames.canSend(2), false); frames.acknowledge(first);
assert.equal(frames.canSend(3), true); frames.sent(3);
assert.equal(frames.canSend(4), false); assert.equal(frames.canSend(254), true);
});
@@ -0,0 +1,24 @@
// This IPC adapter exists only for the browser UI smoke test.
import { app } from 'electron';
import { createEngine } from '../src/engine.mjs';
app.enableSandbox();
app.setPath('userData', process.env.RS_INTERACTION_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let framePending = false;
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
} });
process.on('message', async ({ id, command, args }) => {
try {
let result;
if (command === 'testEvaluate') result = await engine.tabs.get(args.tabId).view.webContents.executeJavaScript(args.code);
else if (command === 'shutdown') { await engine.shutdown(); process.send?.({ id, result: null }); app.exit(0); return; }
else result = await engine.command(command, args);
process.send?.({ id, result });
} catch (error) { process.send?.({ id, error: String(error) }); }
});
process.on('disconnect', () => { void engine.shutdown().finally(() => app.exit(0)); });
process.send?.({ ready: true });
});
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
if (!process.versions.electron) {
const { spawn } = await import('node:child_process');
const { default: electron } = await import('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-performance-'));
const child = spawn(electron, [import.meta.filename, ...process.argv.slice(2)], {
windowsHide: true, stdio: 'inherit', env: { ...process.env, RS_PERFORMANCE_ROOT: root },
});
const timeout = setTimeout(() => child.kill(), 45_000);
process.exitCode = await new Promise((resolve, reject) => { child.once('exit', code => resolve(code ?? 1)); child.once('error', reject); });
clearTimeout(timeout);
} else {
const { app } = await import('electron');
const { createEngine } = await import('../src/engine.mjs');
app.enableSandbox();
app.setPath('userData', process.env.RS_PERFORMANCE_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let engine, code = 0;
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const frames = [];
let writable = true;
try {
engine = await createEngine({ directory: process.env.RS_PERFORMANCE_ROOT, canEmitFrame: () => writable, emit: value => {
if (value.event === 'frame') { frames.push({ time: performance.now(), bytes: value.data.length, tabId: value.tabId, data: value.data, mime: value.mime }); void engine?.command('frameAck', { tabId: value.tabId, frameId: value.frameId }); }
} });
const { tabId } = await engine.command('newTab');
const wc = engine.tabs.get(tabId).view.webContents;
if (wc.isLoading()) await new Promise(resolve => wc.once('did-stop-loading', resolve));
await engine.command('resize', { tabId, width: 1280, height: 800 });
await engine.command('visible', { tabId, visible: true });
await wc.executeJavaScript(`document.body.innerHTML = '<div style="height:6000px;background:linear-gradient(white,steelblue)"><canvas width="1280" height="720"></canvas></div>';
const c = document.querySelector('canvas').getContext('2d'); let tick = 0;
function paint() { c.fillStyle = '#fafafa'; c.fillRect(0,0,1280,720);
for (let i=0;i<80;i++) { c.fillStyle = 'hsl('+i*7+' 60% 50%)'; c.fillRect((i*71+tick*3)%1280,(i*39)%720,30,30); }
tick++; if (!window.stopAnimation) requestAnimationFrame(paint); } paint(); true;`);
await wait(750);
frames.length = 0;
const started = performance.now();
await wait(3000);
const elapsed = performance.now() - started;
const fps = frames.length * 1000 / elapsed;
const gaps = frames.slice(1).map((frame, index) => frame.time - frames[index].time).sort((a,b) => a-b);
const result = { configuredFps: wc.getFrameRate(), frames: frames.length, elapsedMs: Math.round(elapsed), fps: Number(fps.toFixed(1)), p95FrameGapMs: Math.round(gaps[Math.floor(gaps.length * .95)]), meanEncodedBytes: Math.round(frames.reduce((n,f) => n+f.bytes,0)/frames.length), viewport: '1280x800', platform: process.platform };
if (!process.argv.includes('--baseline')) { assert.equal(wc.getFrameRate(), 60); assert.ok(fps >= 24, `Native frame delivery must exceed 24 FPS: ${JSON.stringify(result)}`); }
await engine.command('input', { tabId, input: { type: 'mouseMove', x: 400, y: 400 } });
for (let n=0;n<20;n++) { await engine.command('input', { tabId, input: { type: 'mouseWheel', x: 400, y: 400, deltaY: -30, deltaX: 0 } }); await wait(16); }
await wait(150);
assert.ok(await wc.executeJavaScript('scrollY') > 100, 'Forwarded wheel input must scroll the native page.');
await engine.command('visible', { tabId, visible: false });
await wait(150); frames.length = 0; await wait(300);
assert.equal(frames.length, 0, 'Hidden tabs must stop sending frames.');
await engine.command('visible', { tabId, visible: true });
await wait(200); assert.ok(frames.length > 0, 'Visible tabs must resume frames.');
writable = false; frames.length = 0; await wait(200);
assert.equal(frames.length, 0, 'A busy transport must skip frames before encoding.');
writable = true; await wait(200);
assert.ok(frames.length > 0, 'Frames resume when the transport can accept them.');
const { nativeImage } = await import('electron');
frames.length = 0;
await engine.command('resize', { tabId, width: 1280, height: 800, scale: 2 });
await wait(500);
const highDpi = frames.at(-1);
const pixels = nativeImage.createFromDataURL(`data:${highDpi.mime};base64,${highDpi.data}`).getSize();
assert.ok(pixels.width >= 2560 && pixels.width <= 2562 && pixels.height >= 1600 && pixels.height <= 1602,
`High DPI must render physical pixels, allowing native window rounding: ${JSON.stringify(pixels)}`);
assert.equal(await wc.executeJavaScript('innerWidth'), 1280, 'High DPI keeps CSS page dimensions.');
result.highDpiPixels = pixels;
writable = false;
await wc.executeJavaScript('window.stopAnimation = true; document.body.style.background = "red"; true;');
await wait(400); frames.length = 0;
writable = true; await wait(300);
assert.ok(frames.some(frame => frame.mime === 'image/png'), 'The final lossless static frame must resume after transport backpressure ends.');
await mkdir('output', { recursive: true });
await writeFile(`output/performance-${process.argv.includes('--baseline') ? 'before' : 'after'}.json`, JSON.stringify(result, null, 2));
console.log(JSON.stringify(result));
console.log('PASS native scrolling, hidden frame pause, visible frame resume');
} catch (error) { console.error(error); code = 1; }
finally { await engine?.shutdown(); app.exit(code); }
});
}
+22
View File
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { addressInput, webUrl, publicAddress, resolvePublic } from '../src/policy.mjs';
test('addresses reject active schemes, credentials, controls and malformed URLs', () => {
for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'data:text/html,hi', 'runestone-ui://shell', 'https://user:[email protected]', 'https://example.com\n']) assert.throws(() => webUrl(url));
assert.equal(addressInput('a & b'), 'https://duckduckgo.com/?q=a%20%26%20b');
assert.equal(addressInput('example.com'), 'https://example.com/');
assert.equal(addressInput(''), 'about:blank');
assert.equal(addressInput('test query', 'bing'), 'https://www.bing.com/search?q=test%20query');
});
test('private, mapped, multicast and reserved addresses are blocked', () => {
for (const address of ['127.0.0.1', '10.0.0.1', '169.254.169.254', '192.168.1.2', '172.31.0.1', '100.64.1.1', '0.0.0.0', '224.0.0.1', '::1', '::', 'fc00::1', 'fe80::1', '::ffff:127.0.0.1', '2001:db8::1']) assert.equal(publicAddress(address), false, address);
assert.equal(publicAddress('1.1.1.1'), true);
assert.equal(publicAddress('2606:4700:4700::1111'), true);
});
test('DNS policy rejects mixed public/private answers and pins a validated result', async () => {
await assert.rejects(resolvePublic('example.test', async () => [{ address: '1.1.1.1', family: 4 }, { address: '127.0.0.1', family: 4 }]));
let calls = 0;
const address = await resolvePublic('example.test', async () => { calls++; return [{ address: '1.1.1.1', family: 4 }]; });
assert.equal(calls, 1); assert.equal(address.address, '1.1.1.1');
});
+8
View File
@@ -0,0 +1,8 @@
{
"identifier": "com.runestone.browser-test",
"productName": "RuneStone Browser Test",
"app": {
"windows": [{ "label": "main", "title": "RuneStone browser test (isolated)", "visible": false, "width": 1400, "height": 900, "decorations": false, "dragDropEnabled": false }]
},
"bundle": { "resources": { "browser-engine/": "browser-engine/" } }
}
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { SnapshotOrder } from '../../src/lib/browser/snapshotOrder.ts';
test('late command replies cannot overwrite final Find results', () => {
const order = new SnapshotOrder();
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 1 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 3 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 2 }), false);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 3 }), false);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 4 }), true);
});
test('a new runtime resets the revision and rejects replies from the retired runtime', () => {
const order = new SnapshotOrder();
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 100 }), true);
assert.equal(order.accept({ runtimeId: 'engine-b', revision: 1 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 101 }), false);
});
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/store.mjs';
test('profiles and bookmarks persist without accepting caller-provided paths', () => {
const directory = mkdtempSync(path.join(os.tmpdir(), 'runestone-store-'));
try {
const store = new Store(directory);
assert.equal(store.data.settings.adblock, true);
assert.equal(store.data.settings.search, 'duckduckgo');
assert.deepEqual(store.data.profiles, [{ id: 'user', name: 'User' }]);
const profile = store.createProfile('../name-is-only-a-label');
assert.match(profile.id, /^[a-f0-9-]{36}$/);
store.bookmark(profile.id, 'https://example.com/', '<script>test</script>');
const restored = new Store(directory);
assert.equal(restored.data.bookmarks[0].profileId, profile.id);
assert.throws(() => store.profile('../../other'));
assert.throws(() => store.bookmark('user', 'javascript:alert(1)', 'unsafe'));
} finally { rmSync(directory, { recursive: true, force: true }); }
});
test('browser settings migrate, persist and reject invalid homepages and lists atomically', () => {
const directory = mkdtempSync(path.join(os.tmpdir(), 'runestone-settings-'));
try {
const legacy = new Store(directory);
delete legacy.data.settings.homepage; delete legacy.data.settings.filterLists;
writeFileSync(legacy.file, JSON.stringify(legacy.data));
const store = new Store(directory);
assert.equal(store.data.settings.homepage, '');
assert.equal(store.data.settings.filterLists.length, 2);
store.configure({ ...store.data.settings, homepage: ' https://example.com/home ', filterLists: ['https://example.com/list.txt'], linkDestination: 'external', adblock: false });
const saved = structuredClone(store.data.settings);
assert.deepEqual(new Store(directory).data.settings, saved);
for (const homepage of ['javascript:alert(1)', 'file:///C:/secret', 'https://user:[email protected]', 'search words']) {
assert.throws(() => store.configure({ ...saved, homepage }));
assert.deepEqual(store.data.settings, saved);
}
for (const filterLists of [['http://example.com/list'], ['https://example.com:444/list'], Array(9).fill('https://example.com/list'), 'not-an-array']) {
assert.throws(() => store.configure({ ...saved, filterLists }));
assert.deepEqual(new Store(directory).data.settings, saved);
}
store.configure({ ...saved, homepage: '', filterLists: [] });
assert.equal(new Store(directory).data.settings.homepage, '');
assert.deepEqual(new Store(directory).data.settings.filterLists, []);
} finally { rmSync(directory, { recursive: true, force: true }); }
});
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { Filters } from '../src/filters.mjs';
import { loadLists } from '../src/subscriptions.mjs';
import { fetchList } from '../src/downloads.mjs';
test('custom lists download once, work offline and stop blocking when removed', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-lists-'));
const filters = new Filters();
try {
let downloads = 0;
const addresses = ['https://filters.example.com/custom.txt'];
const options = { directory, download: true, fetch: async () => { downloads++; return '||custom-ad.fixture.test^'; } };
await filters.load('', addresses, options);
const request = { url: 'https://custom-ad.fixture.test/a.js', sourceUrl: 'https://fixture.test/', type: 'script' };
assert.equal(await filters.match(request), true);
await filters.load('', addresses, { directory });
assert.equal(await filters.match(request), true);
assert.equal(downloads, 1);
await filters.load('', []);
assert.equal(await filters.match(request), false);
await assert.rejects(loadLists(['https://filters.example.com/missing.txt'], { directory }), /missing/);
await assert.rejects(fetchList('https://127.0.0.1/list.txt'), /private network/);
await assert.rejects(fetchList('file:///secret.txt'), /HTTP/);
} finally { await filters.close(); await rm(directory, { recursive: true, force: true }); }
});
+204
View File
@@ -0,0 +1,204 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { TabSession } from '../../src/lib/browser/tabSession.ts';
function runtime() {
const tabs = new Map(), calls = [];
let sequence = 0;
const snapshot = () => ({ profiles: [{ id: 'user' }], tabs: [...tabs.values()], bookmarks: [], settings: {} });
const request = async (command, args = {}) => {
calls.push({ command, args });
if (command === 'state') return snapshot();
if (command === 'newTab') {
const id = `runtime-${++sequence}`;
tabs.set(id, { id, profileId: args.profileId, url: args.url || 'about:blank' });
return { tabId: id };
}
if (!tabs.has(args.tabId)) throw new Error('Unknown browser tab.');
if (command === 'closeTab') tabs.delete(args.tabId);
return snapshot();
};
return { tabs, calls, request, snapshot };
}
test('a moved tab keeps its runtime identity and survives source cleanup', async () => {
const engine = runtime();
const source = new TabSession(engine.request, { url: 'https://example.com/' }, () => {});
await source.connect();
const tabId = source.value.tabId;
source.detach();
await source.close();
const target = new TabSession(engine.request, { tabId }, () => {});
await target.connect();
assert.equal(target.value.tabId, tabId);
assert.equal(target.value.url, 'https://example.com/');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
await target.close();
assert.equal(engine.tabs.size, 0);
});
for (const reason of [
'The browser stopped responding. Open a new browser tab to restart it.',
'An existing connection was forcibly closed by the remote host. (os error 10054)',
'An established connection was aborted by the software in your host machine. (os error 10053)',
]) for (const failureAt of [1, 2, 3]) {
test(`opening recovers at request ${failureAt}: ${reason}`, async () => {
const engine = runtime(), phases = []; let requests = 0;
const session = new TabSession(async (command, args) => {
if (++requests === failureAt) {
engine.tabs.clear();
throw new Error(reason);
}
return engine.request(command, args);
}, { profileId: 'research', url: 'https://example.com/bookmark' }, value => phases.push(value.phase));
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(engine.tabs.size, 1);
assert.equal(engine.tabs.get(session.value.tabId).profileId, 'research');
assert.equal(engine.tabs.get(session.value.tabId).url, 'https://example.com/bookmark');
assert.ok(!phases.includes('disconnected'));
});
}
test('a failed state response reuses a tab that still exists', async () => {
const engine = runtime(); let requests = 0;
const session = new TabSession((command, args) => {
if (++requests === 3) throw new Error('The browser stopped responding.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-1');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
});
test('repeated opening failures stop after one retry and allow manual reconnect', async () => {
const engine = runtime(); let requests = 0, fail = true;
const session = new TabSession((command, args) => {
requests++;
if (fail) throw new Error('The browser stopped responding.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
assert.equal(requests, 2);
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'state');
assert.match(session.value.detail.reason, /stopped responding/);
await session.send('resize');
assert.equal(requests, 2);
fail = false;
await session.connect();
assert.equal(session.value.phase, 'ready');
});
test('an invalid profile does not retry tab creation', async () => {
const engine = runtime(); let creates = 0;
const session = new TabSession((command, args) => {
if (command === 'newTab') { creates++; throw new Error('Unknown browser profile.'); }
return engine.request(command, args);
}, { profileId: 'missing' }, () => {});
await session.connect();
assert.equal(creates, 1);
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'newTab');
});
test('closing while the first request fails prevents the retry', async () => {
let rejectRequest, requests = 0;
const session = new TabSession(() => {
requests++;
return new Promise((_resolve, reject) => { rejectRequest = reject; });
}, {}, () => {});
const opening = session.connect();
assert.equal(session.connect(), opening);
await session.close();
rejectRequest(new Error('The browser stopped responding.'));
await opening;
assert.equal(requests, 1);
assert.equal(session.value.phase, 'closed');
});
test('a restart during the first open creates a valid replacement tab', async () => {
const engine = runtime(); let restart = true;
const session = new TabSession(async (...args) => {
const value = await engine.request(...args);
if (args[0] === 'newTab' && restart) { restart = false; engine.tabs.clear(); }
return value;
}, { profileId: 'user', url: 'https://example.com/' }, () => {});
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(engine.tabs.size, 1);
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(engine.tabs.get('runtime-2').url, 'https://example.com/');
});
test('connection loss restores the same profile and URL without repeating input', async () => {
const engine = runtime();
const session = new TabSession(engine.request, { profileId: 'research', url: 'https://example.com/' }, () => {});
await session.connect(); engine.tabs.clear();
await session.send('input', { input: { type: 'char', keyCode: 'x' } });
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(engine.calls.filter(call => call.command === 'input').length, 1);
assert.equal(engine.tabs.get('runtime-2').profileId, 'research');
assert.equal(session.value.detail.operation, 'input');
assert.match(session.value.detail.reason, /Unknown browser tab/);
});
test('failed recovery stops background requests and keeps a specific retry error', async () => {
const engine = runtime(); let fail = false;
const session = new TabSession((command, args) => {
if (fail && command === 'newTab') throw new Error('The browser runtime is missing.');
return engine.request(command, args);
}, {}, () => {});
await session.connect(); engine.tabs.clear(); fail = true;
await session.send('resize', { width: 900, height: 600 });
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'newTab');
assert.match(session.value.detail.reason, /runtime is missing/);
const requests = engine.calls.length;
await session.send('input'); await session.send('visible');
assert.equal(engine.calls.length, requests);
fail = false; await session.connect();
assert.equal(session.value.phase, 'ready');
});
test('late errors from the old tab cannot break the replacement', async () => {
const engine = runtime(); let rejectOld;
const session = new TabSession((command, args) => command === 'input'
? new Promise((_resolve, reject) => rejectOld = reject) : engine.request(command, args), {}, () => {});
await session.connect();
const pending = session.send('input'); engine.tabs.clear();
await session.send('resize');
rejectOld(new Error('Old tab timed out.')); await pending;
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(session.value.detail.operation, 'resize');
});
test('closing during creation removes the late tab and leaves no running view', async () => {
const engine = runtime(); let finish;
const session = new TabSession((command, args) => command === 'newTab'
? new Promise(resolve => finish = () => resolve(engine.request(command, args))) : engine.request(command, args), {}, () => {});
const starting = session.connect();
await new Promise(resolve => setImmediate(resolve));
await session.close(); finish(); await starting;
assert.equal(session.value.phase, 'closed');
assert.equal(engine.tabs.size, 0);
});
test('an invalid address keeps the tab usable and does not restart it', async () => {
const engine = runtime();
const session = new TabSession((command, args) => {
if (command === 'navigate' && args.input.startsWith('javascript:')) throw new Error('Use an HTTP or HTTPS address without embedded credentials.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
await session.send('navigate', { input: 'javascript:alert(1)' });
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-1');
assert.match(session.value.detail.reason, /HTTP or HTTPS/);
await session.send('navigate', { input: 'https://example.com/' });
assert.equal(session.value.message, '');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
});