diff --git a/README.md b/README.md index 6bc62c5..b0f20a2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ size limit: the file goes directly to the other person and is never stored on a ## How to send a file 1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get - an 8 character code. Tell it to the receiver. + an 8 character code. Tell it to the receiver, it works for 6 minutes. 2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**. 3. **Both:** compare the security check (see below) and click **Codes match**. 4. **Receiver:** you now see the file's name and size. Click **Download** to save it. diff --git a/e2e.spec.ts b/e2e.spec.ts index 33ee198..8a45c1f 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -687,6 +687,34 @@ for (const name of Object.keys(BROWSERS)) { }); }); + // The 6 minutes only limit finding each other, a receiver connected by then still gets the file. + test(`live tracker: ${name} a receiver connected before the expiry downloads after it`, async () => { + const [sender, receiver] = await Promise.all([open(name), open(name)]); + await Promise.all([sender, receiver].map((page) => page.clock.install())); + const source = await payload(randomBytes(SIZE)); + + await withLogs(sender, receiver, async () => { + await sender.setInputFiles('input[type=file]', source); + await MODES.tracker!(sender, receiver); + await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 }); + await Promise.all([sender, receiver].map((page) => page.clock.fastForward('06:00'))); + for (const page of [sender, receiver]) { + await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0); + } + await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:'); + + const started = downloadStarts(receiver); + await sender.click('#confirm'); + await receiver.click('#confirm'); + await receiver.click('#download'); + const { download } = await started; + expect(await hash(await download.path())).toBe(await hash(source)); + await expect(sender.locator('#log')).toContainText('delivered'); + await expect(sender.locator('#send-error')).toHaveCount(0); + await expect(receiver.locator('#receive-error')).toHaveCount(0); + }); + }); + // Trackers that keep the socket open but turn the announcement down used to leave both sides waiting. test(`tracker: ${name} reports trackers that reject the announcement`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); @@ -727,8 +755,93 @@ for (const name of Object.keys(BROWSERS)) { await expect(sender.locator('#log')).toContainText(': slow down'); await expect(sender.locator('#log')).not.toContainText('rejected by'); await expect(sender.locator('#send-error')).toHaveCount(0); - // One per tracker socket, none for the closed connections. - expect(await listeners()).toBe(2); + // One per tracker socket and the expiry, none for the closed connections. + expect(await listeners()).toBe(3); + }); + }); + + // Trackers drop a peer that doesn't announce again on their interval, the defaults after 2 to 3 + // minutes. A code nobody uses still ends after 6 minutes, on both sides. + test(`tracker: ${name} both sides announce again until they give up after 6 minutes`, async () => { + const pages = await Promise.all([open(name), open(name)]); + const [sender, receiver] = pages as [Page, Page]; + const announced = pages.map(() => [] as Record[]); + // 0 would announce in a loop, the app waits 30 s at least. + const trackers = await Promise.all( + pages.map(async (page, i) => { + await page.clock.install(); + return mockTrackers(page, (msg) => { + announced[i]!.push(msg); + return { action: 'announce', interval: 0, info_hash: msg.info_hash }; + }); + }), + ); + const again = () => announced.map((msgs) => msgs.filter((msg) => !msg.event)); + const fastForward = (ms: number) => Promise.all(pages.map((page) => page.clock.fastForward(ms))); + + await withLogs(sender, receiver, async () => { + await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); + await sender.click('#share'); + await expect(sender.locator('label[for=send-code]')).toHaveText(/valid until \d/); + await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); + await receiver.click('#receive'); + await expect.poll(() => announced.map((msgs) => msgs.length)).toEqual([2, 2]); + // Until the replies with the interval reached the pages, and any early announce the test. + await sender.waitForTimeout(500); + await fastForward(25_000); + await sender.waitForTimeout(500); + expect(again().map((msgs) => msgs.length)).toEqual([0, 0]); + await fastForward(5_000); + await expect.poll(() => again().map((msgs) => msgs.length)).toEqual([2, 2]); + // The receiver's offers again, a busy sender may have dropped them. + const offers = announced[1]!.filter((msg) => msg.event === 'started').map((msg) => msg.offers[0].offer_id); + expect(again()[1]!.map((msg) => msg.offers[0].offer_id).sort()).toEqual(offers.sort()); + + await fastForward(330_000); + await expect(sender.locator('#send-error')).toHaveText('nobody received the file within 6 minutes, share it again'); + await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:'); + await expect(sender.locator('#copy-send-code')).toBeDisabled(); + await expect(receiver.locator('#receive-error')).toHaveText( + 'no sender answered within 6 minutes, check the code and try again', + ); + await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]); + await expectClosed(sender); + await expectClosed(receiver); + }); + }); + + // Each expiry used to hold its session until it ran out, a failed receiver its connections. + test(`tracker: ${name} sessions that ended keep no expiry and no connection`, async () => { + const pages = await Promise.all([open(name, { init: countDeadlines }), open(name, { init: countDeadlines })]); + const [sender, receiver] = pages as [Page, Page]; + let rejecting = false; + await Promise.all( + pages.map((page) => + mockTrackers(page, ({ info_hash }) => + rejecting ? { 'failure reason': 'not here' } : { action: 'announce', interval: 120, info_hash }, + ), + ), + ); + const deadlines = () => + Promise.all(pages.map((page) => page.evaluate(() => (window as unknown as { deadlines: () => number }).deadlines()))); + + await withLogs(sender, receiver, async () => { + await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); + for (let session = 0; session < 5; session++) { + await sender.click('#share'); + await receiver.fill('#receive-code', `nobody ${session}`); + await receiver.click('#receive'); + } + await expect.poll(deadlines).toEqual([1, 1]); + + rejecting = true; + await sender.click('#share'); + await receiver.click('#receive'); + await expect(sender.locator('#send-error')).toHaveText(/^no tracker accepted it/); + await expect(receiver.locator('#receive-error')).toHaveText(/^no tracker accepted it/); + await expect.poll(deadlines).toEqual([0, 0]); + await expectClosed(sender); + await expectClosed(receiver); }); }); @@ -871,6 +984,29 @@ function countAbortListeners() { (window as unknown as { abortListeners: () => number }).abortListeners = () => listeners.size; } +// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry. +// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own +// window counts. +function countDeadlines() { + if (window !== window.top) return; + const pending = new Set(); + const { setTimeout: set, clearTimeout: clear } = window; + window.setTimeout = ((handler: () => void, ms?: number) => { + if (ms !== 6 * 60_000 || !new Error().stack?.includes('/src/core.ts')) return set(handler, ms); + const id = set(() => { + pending.delete(id); + handler(); + }, ms); + pending.add(id); + return id; + }) as typeof setTimeout; + window.clearTimeout = ((id?: number) => { + pending.delete(id!); + clear(id); + }) as typeof clearTimeout; + (window as unknown as { deadlines: () => number }).deadlines = () => pending.size; +} + for (const name of Object.keys(BROWSERS)) { test(`large: ${name} survives a 40 s stall`, async () => { test.skip(!process.env.LARGE, 'set LARGE=1'); diff --git a/src/App.vue b/src/App.vue index 5eab26f..23c09b5 100644 --- a/src/App.vue +++ b/src/App.vue @@ -8,6 +8,7 @@ import { receiveViaTracker, sendViaTracker, settings as coreSettings, + TRACKER_WAIT, type Check, type Events, type Incoming, @@ -80,6 +81,10 @@ const file = ref(); const offer = ref(''); const answerInput = ref(''); const sendCode = ref(''); +// Until when a receiver can find the share with its code, the time shown and whether it passed. +const sendUntil = ref(''); +const sendExpired = ref(false); +let sendTimer: number | undefined; const offerInput = ref(''); const answer = ref(''); @@ -162,6 +167,8 @@ function begin(on: 'send' | 'receive') { incoming.value = undefined; received.value = undefined; sendCode.value = ''; + sendExpired.value = false; + clearTimeout(sendTimer); offer.value = ''; answer.value = ''; acceptAnswer = undefined; @@ -223,9 +230,15 @@ async function onCreateAnswer() { async function onShare() { const signal = begin('send'); const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal)); - if (code) sendCode.value = code; + if (!code) return; + sendCode.value = code; + sendUntil.value = new Date(Date.now() + TRACKER_WAIT).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); + sendTimer = window.setTimeout(() => (sendExpired.value = true), TRACKER_WAIT); } +// Also once the share failed, every error on the tracker ends it. +const codeGone = computed(() => sendExpired.value || !!error.value); + function onReceive() { const signal = begin('receive'); attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal)); @@ -285,10 +298,13 @@ function onReceive() {

