diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..710f30b --- /dev/null +++ b/biome.json @@ -0,0 +1,20 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, + "files": { "includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg"] }, + "formatter": { "indentStyle": "space", "lineWidth": 120 }, + "javascript": { "formatter": { "quoteStyle": "single" } }, + "css": { "formatter": { "quoteStyle": "single" } }, + "html": { + "experimentalFullSupportEnabled": true, + "formatter": { "enabled": true, "selfCloseVoidElements": "always" } + }, + "linter": { + "rules": { + "preset": "recommended", + "nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" }, + "style": { "noNonNullAssertion": "off", "noDescendingSpecificity": "off" }, + "a11y": { "useSemanticElements": "off" } + } + } +} diff --git a/e2e.spec.ts b/e2e.spec.ts index 8a45c1f..bc82820 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -4,15 +4,15 @@ import { createReadStream } from 'node:fs'; import { open as openFile, readFile, writeFile } from 'node:fs/promises'; import { networkInterfaces } from 'node:os'; import { - chromium, - expect, - firefox, - test, type Browser, type BrowserContext, type BrowserType, + chromium, + expect, + firefox, type Page, type WebSocket as PageSocket, + test, type WebSocketRoute, } from '@playwright/test'; import { build, createServer, preview, type ViteDevServer } from 'vite'; @@ -130,7 +130,8 @@ test.afterAll(async () => { // 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 } = {}) { - const browser = await (browsers[name] ??= BROWSERS[name]!.launch()); + 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(); @@ -192,8 +193,10 @@ function trackPeers() { // Everything the page opened for a transfer is closed again: its peer connections and tracker sockets. async function expectClosed(page: Page) { const peers = () => - page.evaluate(() => - (window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length, + page.evaluate( + () => + (window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed') + .length, ); await expect.poll(peers).toBe(0); await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0); @@ -289,7 +292,10 @@ async function withLogs(sender: Page, receiver: Page, fn: () => Promise) { try { await fn(); } finally { - for (const [name, page] of [['sender', sender], ['receiver', receiver]] as const) { + for (const [name, page] of [ + ['sender', sender], + ['receiver', receiver], + ] as const) { await test.info().attach(`${name} log`, { body: (await log(page).catch(() => null)) ?? '' }); } } @@ -353,6 +359,11 @@ async function transfer( expect(await hash(await download.path())).toBe(await hash(source)); await expect(receiver.locator('#log')).toContainText('download complete'); await expect(sender.locator('#log')).toContainText('delivered'); + if (mode === 'tracker') { + // The transfer used the share up, another receiver would wait for nothing. + await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:'); + await expect(sender.locator('#copy-send-code')).toBeDisabled(); + } await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100); await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100); // Removed hidden pages release the service worker for updates. @@ -383,7 +394,10 @@ for (const from of Object.keys(BROWSERS)) { // Through the public STUN servers and trackers. The signaling doesn't depend on the browser pair, one // pairing each way is enough. for (const mode of ['manual', 'tracker']) { - for (const [from, to] of [['chromium', 'firefox'], ['firefox', 'chromium']] as const) { + for (const [from, to] of [ + ['chromium', 'firefox'], + ['firefox', 'chromium'], + ] as const) { test(`live ${mode}: ${from} sends to ${to}`, async () => { const [sender, receiver] = await Promise.all([open(from), open(to)]); await transfer(mode, sender, receiver, await payload(randomBytes(SIZE)), SIZE); @@ -409,7 +423,10 @@ for (const name of Object.keys(BROWSERS)) { test(`servers: ${name} skips invalid lines and keeps the lists over a reload`, async () => { const page = await open(name); const core = () => - page.evaluate((path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]), '/src/core.ts'); + page.evaluate( + (path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]), + '/src/core.ts', + ); await page.click('#servers summary'); // Both would make the constructors throw. await page.fill('#stun-servers', 'stun:stun.example:99999'); @@ -465,7 +482,9 @@ for (const name of Object.keys(BROWSERS)) { await updateWorker(receiver); // The update has to wait instead of replacing the worker that feeds the download. await expect - .poll(() => receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting)) + .poll(() => + receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting), + ) .toBe(true); expect(await updated(receiver)).toBe(false); await release(receiver); @@ -633,7 +652,9 @@ for (const name of Object.keys(BROWSERS)) { await inject(sender, 10_000); const { download } = await started; await inject(sender, 10_001); - await expect(receiver.locator('#receive-error')).toHaveText('download failed: the sender sent more than it offered'); + await expect(receiver.locator('#receive-error')).toHaveText( + 'download failed: the sender sent more than it offered', + ); await expect(receiver.locator('iframe')).toHaveCount(0); // Firefox leaves the download stalled instead of failing it, see TODO.md. if (name === 'chromium') expect(await download.failure()).not.toBeNull(); @@ -730,7 +751,12 @@ for (const name of Object.keys(BROWSERS)) { await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); await receiver.click('#receive'); await expect(receiver.locator('#receive-error')).toHaveText(rejected); - await expect.poll(() => trackers.map(({ sockets, open }) => [sockets.length, open])).toEqual([[2, 0], [2, 0]]); + await expect + .poll(() => trackers.map(({ sockets, open }) => [sockets.length, open])) + .toEqual([ + [2, 0], + [2, 0], + ]); }); }); @@ -739,7 +765,8 @@ for (const name of Object.keys(BROWSERS)) { test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => { const sender = await open(name, { init: countAbortListeners }); const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); - const listeners = () => sender.evaluate(() => (window as unknown as { abortListeners: () => number }).abortListeners()); + const listeners = () => + sender.evaluate(() => (window as unknown as { abortListeners: () => number }).abortListeners()); const unusable = async () => (await log(sender))!.match(/unusable offer/g)?.length ?? 0; await withLogs(sender, sender, async () => { @@ -765,6 +792,7 @@ for (const name of Object.keys(BROWSERS)) { 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]; + // biome-ignore lint/suspicious/noExplicitAny: raw tracker messages, the test reads nested fields as it needs them const announced = pages.map(() => [] as Record[]); // 0 would announce in a loop, the app waits 30 s at least. const trackers = await Promise.all( @@ -795,10 +823,16 @@ for (const name of Object.keys(BROWSERS)) { 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()); + 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('#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( @@ -823,7 +857,9 @@ for (const name of Object.keys(BROWSERS)) { ), ); const deadlines = () => - Promise.all(pages.map((page) => page.evaluate(() => (window as unknown as { deadlines: () => number }).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))); @@ -886,9 +922,12 @@ for (const name of Object.keys(BROWSERS)) { // The sender notices the receiver left, Chromium only once the connection counts as failed. await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 }); - await expect(receiver.locator('#check-local')).toHaveText(new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), { - timeout: 45_000, - }); + await expect(receiver.locator('#check-local')).toHaveText( + new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), + { + timeout: 45_000, + }, + ); await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!); const started = downloadStarts(receiver); await sender.click('#confirm'); diff --git a/package.json b/package.json index 002b2b6..e64986b 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,8 @@ "build": "vue-tsc && vite build", "preview": "vite preview", "typecheck": "vue-tsc", + "lint": "biome check", + "format": "biome check --write", "test": "playwright test", "test:install": "playwright install chromium firefox", "test:large": "LARGE=1 playwright test -g large" @@ -17,6 +19,7 @@ "vue": "^3.5.44" }, "devDependencies": { + "@biomejs/biome": "2.5.15", "@playwright/test": "^1.64.1", "@types/node": "^26.6.5", "@vitejs/plugin-vue": "^6.0.10", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 25feb50..162dac6 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: + '@biomejs/biome': + specifier: 2.5.15 + version: 2.5.15 '@playwright/test': specifier: ^1.64.1 version: 1.64.1 @@ -208,6 +211,63 @@ packages: resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} engines: {node: '>=6.9.0'} + '@biomejs/biome@2.5.15': + resolution: {integrity: sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-darwin-arm64@2.5.15': + resolution: {integrity: sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.5.15': + resolution: {integrity: sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@2.5.15': + resolution: {integrity: sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64@2.5.15': + resolution: {integrity: sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64-musl@2.5.15': + resolution: {integrity: sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64@2.5.15': + resolution: {integrity: sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-win32-arm64@2.5.15': + resolution: {integrity: sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@2.5.15': + resolution: {integrity: sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} @@ -608,6 +668,41 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 + '@biomejs/biome@2.5.15': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 2.5.15 + '@biomejs/cli-darwin-x64': 2.5.15 + '@biomejs/cli-linux-arm64': 2.5.15 + '@biomejs/cli-linux-arm64-musl': 2.5.15 + '@biomejs/cli-linux-x64': 2.5.15 + '@biomejs/cli-linux-x64-musl': 2.5.15 + '@biomejs/cli-win32-arm64': 2.5.15 + '@biomejs/cli-win32-x64': 2.5.15 + + '@biomejs/cli-darwin-arm64@2.5.15': + optional: true + + '@biomejs/cli-darwin-x64@2.5.15': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.5.15': + optional: true + + '@biomejs/cli-linux-arm64@2.5.15': + optional: true + + '@biomejs/cli-linux-x64-musl@2.5.15': + optional: true + + '@biomejs/cli-linux-x64@2.5.15': + optional: true + + '@biomejs/cli-win32-arm64@2.5.15': + optional: true + + '@biomejs/cli-win32-x64@2.5.15': + optional: true + '@jridgewell/sourcemap-codec@1.6.0': {} '@oxc-project/types@0.154.0': {} diff --git a/public/sw.js b/public/sw.js index 2a686e4..f1d719a 100644 --- a/public/sw.js +++ b/public/sw.js @@ -23,7 +23,10 @@ function open(id, { name, size }, port) { if (chunk) { download.read += chunk.byteLength; // Every MiB, src/core.ts forwards it to the sender for its flow control window. - if (download.read - download.reported >= 2 ** 20) port.postMessage((download.reported = download.read)); + if (download.read - download.reported >= 2 ** 20) { + download.reported = download.read; + port.postMessage(download.read); + } return controller.enqueue(chunk); } controller.close(); @@ -41,7 +44,10 @@ function open(id, { name, size }, port) { downloads.set(id, download); // RFC 8187 encoding, which leaves nothing in the name that could end the header value. - const encoded = encodeURIComponent(name.toWellFormed()).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16)}`); + const encoded = encodeURIComponent(name.toWellFormed()).replace( + /['()*]/g, + (char) => `%${char.charCodeAt(0).toString(16)}`, + ); const headers = { 'Content-Type': 'application/octet-stream', 'Content-Length': String(size), @@ -72,7 +78,10 @@ self.addEventListener('message', ({ data, ports: [port] }) => { self.addEventListener('fetch', (event) => { const id = new URL(event.request.url).pathname.split('/').pop(); // download/ itself is the empty page src/core.ts keeps open to hold this worker during a transfer. - if (!id) return event.respondWith(new Response('', { headers: { 'Content-Type': 'text/html; charset=utf-8' } })); + if (!id) + return event.respondWith( + new Response('', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }), + ); const response = responses.get(id); responses.delete(id); event.respondWith(response ?? new Response('download expired', { status: 404 })); diff --git a/src/App.vue b/src/App.vue index 23c09b5..8de5662 100644 --- a/src/App.vue +++ b/src/App.vue @@ -2,17 +2,17 @@ import { computed, reactive, ref, watch } from 'vue'; import { answerOffer, + type Check, + settings as coreSettings, createOffer, DEFAULT_STUN_SERVERS, DEFAULT_TRACKERS, - receiveViaTracker, - sendViaTracker, - settings as coreSettings, - TRACKER_WAIT, - type Check, type Events, type Incoming, type ReceiveEvents, + receiveViaTracker, + sendViaTracker, + TRACKER_WAIT, } from './core'; const SETTINGS_KEY = 'hellcon:settings'; @@ -61,7 +61,12 @@ const isTracker = (url: string) => // A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped. function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) { const text = ref(settings[key].join('\n')); - const lines = computed(() => text.value.split('\n').map((line) => line.trim()).filter(Boolean)); + const lines = computed(() => + text.value + .split('\n') + .map((line) => line.trim()) + .filter(Boolean), + ); const invalid = computed(() => lines.value.filter((line) => !valid(line))); // Immediate, a saved list may hold lines this browser rejects. watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true }); @@ -236,8 +241,9 @@ async function onShare() { 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); +// Also once the transfer started, which closes the trackers, and once the share failed: every error on +// the tracker ends it. +const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value); function onReceive() { const signal = begin('receive'); @@ -250,6 +256,7 @@ function onReceive() {

HellCon

@@ -258,8 +265,8 @@ function onReceive() {
@@ -296,13 +303,15 @@ function onReceive() {

Tracker

- +