RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+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'));
});
+259
View File
@@ -0,0 +1,259 @@
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');
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('focus', { tabId: first, focused: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
wc.debugger.detach();
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('visible', { tabId: first, visible: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('visible', { tabId: first, visible: true });
await engine.command('focus', { tabId: first, focused: true });
await assert.rejects(engine.command('focus', { tabId: first, focused: 'true' }), /Invalid browser focus/);
passed.push('offscreen focus supports the caret, blur, hidden tabs, and debugger reattachment');
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');
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
const menus = events.length;
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.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
const imageMenu = events.findLast(event => event.event === 'context-menu');
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
const bytes = Buffer.from(part.data, 'base64');
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
assert.equal(bytes.length, 85);
assert.equal(part.next, null);
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
// A large image comes in parts that stay below the line limit of the host.
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
const largeMenus = events.length;
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.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
const parts = [];
for (let offset = 0; offset !== null;) {
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
assert.ok(next.data.length <= 4_000_000);
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
}
const whole = Buffer.concat(parts);
assert.ok(parts.length >= 3);
assert.equal(whole.length, large.size);
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
assert.equal(whole.at(-1), 0x3b);
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
// A middle-click asks for the link under the pointer. Only web links count.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');true;`);
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` });
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null });
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null });
await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/);
await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;');
// An image that opens as the page itself is the main resource of the tab.
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
const directContents = engine.tabs.get(direct).view.webContents;
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
const directMenus = events.length;
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
await engine.command('closeTab', { tabId: direct });
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
passed.push('A middle-click finds the web link under the pointer');
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,25 @@
// 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;
// The fixture server of the smoke test is on 127.0.0.1. The engine blocks local addresses for other hosts.
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, allowedTestHosts: new Set(['127.0.0.1']), 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,13 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { packageTarget } from '../scripts/package-target.mjs';
test('packaging uses native defaults and validates each option independently', () => {
assert.deepEqual(packageTarget([], { platform: 'linux', arch: 'arm64' }), { platform: 'linux', arch: 'arm64' });
assert.deepEqual(packageTarget(['--platform=linux', '--arch=x64'], { platform: 'win32', arch: 'arm64' }), { platform: 'linux', arch: 'x64' });
for (const args of [['--platform=x64'], ['--arch=linux'], ['--arch=x64', '--arch=arm64'], ['--unknown=linux']]) {
assert.throws(() => packageTarget(args), /Use --platform/);
}
assert.deepEqual(packageTarget([], { platform: 'darwin', arch: 'arm64' }), { platform: 'darwin', arch: 'arm64' });
assert.throws(() => packageTarget([], { platform: 'linux', arch: 'ia32' }), /Unsupported/);
});
@@ -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');
});
+7
View File
@@ -0,0 +1,7 @@
{
"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 }]
}
}
@@ -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);
});
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdtemp, mkdir, writeFile, readFile, readdir, chmod, rm, stat, symlink, rename } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { stageRuntime } from '../scripts/stage-runtime.mjs';
async function fixture(t) {
const root = await mkdtemp(join(tmpdir(), 'runestone-stage-test-'));
t.after(() => rm(root, { recursive: true, force: true }));
const project = join(root, 'browser-runtime');
const source = join(project, 'dist/RuneStone-Browser-linux-x64');
const destination = join(root, 'src-tauri/browser-engine');
await mkdir(source, { recursive: true });
await chmod(source, 0o755);
await mkdir(destination, { recursive: true });
await writeFile(join(source, 'RuneStone-Browser'), 'fixture', { mode: 0o755 });
await writeFile(join(destination, 'RuneStone-Browser.exe'), 'old runtime');
return { project, host: root, source, destination, platform: 'linux', arch: 'x64' };
}
test('staging replaces a foreign runtime tree and preserves a recoverable backup', async t => {
const options = await fixture(t);
const result = await stageRuntime(options);
assert.deepEqual(await readdir(options.destination), ['RuneStone-Browser']);
if (process.platform !== 'win32') {
assert.equal((await stat(options.destination)).mode & 0o777, 0o755);
assert.equal((await stat(join(options.destination, 'RuneStone-Browser'))).mode & 0o777, 0o755);
}
assert.equal(await readFile(join(result.backup, 'RuneStone-Browser.exe'), 'utf8'), 'old runtime');
assert.equal(await readFile(join(options.source, 'RuneStone-Browser'), 'utf8'), 'fixture');
});
test('missing source leaves the previous runtime intact', async t => {
const options = await fixture(t);
await assert.rejects(stageRuntime({ ...options, arch: 'arm64' }), /ENOENT/);
assert.equal(await readFile(join(options.destination, 'RuneStone-Browser.exe'), 'utf8'), 'old runtime');
});
test('macOS staging preserves the app bundle and executable layout', async t => {
const options = await fixture(t);
const source = join(options.project, 'dist/RuneStone-Browser-darwin-arm64');
const executable = 'RuneStone-Browser.app/Contents/MacOS/RuneStone-Browser';
await mkdir(join(source, 'RuneStone-Browser.app/Contents/MacOS'), { recursive: true });
await writeFile(join(source, executable), 'macOS fixture', { mode: 0o755 });
await writeFile(join(source, 'RuneStone-Browser.app/Contents/Info.plist'), 'bundle metadata');
if (process.platform !== 'win32') {
await symlink('../Info.plist', join(source, 'RuneStone-Browser.app/Contents/MacOS/metadata'));
}
const result = await stageRuntime({ ...options, platform: 'darwin', arch: 'arm64' });
await rename(source, `${source}-moved`);
assert.equal(await readFile(join(result.destination, executable), 'utf8'), 'macOS fixture');
assert.equal(await readFile(join(result.destination, 'RuneStone-Browser.app/Contents/Info.plist'), 'utf8'), 'bundle metadata');
assert.equal(await readFile(join(result.backup, 'RuneStone-Browser.exe'), 'utf8'), 'old runtime');
if (process.platform !== 'win32') {
assert.equal(await readFile(join(result.destination, 'RuneStone-Browser.app/Contents/MacOS/metadata'), 'utf8'), 'bundle metadata');
}
});
test('Linux staging rejects a non-executable runtime before replacing the old tree', { skip: process.platform === 'win32' }, async t => {
const options = await fixture(t);
await chmod(join(options.source, 'RuneStone-Browser'), 0o644);
await assert.rejects(stageRuntime(options), /EACCES/);
assert.equal(await readFile(join(options.destination, 'RuneStone-Browser.exe'), 'utf8'), 'old runtime');
});
test('Windows staging retains the exe layout without Linux execute permissions', async t => {
const options = await fixture(t);
const source = join(options.project, 'dist/RuneStone-Browser-win32-x64');
await mkdir(source, { recursive: true });
await writeFile(join(source, 'RuneStone-Browser.exe'), 'windows fixture', { mode: 0o644 });
const result = await stageRuntime({ ...options, platform: 'win32' });
assert.deepEqual(await readdir(result.destination), ['RuneStone-Browser.exe']);
assert.equal(await readFile(join(result.destination, 'RuneStone-Browser.exe'), 'utf8'), 'windows fixture');
});
test('Linux staging normalizes a private packager output root for installation', { skip: process.platform === 'win32' }, async t => {
const options = await fixture(t);
await chmod(options.source, 0o700);
const result = await stageRuntime(options);
assert.equal((await stat(result.destination)).mode & 0o777, 0o755);
assert.equal((await stat(options.source)).mode & 0o777, 0o700);
});
+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);
});