Tracker

diff --git a/src/core.ts b/src/core.ts index 6c2776b..c9a4748 100644 --- a/src/core.ts +++ b/src/core.ts @@ -28,6 +28,11 @@ const ICE_TIMEOUT = 5000; // A tracker peer that got an answer but never opens the data channel gives up its turn after this, // e.g. one whose SDP has no usable candidates: its connection never even fails. const CONNECT_TIMEOUT = 30_000; +// A share, or a receiver looking for one, gives up after this without a download: nobody announces +// all day for a code nobody uses. Until then both announce again on the interval the tracker names, +// else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names. +export const TRACKER_WAIT = 6 * 60_000; +const MIN_INTERVAL = 30_000; // Far beyond what a file system stores, but keeps an absurd name out of the page and the worker. const MAX_NAME = 1024; @@ -83,6 +88,16 @@ function live void>>(events: T, s ) as T; } +// Runs expire after TRACKER_WAIT unless closed before, cleared with the session. +function deadline(signal: AbortSignal, expire: () => void) { + const timer = setTimeout(() => { + owned.close(); + expire(); + }, TRACKER_WAIT); + const owned = own(signal, { close: () => clearTimeout(timer) }); + return owned; +} + function createPeerConnection(signal: AbortSignal) { // An empty urls list is a syntax error. const stun = settings.stun && settings.stunServers.length; @@ -560,21 +575,24 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal: // A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason // before anything else rejects the announcement, the tracker is no use then and its socket closes, a // later one only concerns that message and is logged. lost runs once it closed without close() being -// called: unreachable, lost or rejected. +// called: unreachable, lost or rejected. again announces once more, on the first interval it names. function trackerSocket( url: string, signal: AbortSignal, events: Events, message: (msg: Message) => void, lost: () => void, + again: () => void, ) { const ws = own(signal, new WebSocket(url)); let opened = false; let accepted = false; let closed = false; + let reannounce: ReturnType | undefined; const end = (reason: string) => { if (closed) return; closed = true; + clearInterval(reannounce); // Already closed unless rejected, this only lets go of it. ws.close(); events.log(reason); @@ -586,7 +604,9 @@ function trackerSocket( rejected: undefined as string | undefined, alive: () => !closed, close: () => { + if (closed) return; closed = true; + clearInterval(reannounce); ws.close(); }, }; @@ -597,6 +617,10 @@ function trackerSocket( if (typeof failure !== 'string') { if (!msg) return; accepted = true; + // Seconds, JSON may give Infinity for a huge one. Beyond TRACKER_WAIT it would never come. + if (!reannounce && !closed && typeof msg.interval === 'number') { + reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000))); + } return message(msg); } if (accepted) return events.log(`${url}: ${failure}`); @@ -619,7 +643,8 @@ function noTracker(trackers: (Tracker | undefined)[]) { // Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a // time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed // the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be -// answered or never connects. Once the download started the share is used up, the trackers go. +// answered or never connects. Once the download started the share is used up, the trackers go. After +// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn. export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) { events = live(events, signal); const code = randomCode(); @@ -628,16 +653,28 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi const trackers: Tracker[] = []; let busy = false; let shared = false; + let expired = false; // The latest offer that came while busy, answered once that peer is out. let waiting: (() => void) | undefined; // Without a tracker no further receiver can find the share. const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive()); + const nobody = `nobody received the file within ${TRACKER_WAIT / 60_000} minutes, share it again`; + const expiry = deadline(signal, () => { + expired = true; + for (const tracker of trackers) tracker.close(); + if (stranded()) events.error(nobody); + }); + // Once stranded the share is over. + const end = (reason: string) => { + expiry.close(); + events.error(reason); + }; function next() { busy = false; if (signal.aborted) return; - if (stranded()) return events.error(noTracker(trackers)); + if (stranded()) return end(expired ? nobody : noTracker(trackers)); events.log('waiting for the next receiver'); const offer = waiting; waiting = undefined; @@ -668,6 +705,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi handshake.start(); shared = true; waiting = undefined; + expiry.close(); for (const tracker of trackers) tracker.close(); }; sendFile(pc, channel, file, events, { ...handshake, start }, signal); @@ -704,7 +742,8 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi if (busy) waiting = () => answer(tracker.ws, url, offer); else answer(tracker.ws, url, offer); }, - () => stranded() && events.error(noTracker(trackers)), + () => stranded() && end(noTracker(trackers)), + () => announce(tracker.ws, hash, peerId, { left: 0 }), ); tracker.ws.onopen = () => { announce(tracker.ws, hash, peerId, { left: 0, event: 'started' }); @@ -719,7 +758,8 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi // Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails // or the sender leaves before, the used up offers are replaced. The others stay, a sender may have // queued one of them. An answer that can't be used or never connects is replaced right away. Once the -// download started, every other offer and tracker socket goes. +// download started, every other offer and tracker socket goes. After TRACKER_WAIT no offer is made or +// kept any more, a sender connected by then still gets its turn. export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) { events = live(events, signal); await downloadsReady(); @@ -731,10 +771,29 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig const offers = new Map(); let isConnected = false; let started = false; + let expired = false; + + const nobody = `no sender answered within ${TRACKER_WAIT / 60_000} minutes, check the code and try again`; + // Without a sender connected the search is over, every offer goes. + const end = (reason: string) => { + expiry.close(); + for (const { pc, tracker } of offers.values()) { + tracker?.close(); + pc.close(); + } + events.error(reason); + }; + // A connected sender keeps its connection, the other offers wait for next or start. + const expiry = deadline(signal, () => { + expired = true; + if (!isConnected) return end(nobody); + for (const { tracker } of offers.values()) tracker?.close(); + }); const next = () => { isConnected = false; if (signal.aborted) return; + if (expired) return end(nobody); events.log('looking again'); for (const [url, { pc }] of offers) if (pc.signalingState === 'closed') offer(url); }; @@ -752,7 +811,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig if (pc.signalingState === 'closed') return; events.log(reason); pc.close(); - if (!isConnected && !started && !signal.aborted) offer(url); + if (!isConnected && !started && !signal.aborted && !expired) offer(url); }; channel.onopen = () => { clearTimeout(timeout); @@ -762,6 +821,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig const start = () => { handshake.start(); started = true; + expiry.close(); for (const other of offers.values()) { other.tracker?.close(); if (other.pc !== pc) other.pc.close(); @@ -776,7 +836,15 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig pc.setLocalDescription() .then(() => gatherIce(pc)) .then(() => { - if (pc.signalingState === 'closed') return; + if (pc.signalingState === 'closed' || expired) return; + // Again with the same offer on the interval, a busy sender may have dropped it meanwhile. + const hello = (event?: string) => + announce(tracker.ws, hash, peerId, { + left: 1, + numwant: 1, + event, + offers: [{ offer_id: offerId, offer: pc.localDescription }], + }); const tracker = trackerSocket( url, signal, @@ -794,18 +862,14 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig () => { entry.lost = true; if (!isConnected && !started && [...offers.values()].every((other) => other.lost)) { - events.error(noTracker([...offers.values()].map((other) => other.tracker))); + end(noTracker([...offers.values()].map((other) => other.tracker))); } }, + () => hello(), ); entry.tracker = tracker; tracker.ws.onopen = () => { - announce(tracker.ws, hash, peerId, { - left: 1, - numwant: 1, - event: 'started', - offers: [{ offer_id: offerId, offer: pc.localDescription }], - }); + hello('started'); events.log(`looking on ${url}`); }; }) diff --git a/src/style.css b/src/style.css index eede103..ae013a3 100644 --- a/src/style.css +++ b/src/style.css @@ -246,6 +246,11 @@ button:disabled { user-select: all; } +#send-code[data-expired] { + text-decoration: line-through; + user-select: none; +} + /* Copy buttons, secondary next to the value they copy */ [data-copy] {