diff --git a/README.md b/README.md index a2685f1..4ea2a82 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 - a 10 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can + an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can get the file, or pretend to be you, so give it to nobody else. 2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**. 3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it. @@ -74,7 +74,7 @@ networks, a direct connection may not be possible. sticks with the first that answers. The sender stays on the first tracker that accepts it. The receiver goes down the list until it finds the sender, and the trackers it passes keep its encrypted offer. Nobody without the code learns your address through a tracker. -- Settings (STUN on or off, your server lists) are kept in your browser only. +- Nothing is kept: every reload starts with the default settings. - Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that, host your own (below). @@ -86,6 +86,15 @@ brings back the original lists. The order matters: the sender stays on the first works, the receiver tries them in order until it finds the sender. Both lists must contain that tracker. +The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC): +guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the +receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could +still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both +sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody +can guess ahead for a salt they don't know. + +Nothing of this is kept, a reload brings back the defaults. + ## Host your own HellCon is a static website, any web server can host it. Build it with Node.js and pnpm: diff --git a/TODO.md b/TODO.md index e0c34ce..f990715 100644 --- a/TODO.md +++ b/TODO.md @@ -2,10 +2,26 @@ ## Ideas +- Unstick a wrong salt: while a tracker share or search runs, the salt is locked, and a receiver + told "Check the code and the salt" can't change it for up to 6 minutes. The receiver doesn't need + the lock: like the code field, the salt could stay editable and count from the next Receive + (`saltLocked` only for `side === 'send'`). The sender does, the code shown must match the salt + shown: a Stop button next to the valid code would end the share, unlock the salt and also let a + share be withdrawn early. Changing the salt itself shouldn't end a share, a stray click would. + - Resume interrupted transfers: the receiver already reports how much the download manager has read (`{ read }`), which is where a new connection could continue. The browser can't append to a finished or failed download though, so a resume would have to start a new one. +- Keep user settings again: for now every reload starts from the defaults, the server lists and the + own salt too. Open which ones to keep, and how a kept one that differs from the other side's would + show, instead of silently breaking a share. + +- Version the protocol for 1.0: put a version into the key derivation, e.g. `hellcon/1 ` as + the PBKDF2 salt in `secrets`. Until then any change to it silently breaks sharing between + deployments on different versions, the receiver only sees "No sender with this code". Open how a + mismatch would be reported, e.g. by trying the previous version's swarm too. + ## Open observations - Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver diff --git a/e2e.spec.ts b/e2e.spec.ts index df2129a..6508102 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -37,6 +37,14 @@ const PROBE_TIMEOUT = 2000; const PROOF_TIMEOUT = 10_000; const CONNECT_TIMEOUT = 30_000; const DOWNLOAD_GRACE = 1000; +// Every page's clock starts a second into the window from 12:00 to 12:06 UTC unless a test sets +// another time, so the test knows the salt of every code, see saltOf. SALT_WINDOW is the one in +// src/core.ts. +const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1); +const SALT_WINDOW = 6 * 60_000; +const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; +// When a share or search ends, in its error. The browser writes the time its own way. +const UNTIL = String.raw`until \d\d?:\d\d(?:[\u00a0\u202f][AP]M)?`; // Enough for a transfer whose receiver holds back its reads to pause at the window. const HELD_SIZE = 3 * WINDOW; // What the fake STUN server reports as public address, reserved for documentation. @@ -73,7 +81,7 @@ const MODES: Record Promise> = { }, async tracker(sender, receiver) { await sender.click('#share'); - await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{10}$/); + await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{11}$/); await sender.click('#copy-send-code'); await expect(sender.locator('#copy-send-code')).toHaveText('Copied'); await expect(sender.locator('#log')).toContainText('waiting on'); @@ -134,13 +142,18 @@ test.afterAll(async () => { stun.close(); }); -// init runs in the page before the app. base is the app's URL, the dev server's by default. -async function open(name: string, { init, base = url }: { init?: () => void; base?: string } = {}) { +// init runs in the page before the app. base is the app's URL, the dev server's by default. time is +// where the page's clock starts. +async function open( + name: string, + { init, base = url, time = TEST_TIME }: { init?: () => void; base?: string; time?: number } = {}, +) { browsers[name] ??= BROWSERS[name]!.launch(); const browser = await browsers[name]; const context = await browser.newContext({ permissions: PERMISSIONS[name] }); contexts.push(context); const page = await context.newPage(); + await page.clock.install({ time }); const trackers: PageSocket[] = []; sockets.set(page, trackers); page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws)); @@ -450,13 +463,28 @@ for (const [from, to] of [ test(`own tracker: ${from} sends to ${to}`, async () => { const tracker = await ownTracker(); const [sender, receiver] = await Promise.all([open(from), open(to)]); + // With an own salt, the clock's is in the live tests. + for (const page of [sender, receiver]) { + await page.uncheck('#stun'); + await page.click('#servers summary'); + await page.fill('#trackers', tracker); + await page.check('#own-salt'); + await page.fill('#salt', 'own tracker'); + } + await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE); + await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`); + }); + + // The code tells its window, the receiver's clock can be hours off. With the clock's salt. + test(`own tracker: ${from} sends to ${to} with the receiver's clock 2 hours behind`, async () => { + const tracker = await ownTracker(); + const [sender, receiver] = await Promise.all([open(from), open(to, { time: TEST_TIME - 2 * 3_600_000 })]); for (const page of [sender, receiver]) { await page.uncheck('#stun'); await page.click('#servers summary'); await page.fill('#trackers', tracker); } await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE); - await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`); }); } @@ -474,7 +502,7 @@ test('build: chromium sends to firefox from the production build', async () => { }); for (const name of Object.keys(BROWSERS)) { - test(`servers: ${name} skips invalid lines and keeps the lists over a reload`, async () => { + test(`servers: ${name} skips invalid lines, a reload brings back the defaults`, async () => { const page = await open(name); const core = () => page.evaluate( @@ -489,10 +517,16 @@ for (const name of Object.keys(BROWSERS)) { await expect(page.locator('#servers')).toContainText('without #: tracker.example, wss://tracker.example/#'); expect(await core()).toEqual([[], ['wss://tracker.example']]); + await page.uncheck('#stun'); + await page.check('#own-salt'); + await page.fill('#salt', 'salt'); await page.reload(); await page.click('#servers summary'); - await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example'); - expect(await core()).toEqual([[], ['wss://tracker.example']]); + await expect(page.locator('#trackers')).toHaveValue(/^wss:\/\/tracker\.pagequit\.net\n/); + await expect(page.locator('#stun')).toBeChecked(); + await expect(page.locator('#own-salt')).not.toBeChecked(); + await expect(page.locator('#salt')).toHaveCount(0); + expect((await core())[1]).toContain('wss://tracker.webtorrent.dev'); await page.fill('#receive-code', 'code'); await page.fill('#trackers', ''); @@ -701,7 +735,6 @@ for (const name of Object.keys(BROWSERS)) { // DOWNLOAD_GRACE. The frame holding the worker goes right away, it would block an update. test(`boundary: ${name} keeps a finished download's frame for DOWNLOAD_GRACE`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); - await receiver.clock.install(); await withLogs(sender, receiver, async () => { await connect('offline', sender, receiver, await payload(Buffer.alloc(0), 'empty.bin')); @@ -762,7 +795,7 @@ for (const name of Object.keys(BROWSERS)) { const first = await sender.locator('#send-code').textContent(); await sender.click('#share'); await expect(sender.locator('#send-code')).not.toHaveText(first!); - await receiver.fill('#receive-code', 'nobody'); + await receiver.fill('#receive-code', 'nobodyhere0'); await receiver.click('#receive'); await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0); // The log tells the sessions apart. @@ -1002,7 +1035,6 @@ 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 () => { @@ -1091,7 +1123,7 @@ for (const name of Object.keys(BROWSERS)) { await receiver.uncheck('#stun'); await receiver.click('#servers summary'); await receiver.fill('#trackers', urls.join('\n')); - await receiver.fill('#receive-code', 'somecode'); + await receiver.fill('#receive-code', 'somecode123'); await receiver.click('#receive'); await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`); // A third one would come within milliseconds. @@ -1146,6 +1178,134 @@ for (const name of Object.keys(BROWSERS)) { }); }); + // The info_hash tells which salt a share took: the window its code ends with, or that and the own + // salt, trimmed and NFC. A code made late in a window still lasts 6 minutes. The salt stays as it is + // while a share or search runs. + test(`salt: ${name} a share takes the clock's salt or the own one, which stays while it runs`, async () => { + const sender = await open(name); + const hashes: string[] = []; + await mockTrackers(sender, (msg) => { + if (msg.event === 'started') hashes.push(msg.info_hash as string); + return { action: 'announce', interval: 120, info_hash: msg.info_hash }; + }); + const label = sender.locator('label[for=send-code]'); + const valid = /^\s*Code, give this to the receiver, valid until .+:\s*$/; + // The time as the label writes it, in the page's locale and time zone. + const time = (at: number) => + sender.evaluate( + (at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'), + at, + ); + // The code and info_hash of the share start begins, by default a click on Share. + const share = async (start = () => sender.click('#share')) => { + const count = hashes.length; + await start(); + await expect.poll(() => hashes.length).toBe(count + 1); + return { code: (await sender.locator('#send-code').textContent())!, hash: hashes.at(-1) }; + }; + + await withLogs(sender, sender, async () => { + await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); + const first = await share(); + expect(first.hash).toBe(swarm(first.code)); + await expect(label).toHaveText(valid); + // toHaveText takes a no-break space for any space, the text itself has to have it. + expect(await label.textContent()).toMatch(new RegExp(`${UNTIL}:`)); + + // 12:05:30, half a minute before the window ends. Still valid for 6 minutes, until 12:11. + await sender.clock.fastForward('05:29'); + const late = await share(); + expect(late.code.at(-1)).toBe(first.code.at(-1)); + expect(late.hash).toBe(swarm(late.code)); + await expect(label).toHaveText(valid); + expect(await label.textContent()).toContain(`until ${await time(Date.UTC(2026, 0, 1, 12, 11, 30))}:`); + + await sender.clock.fastForward('06:00'); + await expect(label).toHaveText('Code, no longer valid:'); + const next = await share(); + expect(next.code.at(-1)).not.toBe(first.code.at(-1)); + expect(next.hash).toBe(swarm(next.code)); + + // The switch, and the salt with Generate while it's on. + const locked = async (disabled: boolean) => { + const ids = (await sender.isChecked('#own-salt')) ? ['#own-salt', '#salt', '#generate-salt'] : ['#own-salt']; + for (const id of ids) await expect(sender.locator(id)).toBeEnabled({ enabled: !disabled }); + }; + await locked(true); + await sender.clock.fastForward('06:00'); + await expect(label).toHaveText('Code, no longer valid:'); + await locked(false); + + await sender.check('#own-salt'); + await expect(sender.locator('#share')).toBeDisabled(); + await sender.fill('#salt', ' '); + await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'true'); + await expect(sender.locator('#share')).toBeDisabled(); + // ü decomposed, u and a combining diaeresis. + await sender.fill('#salt', ' Gru\u0308ße '); + await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'false'); + const own = await share(); + expect(own.hash).toBe(swarm(own.code, 'Grüße')); + await expect(label).toHaveText(/^\s*Code, give this and your salt to the receiver, valid until .+:\s*$/); + await locked(true); + + // 16 of the code's characters. + await sender.clock.fastForward('06:00'); + await locked(false); + await sender.click('#generate-salt'); + const generated = await sender.inputValue('#salt'); + expect(generated).toMatch(/^[0-9a-zA-Z]{16}$/); + const resalted = await share(); + expect(resalted.hash).toBe(swarm(resalted.code, generated)); + + // What can't be a code is told right away, that search is over. + await sender.fill('#receive-code', 'abcdefghij'); + await sender.click('#receive'); + await expect(sender.locator('#receive-error')).toHaveText('a code has 11 letters and digits, check it'); + await locked(false); + + await sender.fill('#receive-code', 'abcdefghijk'); + await sender.click('#receive'); + await expect.poll(() => hashes).toContain(swarm('abcdefghijk', generated)); + await locked(true); + }); + }); + + // Until the transfer is over, on both sides. + test(`salt: ${name} stays while the peers are connected`, async () => { + const tracker = await ownTracker(); + const [sender, receiver] = await Promise.all([open(name), open(name)]); + for (const page of [sender, receiver]) { + await page.uncheck('#stun'); + await page.click('#servers summary'); + await page.fill('#trackers', tracker); + await page.check('#own-salt'); + await page.fill('#salt', 'salt'); + } + const locked = (disabled: boolean) => + Promise.all( + [sender, receiver].flatMap((page) => + ['#own-salt', '#salt', '#generate-salt'].map((id) => + expect(page.locator(id)).toBeEnabled({ enabled: !disabled }), + ), + ), + ); + + await withLogs(sender, receiver, async () => { + await connect('tracker', sender, receiver, await payload(randomBytes(1000))); + await expect(sender.locator('#send-status')).toHaveText('Waiting for the receiver to download'); + await expect(receiver.locator('#receive-status')).toHaveText('Click Download to save the file'); + await locked(true); + + const started = downloadStarts(receiver); + await receiver.click('#download'); + await started; + await expect(sender.locator('#send-status')).toHaveText('Delivered'); + await expect(receiver.locator('#receive-status')).toHaveText('Download complete'); + await locked(false); + }); + }); + // 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 () => { @@ -1156,7 +1316,6 @@ for (const name of Object.keys(BROWSERS)) { // 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 }; @@ -1191,12 +1350,12 @@ for (const name of Object.keys(BROWSERS)) { await fastForward(330_000); await expect(sender.locator('#send-error')).toHaveText( - 'nobody received the file within 6 minutes, share it again', + new RegExp(`^nobody received the file ${UNTIL}, 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', + new RegExp(`^no sender answered ${UNTIL}, ask the sender for a new code$`), ); await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]); await expectClosed(sender); @@ -1225,7 +1384,7 @@ for (const name of Object.keys(BROWSERS)) { 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.fill('#receive-code', `nobodyhere${session}`); await receiver.click('#receive'); } await expect.poll(deadlines).toEqual([1, 1]); @@ -1245,7 +1404,6 @@ for (const name of Object.keys(BROWSERS)) { // gets no turn either. test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => { const sender = await open(name, { init: holdDecrypts }); - await sender.clock.install(); const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); const decrypts = () => sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts); @@ -1259,7 +1417,7 @@ for (const name of Object.keys(BROWSERS)) { await expect.poll(decrypts).toEqual({ held: 1, done: 0 }); await sender.clock.fastForward('06:00'); await expect(sender.locator('#send-error')).toHaveText( - 'nobody received the file within 6 minutes, share it again', + new RegExp(`^nobody received the file ${UNTIL}, share it again$`), ); await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts()); @@ -1324,10 +1482,10 @@ for (const name of Object.keys(BROWSERS)) { await fastForward('06:00'); await fastForward(CONNECT_TIMEOUT); await expect(sender.locator('#send-error')).toHaveText( - `no receiver connected within 6 minutes: the receiver ${NO_PUBLIC}`, + new RegExp(`^no receiver connected ${UNTIL}: the receiver ${NO_PUBLIC}$`), ); await expect(receiver.locator('#receive-error')).toHaveText( - `no sender connected within 6 minutes: this side ${NO_PUBLIC}`, + new RegExp(`^no sender connected ${UNTIL}: this side ${NO_PUBLIC}$`), ); await expectClosed(sender); await expectClosed(receiver); @@ -1346,7 +1504,7 @@ for (const name of Object.keys(BROWSERS)) { await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`); const code = (await sender.locator('#send-code').textContent())!; await intrude(intruder, swarm(code)); - await intruder.fill('#receive-code', 'notthecode'); + await intruder.fill('#receive-code', 'notthecode0'); await intruder.click('#receive'); await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 }); await intruder.context().close(); @@ -1366,7 +1524,6 @@ for (const name of Object.keys(BROWSERS)) { test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]); - await sender.clock.install(); const source = await payload(randomBytes(SIZE)); await withLogs(sender, receiver, async () => { @@ -1537,15 +1694,27 @@ async function interpose(middle: Page, code: string, toSender: Announce[], toRec ); } -// What secrets in src/core.ts derives from the code for info, PBKDF2 once per code. -const masters = new Map(); -function secret(code: string, info: string, length: number) { - if (!masters.has(code)) masters.set(code, pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256')); - return Buffer.from(hkdfSync('sha256', masters.get(code)!, '', info, length)); +// The salt src/core.ts derives with for a code made or entered around TEST_TIME: the start of the window +// the code's last character tells, the one nearest TEST_TIME's, then own if given. +function saltOf(code: string, own?: string) { + const now = Math.floor(TEST_TIME / SALT_WINDOW); + const cycle = CODE_CHARS.length; + const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle; + const salt = new Date((now + (ahead < cycle / 2 ? ahead : ahead - cycle)) * SALT_WINDOW).toISOString().slice(0, 16); + return own === undefined ? salt : `${salt} ${own}`; } -// The code's info_hash. -const swarm = (code: string) => secret(code, 'swarm', 20).toString('latin1'); +// What secrets in src/core.ts derives from the code and own salt for info, PBKDF2 once per pair. +const masters = new Map(); +function secret(code: string, info: string, length: number, own?: string) { + const salt = saltOf(code, own); + const pair = JSON.stringify([code, salt]); + if (!masters.has(pair)) masters.set(pair, pbkdf2Sync(code, `hellcon ${salt}`, 600_000, 32, 'sha256')); + return Buffer.from(hkdfSync('sha256', masters.get(pair)!, '', info, length)); +} + +// The info_hash of the code with the own salt, if any. +const swarm = (code: string, own?: string) => secret(code, 'swarm', 20, own).toString('latin1'); // Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code. function seal(code: string, type: 'offer' | 'answer', sdp: string) { @@ -1610,14 +1779,11 @@ const garbageOffer = (code?: string) => const NO_PUBLIC = 'has no public address, between different networks both sides need STUN'; -// A sender and a receiver as if on different networks, with the servers open and the clock installed. +// A sender and a receiver as if on different networks, with the servers open. // Only the sender has a public address, from the fake STUN server, it answers nobody though. async function apart(name: string) { const pages = await Promise.all([open(name, { init: dropHosts }), open(name, { init: dropHosts })]); - for (const page of pages) { - await page.clock.install(); - await page.click('#servers summary'); - } + for (const page of pages) await page.click('#servers summary'); await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`); await pages[1]!.uncheck('#stun'); return pages as [Page, Page]; @@ -1685,15 +1851,14 @@ function holdDecrypts() { }; } -// 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. +// Init script: window.deadlines() counts the core's pending expiry timers, see deadline in +// src/core.ts. 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); + if (!/\bdeadline\b.*\/src\/core\.ts/.test(new Error().stack ?? '')) return set(handler, ms); const id = set(() => { pending.delete(id); handler(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fe86458..875e9b1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -571,8 +571,8 @@ packages: engines: {node: '>=20'} hasBin: true - postcss@8.5.31: - resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} rolldown@1.2.15: @@ -819,7 +819,7 @@ snapshots: '@vue/shared': 3.5.44 estree-walker: 2.0.2 magic-string: 0.30.21 - postcss: 8.5.31 + postcss: 8.5.32 source-map-js: 1.2.2 '@vue/compiler-ssr@3.5.44': @@ -947,7 +947,7 @@ snapshots: dependencies: playwright-core: 1.64.1 - postcss@8.5.31: + postcss@8.5.32: dependencies: nanoid: 3.3.20 picocolors: 1.1.1 @@ -989,7 +989,7 @@ snapshots: dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 - postcss: 8.5.31 + postcss: 8.5.32 rolldown: 1.2.15 tinyglobby: 0.2.17 optionalDependencies: diff --git a/src/App.vue b/src/App.vue index 91ae147..5e1765a 100644 --- a/src/App.vue +++ b/src/App.vue @@ -8,36 +8,27 @@ import { DEFAULT_STUN_SERVERS, DEFAULT_TRACKERS, type Events, + formatTime, type Incoming, type Phase, type ReceiveEvents, + randomCode, receiveViaTracker, + type SendEvents, sendViaTracker, - TRACKER_WAIT, } from './core'; -const SETTINGS_KEY = 'hellcon:settings'; - -// Same object as the core's, so the core sees every change. +// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the +// defaults. const settings = reactive(coreSettings); -// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay. -try { - const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}'); - if (typeof saved.stun === 'boolean') settings.stun = saved.stun; - if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers; - if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers; -} catch {} - -watch( - settings, - () => { - try { - localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); - } catch {} - }, - { deep: true }, -); +// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share. +const ownSalt = reactive({ on: false, text: '' }); +// Empty is no salt, Share and Receive wait for one. +const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim()); +const salt = () => (ownSalt.on ? ownSalt.text : undefined); +// From the code's alphabet, 16 characters are about 95 bits. +const onGenerateSalt = () => (ownSalt.text = randomCode(16)); // RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core. // For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection @@ -69,7 +60,7 @@ function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boo .filter(Boolean), ); const invalid = computed(() => lines.value.filter((line) => !valid(line))); - // Immediate, a saved list may hold lines this browser rejects. + // Immediate, a default may be a line this browser rejects. watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true }); // Unwraps both refs, so the template can bind them as plain properties. return reactive({ text, invalid }); @@ -89,10 +80,10 @@ const shared = 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(''); +// Until when a receiver can find the share with its code, whether with an own salt and whether that +// passed, as the core tells. +const sendUntil = ref(0); const sendExpired = ref(false); -let sendTimer: number | undefined; const offerInput = ref(''); const answer = ref(''); @@ -126,7 +117,11 @@ const events: Omit = { type Progress = { read: number; size: number }; const sent = ref(); -const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) }; +const sendEvents: SendEvents = { + ...events, + progress: (read, size) => (sent.value = { read, size }), + expired: () => (sendExpired.value = true), +}; const incoming = ref(); const received = ref(); @@ -186,12 +181,15 @@ let acceptAnswer: ((answer: string) => Promise) | undefined; // the one before: its connections close and what it showed goes, so nothing else can write here. let session: AbortController | undefined; const side = ref<'send' | 'receive'>(); +// Whether the session is a tracker share or search, which runs with the salt it started with. +const viaTracker = ref(false); // what goes into the log, so the sessions in it can be told apart. -function begin(on: 'send' | 'receive', what: string) { +function begin(on: 'send' | 'receive', what: string, tracker = false) { session?.abort(); session = new AbortController(); side.value = on; + viaTracker.value = tracker; events.log(`--- ${what} ---`); error.value = ''; status.value = undefined; @@ -202,7 +200,6 @@ function begin(on: 'send' | 'receive', what: string) { received.value = undefined; sendCode.value = ''; sendExpired.value = false; - clearTimeout(sendTimer); offer.value = ''; answer.value = ''; acceptAnswer = undefined; @@ -238,7 +235,7 @@ function formatSize(bytes: number) { bytes /= 1024; unit++; } - return `${bytes.toFixed(unit ? 1 : 0)} ${units[unit]}`; + return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`; } async function onCreateOffer() { @@ -263,13 +260,12 @@ async function onCreateAnswer() { } async function onShare() { - const signal = begin('send', `share ${file.value!.name} via tracker`); + const signal = begin('send', `share ${file.value!.name} via tracker`, true); shared.value = file.value; - const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal)); - 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); + const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt())); + if (!result) return; + sendCode.value = result.code; + sendUntil.value = result.until; } // Also once the transfer started, which closes the trackers, and once the share failed: every error on @@ -277,20 +273,52 @@ async function onShare() { const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value); function onReceive() { - const signal = begin('receive', 'receive via tracker'); - attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal)); + const signal = begin('receive', 'receive via tracker', true); + attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt())); } + +// The salt stays as it is while a tracker share or search runs: it found or waits in the swarm of the +// salt it started with, another one shown would be the wrong one to give the receiver. +const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stopped'].includes(phase.value!));