From aea75fff92baf1aee4a7e90d8f6f9a00f8a41ea5 Mon Sep 17 00:00:00 2001 From: Schluffe Date: Thu, 22 Oct 2026 00:35:36 +0200 Subject: [PATCH] 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 --- .gitignore | 1 + TODO.md | 57 ++++++++++ e2e.spec.ts | 168 ++++++++++++++++++++++++++++ package.json | 6 +- pnpm-lock.yaml | 28 +++++ src/App.vue | 118 +++++++++++++++++++- src/main.ts | 294 +++++++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 2 +- 8 files changed, 670 insertions(+), 4 deletions(-) create mode 100644 TODO.md create mode 100644 e2e.spec.ts diff --git a/.gitignore b/.gitignore index af45a21..d18924c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ dist .env .env.* !.env.example +test-results diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..0101bac --- /dev/null +++ b/TODO.md @@ -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. diff --git a/e2e.spec.ts b/e2e.spec.ts new file mode 100644 index 0000000..3d03f53 --- /dev/null +++ b/e2e.spec.ts @@ -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 = { 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 Promise> = { + 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())); + } + }); +} diff --git a/package.json b/package.json index 776dcbf..002b2b6 100644 --- a/package.json +++ b/package.json @@ -8,12 +8,16 @@ "dev": "vite", "build": "vue-tsc && vite build", "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": { "vue": "^3.5.44" }, "devDependencies": { + "@playwright/test": "^1.64.1", "@types/node": "^26.6.5", "@vitejs/plugin-vue": "^6.0.10", "typescript": "~6.0.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9903b75..25feb50 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -170,6 +170,9 @@ importers: specifier: ^3.5.44 version: 3.5.44(typescript@6.0.3) devDependencies: + '@playwright/test': + specifier: ^1.64.1 + version: 1.64.1 '@types/node': specifier: ^26.6.5 version: 26.6.5 @@ -211,6 +214,11 @@ packages: '@oxc-project/types@0.154.0': 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': resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -490,6 +498,16 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} 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: resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} engines: {node: ^10 || ^12 || >=14} @@ -594,6 +612,10 @@ snapshots: '@oxc-project/types@0.154.0': {} + '@playwright/test@1.64.1': + dependencies: + playwright: 1.64.1 + '@rolldown/binding-android-arm-eabi@1.2.14': optional: true @@ -809,6 +831,12 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.64.1: {} + + playwright@1.64.1: + dependencies: + playwright-core: 1.64.1 + postcss@8.5.31: dependencies: nanoid: 3.3.20 diff --git a/src/App.vue b/src/App.vue index 60d8a93..48ec591 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,10 +1,124 @@ diff --git a/src/main.ts b/src/main.ts index 8dd6bc1..6966342 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,4 +2,298 @@ import { createApp } from 'vue'; import App from './App.vue'; 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((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((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 }).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'); diff --git a/tsconfig.json b/tsconfig.json index 9b9e610..34029d6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,5 +15,5 @@ "skipLibCheck": true, "noEmit": true }, - "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"] + "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"] }