Add file transfer PoC with manual and tracker signaling

- Core in src/main.ts: manual SDP copy/paste exchange (default, no
  tracker) and optional WebTorrent tracker signaling, STUN opt-out
- Fingerprint security check, sender confirms before sending
- ICE gathering stops after the first STUN result (5 s hard cap)
- Receiver writes to OPFS via an inline dedicated worker instead of RAM
- Playwright e2e suite across Chromium/Firefox and all signaling modes,
  opt-in 2.5 GiB transfer test (pnpm test:large)
- TODO.md with review findings and the service worker plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-22 00:35:36 +02:00
1 parent 24307eb96a
commit aea75fff92
8 files changed
+670 -4

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ dist
.env .env
.env.* .env.*
!.env.example !.env.example
test-results
+57
View File
@@ -0,0 +1,57 @@
# TODO
## Next: service worker streaming download
Stream received bytes straight into the browser's download manager instead of staging them in OPFS.
Needs one new file (service workers can only be registered from a real same-origin script).
- Removes the OPFS staging copy, so the file no longer takes twice the disk space.
- Removes the OPFS quota cap (~10 GiB per site, 2000 MiB in Chromium incognito).
- Fixes "Opening another tab breaks existing downloads" below completely.
## Review findings
### [P2] Opening another tab breaks existing downloads
`clearStorage()` runs on startup and deletes every OPFS entry. OPFS is shared by all tabs of the
origin, so it also deletes the file behind another tab's not yet clicked download link.
- Real fix: Web Locks. Each tab holds a lock named after every file it received (released by the
browser when the tab closes or crashes). Cleanup only removes entries whose lock is free
(`navigator.locks.request(name, { ifAvailable: true }, ...)`).
- Fixed by the service worker download: no OPFS staging, nothing to clean up.
### [P2] Disk writes have no flow control
Chunks go data channel → main thread → worker message queue → disk without waiting for writes. If
storage is slower than the network (SD card, HDD, throttled background tab), queued buffers grow
without bound in RAM.
- Real fix: application level acknowledgements. The receiving side cannot pause a data channel,
so the worker reports its written offset, the receiver sends it to the sender over the data
channel, and the sender keeps at most a fixed window (e.g. 8 MiB) unacknowledged, on top of the
existing `bufferedAmount` check.
- Not fixed by the service worker: stream backpressure stops at the receiver, it still has to
reach the sender.
- Bonus: the acknowledged offset is the basis for resuming interrupted transfers.
### [P2] Storage failures don't stop the transfer
A write failure is only logged on the receiver. The sender keeps sending and reports "sent", which
only means "handed to the send buffer".
- Real fix:
1. Check `navigator.storage.estimate()` against the announced size before accepting, optionally
`navigator.storage.persist()` (raises Firefox's limit after a prompt).
2. Report errors to the sender (`{ error }` message or closing the channel), sender stops.
3. Receiver sends "done" only after the final flush, sender shows "delivered" only then.
- Partly fixed by the service worker: the quota failure goes away, but download errors and user
cancels still have to be reported to the sender.
- Points 2 and 3 share the receiver → sender control channel with the flow control fix, build them
together.
## Open observations
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
+168
View File
@@ -0,0 +1,168 @@
import { createHash, randomBytes } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { open as openFile, writeFile } from 'node:fs/promises';
import { chromium, expect, firefox, test, type Browser, type BrowserType, type Page } from '@playwright/test';
import { createServer, type ViteDevServer } from 'vite';
// Runs against the real public trackers and STUN servers from src/main.ts.
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
const SIZE = 5_000_000;
// Opt-in with LARGE=1: beyond the 2000 MiB Chromium stores in incognito-like contexts, and far
// beyond what the old in-memory receiver handled.
const LARGE_SIZE = 2.5 * 2 ** 30;
// Each mode connects a sender page that already picked a file to a receiver page.
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
async manual(sender, receiver) {
await sender.click('#create-offer');
await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
await receiver.fill('#offer-input', await sender.inputValue('#offer'));
await receiver.click('#create-answer');
await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 });
await sender.fill('#answer-input', await receiver.inputValue('#answer'));
await sender.click('#accept-answer');
},
async offline(sender, receiver) {
await sender.uncheck('#stun');
await receiver.uncheck('#stun');
await MODES.manual!(sender, receiver);
for (const code of [await sender.inputValue('#offer'), await receiver.inputValue('#answer')]) {
expect(Buffer.from(code, 'base64').toString()).not.toContain('typ srflx');
}
},
// 192.0.2.1 is reserved for documentation and never answers, without the early stop in
// gatherIce Chromium would wait 40 s per side, with only the hard timeout still 10 s.
async 'dead-stun'(sender, receiver) {
for (const page of [sender, receiver]) {
await page.evaluate((path) => import(path).then((core) => core.STUN_SERVERS.push('stun:192.0.2.1:3478')), '/src/main.ts');
}
const start = Date.now();
await MODES.manual!(sender, receiver);
expect(Date.now() - start).toBeLessThan(4000);
},
async tracker(sender, receiver) {
await sender.click('#share');
await expect(sender.locator('#send-code')).toHaveText(/^\d{6}$/);
await expect(sender.locator('#log')).toContainText('waiting on');
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
await receiver.click('#receive');
},
};
let server: ViteDevServer;
let url: string;
const browsers: Browser[] = [];
test.describe.configure({ mode: 'parallel' });
test.setTimeout(60_000);
test.beforeAll(async () => {
server = await createServer({ logLevel: 'silent', server: { port: 0 } });
await server.listen();
url = server.resolvedUrls!.local[0]!;
});
test.afterAll(async () => {
await Promise.all(browsers.map((browser) => browser.close()));
await server.close();
});
async function open(name: string, sockets: string[]) {
const browser = await BROWSERS[name]!.launch();
browsers.push(browser);
const page = await (await browser.newContext()).newPage();
page.on('websocket', (ws) => sockets.push(ws.url()));
await page.goto(url);
return page;
}
async function hash(path: string) {
const sha = createHash('sha256');
for await (const chunk of createReadStream(path)) sha.update(chunk);
return sha.digest('hex');
}
const log = (page: Page) => page.locator('#log').textContent();
// Sends the file at source and verifies security check, OPFS storage and the downloaded bytes.
async function transfer(mode: string, sender: Page, receiver: Page, source: string, size: number) {
try {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){4}[0-9A-F]{2}$/, {
timeout: 45_000,
});
await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!);
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
await expect(sender.locator('#log')).toContainText('waiting for the security check');
await expect(receiver.locator('#log')).not.toContainText('receiving');
await sender.click('#confirm');
await expect(receiver.locator('#download')).toBeVisible({ timeout: test.info().timeout });
// The receiver must have written the file to OPFS, not collected it in RAM.
const stored = await receiver.evaluate(async () => {
const sizes = [];
const root = await navigator.storage.getDirectory();
for await (const handle of root.values()) sizes.push((await (handle as FileSystemFileHandle).getFile()).size);
return sizes;
});
expect(stored).toEqual([size]);
const [download] = await Promise.all([receiver.waitForEvent('download'), receiver.click('#download')]);
expect(download.suggestedFilename()).toBe(source.split('/').pop());
expect(await hash(await download.path())).toBe(await hash(source));
} finally {
await test.info().attach('sender log', { body: (await log(sender)) ?? '' });
await test.info().attach('receiver log', { body: (await log(receiver)) ?? '' });
}
}
for (const mode of Object.keys(MODES)) {
for (const from of Object.keys(BROWSERS)) {
for (const to of Object.keys(BROWSERS)) {
test(`${mode}: ${from} sends to ${to}`, async () => {
const sockets: string[] = [];
const [sender, receiver] = await Promise.all([open(from, sockets), open(to, sockets)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(SIZE));
await transfer(mode, sender, receiver, source, SIZE);
if (mode !== 'tracker') {
expect(sockets.filter((socket) => !socket.startsWith(url.replace('http', 'ws')))).toEqual([]);
}
});
}
}
}
for (const name of Object.keys(BROWSERS)) {
test(`large: ${name} sends 2.5 GiB`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(300_000);
// Sparse file with a random block every 64 MiB, so the hash catches lost or reordered chunks.
const source = test.info().outputPath('large.bin');
const file = await openFile(source, 'w');
await file.truncate(LARGE_SIZE);
for (let at = 0; at < LARGE_SIZE; at += 64 * 2 ** 20) await file.write(randomBytes(16384), 0, 16384, at);
await file.close();
// Real profiles on disk like normal users have; downloads go there too instead of the temp dir.
const contexts = await Promise.all(
['sender', 'receiver'].map((profile) =>
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
downloadsPath: test.info().outputPath('downloads'),
}),
),
);
try {
const [sender, receiver] = await Promise.all(contexts.map((context) => context.newPage()));
await Promise.all([sender!.goto(url), receiver!.goto(url)]);
await transfer('offline', sender!, receiver!, source, LARGE_SIZE);
} finally {
await Promise.all(contexts.map((context) => context.close()));
}
});
}
+5 -1
View File
@@ -8,12 +8,16 @@
"dev": "vite", "dev": "vite",
"build": "vue-tsc && vite build", "build": "vue-tsc && vite build",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "vue-tsc" "typecheck": "vue-tsc",
"test": "playwright test",
"test:install": "playwright install chromium firefox",
"test:large": "LARGE=1 playwright test -g large"
}, },
"dependencies": { "dependencies": {
"vue": "^3.5.44" "vue": "^3.5.44"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.64.1",
"@types/node": "^26.6.5", "@types/node": "^26.6.5",
"@vitejs/plugin-vue": "^6.0.10", "@vitejs/plugin-vue": "^6.0.10",
"typescript": "~6.0.3", "typescript": "~6.0.3",
+28
View File
@@ -170,6 +170,9 @@ importers:
specifier: ^3.5.44 specifier: ^3.5.44
version: 3.5.44(typescript@6.0.3) version: 3.5.44(typescript@6.0.3)
devDependencies: devDependencies:
'@playwright/test':
specifier: ^1.64.1
version: 1.64.1
'@types/node': '@types/node':
specifier: ^26.6.5 specifier: ^26.6.5
version: 26.6.5 version: 26.6.5
@@ -211,6 +214,11 @@ packages:
'@oxc-project/types@0.154.0': '@oxc-project/types@0.154.0':
resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==} resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==}
'@playwright/test@1.64.1':
resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==}
engines: {node: '>=20'}
hasBin: true
'@rolldown/binding-android-arm-eabi@1.2.14': '@rolldown/binding-android-arm-eabi@1.2.14':
resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==} resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==}
engines: {node: ^20.19.0 || >=22.12.0} engines: {node: ^20.19.0 || >=22.12.0}
@@ -490,6 +498,16 @@ packages:
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'} engines: {node: '>=12'}
playwright-core@1.64.1:
resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==}
engines: {node: '>=20'}
hasBin: true
playwright@1.64.1:
resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==}
engines: {node: '>=20'}
hasBin: true
postcss@8.5.31: postcss@8.5.31:
resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
@@ -594,6 +612,10 @@ snapshots:
'@oxc-project/types@0.154.0': {} '@oxc-project/types@0.154.0': {}
'@playwright/test@1.64.1':
dependencies:
playwright: 1.64.1
'@rolldown/binding-android-arm-eabi@1.2.14': '@rolldown/binding-android-arm-eabi@1.2.14':
optional: true optional: true
@@ -809,6 +831,12 @@ snapshots:
picomatch@4.0.7: {} picomatch@4.0.7: {}
playwright-core@1.64.1: {}
playwright@1.64.1:
dependencies:
playwright-core: 1.64.1
postcss@8.5.31: postcss@8.5.31:
dependencies: dependencies:
nanoid: 3.3.20 nanoid: 3.3.20
+116 -2
View File
@@ -1,10 +1,124 @@
<script setup lang="ts"> <script setup lang="ts">
const message = 'Hello, world!'; import { reactive, ref } from 'vue';
import {
answerOffer,
createOffer,
receiveViaTracker,
sendViaTracker,
settings as coreSettings,
type Check,
type Events,
} from './main';
// Same object as the core's, so the core sees every change.
const settings = reactive(coreSettings);
const file = ref<File>();
const offer = ref('');
const answerInput = ref('');
const sendCode = ref('');
const offerInput = ref('');
const answer = ref('');
const receiveCode = ref('');
const check = ref<Check>();
const confirmSend = ref<() => void>();
const download = ref<{ name: string; url: string }>();
const log = ref<string[]>([]);
const events: Events = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
file: (name, url) => (download.value = { name, url }),
check: (result, confirm) => {
check.value = result;
confirmSend.value = confirm;
},
};
function onConfirm() {
confirmSend.value?.();
confirmSend.value = undefined;
}
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
function onPick(event: Event) {
file.value = (event.target as HTMLInputElement).files?.[0];
}
async function onCreateOffer() {
const result = await createOffer(file.value!, events);
offer.value = result.offer;
acceptAnswer = result.accept;
}
function onAcceptAnswer() {
acceptAnswer?.(answerInput.value);
}
async function onCreateAnswer() {
answer.value = await answerOffer(offerInput.value, events);
}
async function onShare() {
sendCode.value = await sendViaTracker(file.value!, events);
}
function onReceive() {
receiveViaTracker(receiveCode.value, events);
}
</script> </script>
<template> <template>
<main> <main>
<h1>HellCon</h1> <h1>HellCon</h1>
<p>{{ message }}</p>
<label>
<input id="stun" v-model="settings.stun" type="checkbox" />
Use STUN
</label>
<h2>Send</h2>
<input type="file" @change="onPick" />
<h3>Manual</h3>
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer">
<p>Offer, send this to the receiver:</p>
<textarea id="offer" readonly :value="offer"></textarea>
<p>Answer from the receiver:</p>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" @click="onAcceptAnswer">Connect</button>
</template>
<h3>Tracker (optional)</h3>
<button id="share" :disabled="!file" @click="onShare">Share via tracker</button>
<p v-if="sendCode">Code: <output id="send-code">{{ sendCode }}</output></p>
<h2>Receive</h2>
<h3>Manual</h3>
<textarea id="offer-input" v-model="offerInput" placeholder="offer"></textarea>
<button id="create-answer" @click="onCreateAnswer">Create answer</button>
<template v-if="answer">
<p>Answer, send this back to the sender:</p>
<textarea id="answer" readonly :value="answer"></textarea>
</template>
<h3>Tracker (optional)</h3>
<input id="receive-code" v-model="receiveCode" placeholder="code" />
<button id="receive" @click="onReceive">Receive</button>
<p v-if="check">
Security check, you: <output id="check-local">{{ check.local }}</output>, peer:
<output id="check-remote">{{ check.remote }}</output>. The other side must show the same two codes swapped.
<button v-if="confirmSend" id="confirm" @click="onConfirm">Codes match, send</button>
</p>
<p v-if="download"><a id="download" :href="download.url" :download="download.name">{{ download.name }}</a></p>
<h2>Log</h2>
<pre id="log">{{ log.join('\n') }}</pre>
</main> </main>
</template> </template>
+294
View File
@@ -2,4 +2,298 @@ import { createApp } from 'vue';
import App from './App.vue'; import App from './App.vue';
import './style.css'; import './style.css';
export const TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
export const STUN_SERVERS = [
'stun:stun.pagequit.net:3478',
'stun:stun.cloudflare.com:3478',
'stun:stun.l.google.com:19302',
'stun:stun.nextcloud.com:443',
];
// Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody.
export const settings = { stun: true };
const CHUNK_SIZE = 16 * 1024;
const MAX_BUFFERED = 1024 * 1024;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
export type Check = { local: string; remote: string };
export type Events = {
log: (message: string) => void;
file: (name: string, url: string) => void;
// confirm is only passed on the sender side, the file is sent once it is called.
check: (check: Check, confirm?: () => void) => void;
};
function createPeerConnection() {
return new RTCPeerConnection({ iceServers: settings.stun ? [{ urls: STUN_SERVERS }] : [] });
}
function randomBinary(length: number) {
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
}
function randomCode() {
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, '0');
}
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
async function infoHash(code: string) {
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
return String.fromCharCode(...new Uint8Array(digest));
}
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
ws.send(
JSON.stringify({
action: 'announce',
info_hash: hash,
peer_id: peerId,
numwant: 0,
uploaded: 0,
downloaded: 0,
...params,
}),
);
}
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
// the same public address: the first one plus a short grace for the other IP family is enough.
async function gatherIce(pc: RTCPeerConnection) {
if (pc.iceGatheringState === 'complete') return;
await new Promise<void>((resolve) => {
const timeout = setTimeout(resolve, ICE_TIMEOUT);
const done = () => {
clearTimeout(timeout);
resolve();
};
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') done();
});
pc.addEventListener('icecandidate', ({ candidate }) => {
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
});
});
}
// Anti-MITM check: the first 5 bytes of both DTLS certificate fingerprints. My local code must
// equal the peer's remote code and vice versa, otherwise someone interposed on the signaling.
function securityCheck(pc: RTCPeerConnection): Check {
const short = (sdp = '') =>
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 5).join(' ') ?? '?';
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
}
// With confirm, resolves once the user compared the codes, so nothing is sent to a man in the middle.
function connected(pc: RTCPeerConnection, via: string, events: Events, confirm = false) {
events.log(`connected via ${via}`);
if (confirm) events.log('waiting for the security check');
return new Promise<void>((resolve) => events.check(securityCheck(pc), confirm ? resolve : undefined));
}
async function sendFile(channel: RTCDataChannel, file: File, events: Events) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
}
events.log(`sending ${file.name} (${file.size} bytes)`);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
if (channel.bufferedAmount > MAX_BUFFERED) {
await new Promise((resolve) => channel.addEventListener('bufferedamountlow', resolve, { once: true }));
}
channel.send(await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer());
}
events.log('sent');
}
// Runs in a dedicated worker, because OPFS sync access handles only exist there. It is started from
// a Blob URL so the app stays one script, which means it must not use anything outside its body.
function storageWorker() {
type SyncHandle = { write(data: ArrayBuffer, options: { at: number }): number; flush(): void; close(): void };
let handle: SyncHandle;
let offset = 0;
let queue = Promise.resolve();
// Opening is async, the queue keeps chunks from overtaking it and each other.
self.onmessage = ({ data }: MessageEvent) => {
queue = queue
.then(async () => {
if (data.open) {
const root = await navigator.storage.getDirectory();
const file = await root.getFileHandle(data.open, { create: true });
handle = await (file as unknown as { createSyncAccessHandle(): Promise<SyncHandle> }).createSyncAccessHandle();
} else if (data.chunk) {
// Over quota some browsers write less instead of throwing.
const written = handle.write(data.chunk, { at: offset });
offset += written;
if (written !== data.chunk.byteLength) throw new Error(`storage full after ${offset} bytes`);
} else {
handle.flush();
handle.close();
self.postMessage({ done: true });
}
})
.catch((error) => {
self.postMessage({ error: String(error) });
self.close();
});
};
}
const STORAGE_WORKER = URL.createObjectURL(new Blob([`(${storageWorker})()`], { type: 'text/javascript' }));
// Received files are written to OPFS instead of RAM and stay there until the next visit, because the
// download link reads from them.
async function clearStorage() {
const root = await navigator.storage.getDirectory();
for await (const name of root.keys()) await root.removeEntry(name);
}
function receiveFile(channel: RTCDataChannel, events: Events) {
const id = crypto.randomUUID();
let meta: { name: string; size: number } | undefined;
let worker: Worker | undefined;
let received = 0;
async function stored() {
worker!.terminate();
const root = await navigator.storage.getDirectory();
const file = await (await root.getFileHandle(id)).getFile();
events.log('received');
events.file(meta!.name, URL.createObjectURL(file));
}
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (typeof data === 'string') {
meta = JSON.parse(data);
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
worker = new Worker(STORAGE_WORKER);
worker.onmessage = ({ data }) => (data.error ? events.log(`storage failed: ${data.error}`) : stored());
worker.postMessage({ open: id });
} else {
received += data.byteLength;
worker!.postMessage({ chunk: data }, [data]);
}
if (meta && received === meta.size) worker!.postMessage({ done: true });
};
}
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
// The sender offers, the receiver answers, no tracker involved.
export async function createOffer(file: File, events: Events) {
const pc = createPeerConnection();
const channel = pc.createDataChannel('file');
channel.onopen = async () => {
await connected(pc, 'manual exchange', events, true);
sendFile(channel, file, events);
};
await pc.setLocalDescription();
await gatherIce(pc);
return {
offer: btoa(pc.localDescription!.sdp),
accept: (answer: string) => pc.setRemoteDescription({ type: 'answer', sdp: atob(answer.trim()) }),
};
}
export async function answerOffer(offer: string, events: Events) {
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) => {
connected(pc, 'manual exchange', events);
receiveFile(channel, events);
};
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
await pc.setLocalDescription();
await gatherIce(pc);
return btoa(pc.localDescription!.sdp);
}
// Tracker signaling (optional): sender joins the swarm on every tracker and answers the first offer.
export async function sendViaTracker(file: File, events: Events) {
const code = randomCode();
const hash = await infoHash(code);
const peerId = randomBinary(20);
let pc: RTCPeerConnection | undefined;
for (const url of TRACKERS) {
const ws = new WebSocket(url);
ws.onopen = () => {
announce(ws, hash, peerId, { left: 0, event: 'started' });
events.log(`waiting on ${url}`);
};
ws.onmessage = async (event) => {
const msg = JSON.parse(event.data);
if (!msg.offer || pc) return;
events.log(`offer via ${url}`);
const peer = (pc = createPeerConnection());
peer.ondatachannel = async ({ channel }) => {
await connected(peer, url, events, true);
sendFile(channel, file, events);
};
await peer.setRemoteDescription(msg.offer);
await peer.setLocalDescription();
await gatherIce(peer);
announce(ws, hash, peerId, {
left: 0,
to_peer_id: msg.peer_id,
offer_id: msg.offer_id,
answer: peer.localDescription,
});
};
}
return code;
}
// Receiver sends one offer per tracker; the first data channel that opens wins.
export async function receiveViaTracker(code: string, events: Events) {
const hash = await infoHash(code);
const peerId = randomBinary(20);
let isConnected = false;
for (const url of TRACKERS) {
const pc = createPeerConnection();
const channel = pc.createDataChannel('file');
const offerId = randomBinary(20);
channel.onopen = () => {
if (isConnected) return pc.close();
isConnected = true;
connected(pc, url, events);
};
receiveFile(channel, events);
pc.setLocalDescription()
.then(() => gatherIce(pc))
.then(() => {
const ws = new WebSocket(url);
ws.onopen = () => {
announce(ws, hash, peerId, {
left: 1,
numwant: 1,
event: 'started',
offers: [{ offer_id: offerId, offer: pc.localDescription }],
});
events.log(`looking on ${url}`);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.answer && msg.offer_id === offerId) {
events.log(`answer via ${url}`);
pc.setRemoteDescription(msg.answer);
}
};
});
}
}
clearStorage();
// Mounted last: App.vue imports the core from this module.
createApp(App).mount('#app'); createApp(App).mount('#app');
+1 -1
View File
@@ -15,5 +15,5 @@
"skipLibCheck": true, "skipLibCheck": true,
"noEmit": true "noEmit": true
}, },
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"] "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"]
} }