Add hosted service-worker streaming downloads

This commit is contained in:
Schluffe committed 2026-10-16 13:49:17 +02:00
1 parent a53022d717
commit 7856725c72
8 files changed
+344 -17

No files matched your search

+39 -1
View File
@@ -4,7 +4,8 @@ import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDis
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -13,6 +14,7 @@ const axeSource = await readFile(join(root, 'node_modules/axe-core/axe.min.js'),
const provider = process.argv.includes('--default-network') ? 'pagequit' : 'none';
const turn = process.argv.includes('--turn');
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
const streaming = process.argv.includes('--stream-download');
const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null;
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
const server = createServer(async (req, res) => {
@@ -36,6 +38,7 @@ const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [
'--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
interface ProtocolResults {
'Browser.setDownloadBehavior': object;
'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string };
'Runtime.enable': object;
@@ -94,6 +97,7 @@ async function page(url = origin) {
await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId);
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
if (streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId);
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url }, sessionId);
for (let n = 0; n < 100; n++) {
@@ -159,6 +163,38 @@ async function connect(sender: string, receiver: string, size: number) {
}
}
try {
if (streaming) {
const downloads = join(profile, 'downloads');
await mkdir(downloads);
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
const sender = await page();
for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) {
const receiver = await page();
await click(receiver, 'Receive');
await connect(sender, receiver, size);
assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined');
await click(receiver, 'Receive as download (up to 64 GiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
const destination = join(downloads, 'browser-test.bin');
const deadline = Date.now() + 30000;
while (true) {
try { if ((await stat(destination)).size === size) break; } catch {}
if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.');
await new Promise(resolve => setTimeout(resolve, 100));
}
let bytes = 0;
for await (const chunk of createReadStream(destination)) {
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
bytes += (chunk as Buffer).length;
}
assert.equal(bytes, size);
await rm(destination);
await click(sender, 'Reset');
console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`);
}
assert.deepEqual(browserErrors, []);
} else {
const sender = await page(), receiver = await page();
if (!turn) {
assert.equal(await evaluate(sender, () => document.querySelector<HTMLSelectElement>('#stun-provider')?.value), 'pagequit');
@@ -172,6 +208,7 @@ try {
assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true);
const localSender = await page(localUrl);
await connect(localSender, localReceiver, 1024);
assert.equal(await evaluate(localReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent?.includes('Receive as download'))), false, 'file:// must not offer service-worker downloads');
await click(localReceiver, 'Receive in memory (up to 64 MiB)');
await wait(localReceiver, () => !!document.querySelector('a.download'));
const data = await evaluate(localReceiver, async () => {
@@ -231,6 +268,7 @@ try {
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
assert.deepEqual(browserErrors, []);
}
} finally {
browser.kill();
await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });