Refactor the app

This commit is contained in:
Schluffe committed 2026-10-28 21:05:47 +01:00
1 parent f53d39ae69
commit 8f82700736
11 files changed
+2032 -235

No files matched your search

+148 -222
View File
@@ -1,3 +1,5 @@
import { type Download, downloadsReady, startDownload } from './download';
export const DEFAULT_TRACKERS = [
'wss://tracker.pagequit.net',
'wss://tracker.webtorrent.dev',
@@ -11,6 +13,10 @@ export const DEFAULT_STUN_SERVERS = [
'stun:stun.nextcloud.com:443',
];
// App.vue uses the settings and their defaults, randomCode, formatTime, the types and the sessions
// at the end. src/core.test.ts also tests the other exports on their own, biome.json keeps them to it:
// a new one goes on its list there.
// Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody.
// Read whenever a connection or tracker socket is created, so changes apply to the next one.
export const settings = {
@@ -19,41 +25,34 @@ export const settings = {
trackers: [...DEFAULT_TRACKERS],
};
const CHUNK_SIZE = 16 * 1024;
const MAX_BUFFERED = 1024 * 1024;
export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024;
// The receiving side can't pause a data channel, so it reports how much the download manager has
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM.
const WINDOW = 8 * 1024 * 1024;
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
const KEEPALIVE = 10_000;
// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its
// download manager. Its frame removed before that, the download never shows up, though the worker
// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests.
const DOWNLOAD_GRACE = 1000;
export const WINDOW = 8 * 1024 * 1024;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
// A STUN server that reports no public address by then gets passed over, see stunServer.
// A STUN server that reports no public address by then gets passed over, see stunChoice.
const PROBE_TIMEOUT = 2000;
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
const TRACKER_TIMEOUT = 10_000;
export const TRACKER_TIMEOUT = 10_000;
// 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: Chromium never even fails its connection. The manual
// sender gives up on the answer after it as well.
const CONNECT_TIMEOUT = 30_000;
export 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.
// The manual receiver waits this long for the sender to connect, it has to get the answer first.
export const TRACKER_WAIT = 6 * 60_000;
const MIN_INTERVAL = 30_000;
export const MIN_INTERVAL = 30_000;
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
const PBKDF2_ITERATIONS = 600_000;
export const PBKDF2_ITERATIONS = 600_000;
// A tracker peer that connects but proves no code gives up its turn after this. Signing takes
// milliseconds, a peer that knows the code is never near it.
const PROOF_TIMEOUT = 10_000;
export const PROOF_TIMEOUT = 10_000;
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
const MAX_NAME = 1024;
export const MAX_NAME = 1024;
export type Check = {
local: string;
@@ -101,7 +100,7 @@ export type ReceiveEvents = Events & {
// Closes it once the session ends, right away if it already did. Closing it earlier lets go of it, else
// the session would keep every connection a rejected or failed peer left behind until it ends.
function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
export function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
const closeResource = resource.close.bind(resource);
// Without the abort event, WebSocket.close() would take it for a close code and throw.
const close = () => closeResource();
@@ -115,14 +114,14 @@ function own<T extends { close: () => void }>(signal: AbortSignal, resource: T)
}
// Closing everything fires events of its own, none of them reaches the caller after the abort.
function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
export function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
return Object.fromEntries(
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
) as T;
}
// Runs expire after ms unless closed before, cleared with the session.
function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
export function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
const timer = setTimeout(() => {
owned.close();
expire();
@@ -158,81 +157,88 @@ async function probe(url: string, stop: AbortSignal) {
}
}
// Probes list in order from start on, the ones before start last, see stunServer.
function probeFrom(list: string[], start: number) {
const key = list.join('\n');
const stop = new AbortController();
let at = start;
let settled = false;
let waiting = 0;
const server = (async () => {
for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) {
// No further server is contacted once nobody waits, STUN was turned off or the list changed.
if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return;
if (await probe(list[at]!, stop.signal)) return list[at];
}
})().finally(() => (settled = true));
const choice = {
list,
key,
server,
// Before it found one, the next probe goes on where this one stopped.
stopped: false,
// The server for a session's connection. Once no session waits for it any more, the probe stops.
async wait(signal: AbortSignal) {
if (signal.aborted) return;
waiting++;
const leave = () => {
if (--waiting || settled) return;
choice.stopped = true;
resume = { key, at };
stop.abort();
};
signal.addEventListener('abort', leave, { once: true });
try {
return await server;
} finally {
signal.removeEventListener('abort', leave);
if (!signal.aborted) waiting--;
}
},
};
// E.g. offline, the next connection probes again.
void server.then((url) => {
if (!url && stun === choice) stun = undefined;
});
return choice;
}
let stun: ReturnType<typeof probeFrom> | undefined;
// Where the next probe of the list with key starts, if not at its first server.
let resume: { key: string; at: number } | undefined;
// Each connection uses one STUN server, so only that one learns the address: the first in the list
// that reports one. It stays for the page's lifetime, unless a connection gets no address from it,
// then the next connection probes on from the server after it. A changed list starts over. None, or
// none reporting an address, means connections without STUN. A device with a public address of its
// own gets none reported (browsers drop it as redundant) and probes them all for every connection.
function stunServer(signal: AbortSignal) {
if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined);
const key = settings.stunServers.join('\n');
if (stun?.key !== key || stun.stopped) {
stun = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
resume = undefined;
// The page has one, see stun, a test makes its own with a probe of its own.
export function stunChoice(answers = probe) {
let current: ReturnType<typeof probeFrom> | undefined;
// Where the next probe of the list with key starts, if not at its first server.
let resume: { key: string; at: number } | undefined;
// Probes list in order from start on, the ones before start last.
function probeFrom(list: string[], start: number) {
const key = list.join('\n');
const stop = new AbortController();
let at = start;
let settled = false;
let waiting = 0;
const server = (async () => {
for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) {
// No further server is contacted once nobody waits, STUN was turned off or the list changed.
if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return;
if (await answers(list[at]!, stop.signal)) return list[at];
}
})().finally(() => (settled = true));
const choice = {
list,
key,
server,
// Before it found one, the next probe goes on where this one stopped.
stopped: false,
// The server for a session's connection. Once no session waits for it any more, the probe stops.
async wait(signal: AbortSignal) {
if (signal.aborted) return;
waiting++;
const leave = () => {
if (--waiting || settled) return;
choice.stopped = true;
resume = { key, at };
stop.abort();
};
signal.addEventListener('abort', leave, { once: true });
try {
return await server;
} finally {
signal.removeEventListener('abort', leave);
if (!signal.aborted) waiting--;
}
},
};
// E.g. offline, the next connection probes again.
void server.then((url) => {
if (!url && current === choice) current = undefined;
});
return choice;
}
return stun.wait(signal);
return {
// The server for a connection of the session with signal, if any.
server(signal: AbortSignal) {
if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined);
const key = settings.stunServers.join('\n');
if (current?.key !== key || current.stopped) {
current = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
resume = undefined;
}
return current.wait(signal);
},
// A connection got no public address from url.
async failed(url: string) {
const choice = current;
if (!choice || (await choice.server) !== url || current !== choice) return;
resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length };
current = undefined;
},
};
}
// A connection got no public address from url.
async function stunFailed(url: string) {
const choice = stun;
if (!choice || (await choice.server) !== url || stun !== choice) return;
resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length };
stun = undefined;
}
const stun = stunChoice();
async function createPeerConnection(signal: AbortSignal) {
const server = await stunServer(signal);
const server = await stun.server(signal);
return own(signal, new RTCPeerConnection({ iceServers: server ? [{ urls: server }] : [] }));
}
@@ -241,7 +247,7 @@ async function createPeerConnection(signal: AbortSignal) {
// biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above
type Message = Record<string, any>;
function parse(data: unknown): Message | undefined {
export function parse(data: unknown): Message | undefined {
if (typeof data !== 'string') return;
try {
const message = JSON.parse(data);
@@ -250,7 +256,7 @@ function parse(data: unknown): Message | undefined {
}
// The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored.
function decode(code: string, type: 'offer' | 'answer') {
export function decode(code: string, type: 'offer' | 'answer') {
try {
return { type, sdp: atob(code.replace(/\s/g, '')) };
} catch {
@@ -262,7 +268,7 @@ function randomBinary(length: number) {
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
}
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// The largest multiple of the alphabet's length a byte holds. The bytes above would make the first
// characters likelier, they are dropped.
const CODE_LIMIT = 256 - (256 % CODE_CHARS.length);
@@ -286,13 +292,13 @@ export const formatTime = (time: number) =>
// its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts
// TRACKER_WAIT from the click whenever in its window that was.
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
const SALT_WINDOW = 6 * 60_000;
const CODE_LENGTH = 11;
export const SALT_WINDOW = 6 * 60_000;
export const CODE_LENGTH = 11;
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
// The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo,
// not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share.
function trackerSalt(at: number, own?: string) {
export function trackerSalt(at: number, own?: string) {
const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16);
if (own === undefined) return salt;
if (!own.trim()) throw new Error('the own salt is empty');
@@ -300,14 +306,14 @@ function trackerSalt(at: number, own?: string) {
}
// A sender's new code and its salt.
function newCode(own?: string) {
export function newCode(own?: string) {
const at = clockWindow(Date.now());
return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) };
}
// The salt of the code a receiver got, its window from half the characters before the clock's to half
// after. Anything else can't be a code, a typo gets told right away instead of searched for.
function codeSalt(code: string, own?: string) {
export function codeSalt(code: string, own?: string) {
if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char)))
throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`);
const now = clockWindow(Date.now());
@@ -325,7 +331,7 @@ function codeSalt(code: string, own?: string) {
// years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one
// system can be other bytes than on the next. HKDF splits the result, the public info_hash tells
// nothing about the keys: one seals the signaling, see seal, one proves the connection.
async function secrets(code: string, salt: string) {
export async function secrets(code: string, salt: string) {
const text = new TextEncoder();
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits(
@@ -356,7 +362,7 @@ async function secrets(code: string, salt: string) {
// the swarm without the code learn the addresses in it, and nobody answers what they can't open. The
// type is sealed along, an offer doesn't pass for an answer. Base64 of IV and ciphertext, in the
// sdp field, so trackers relay it like any other.
async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
export async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
const text = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12));
const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) };
@@ -365,7 +371,7 @@ async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
}
// The SDP, unless it wasn't sealed with the code as that type.
async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) {
export async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) {
// atob throws on what isn't base64, decrypt on anything else.
try {
const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0));
@@ -411,13 +417,13 @@ async function gatherIce(pc: RTCPeerConnection) {
});
});
const [server] = pc.getConfiguration().iceServers ?? [];
if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!);
if (server && !reported && pc.signalingState !== 'closed') void stun.failed([server.urls].flat()[0]!);
}
// Why pc didn't connect, if a missing public address explains it: a side without one from STUN offers
// only local addresses, enough on the same network or VPN. peer names the other side. A device with
// a public address of its own offers none either, see stunServer, so it's a hint, not a diagnosis.
function stunHint(pc: RTCPeerConnection, peer: string) {
// a public address of its own offers none either, see stunChoice, so it's a hint, not a diagnosis.
export function stunHint(pc: RTCPeerConnection, peer: string) {
const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? '');
const local = offersPublic(pc.localDescription);
const remote = offersPublic(pc.remoteDescription);
@@ -439,7 +445,7 @@ const host = (url: string) => URL.parse(url)?.host || url;
// Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can
// brute force with matching certificates. My local code must equal the peer's remote code and vice
// versa, otherwise someone interposed on the signaling.
function securityCheck(pc: RTCPeerConnection) {
export function securityCheck(pc: RTCPeerConnection) {
const short = (sdp = '') =>
sdp
.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]
@@ -452,7 +458,7 @@ function securityCheck(pc: RTCPeerConnection) {
// Every fingerprint the SDP names, in full: one added beside the real one changes the result too.
// Browsers may move them between session and media level, so each counts once.
const fingerprints = (sdp: string) =>
export const fingerprints = (sdp: string) =>
[...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort();
// The security check of tracker signaling, resolves once the peer proved the code. Each side signs its
@@ -460,7 +466,7 @@ const fingerprints = (sdp: string) =>
// against its own view. An interposer has its own certificate towards each side and can't sign for it
// without the code, neither can a peer that found the swarm some other way. One that sends no proof
// within PROOF_TIMEOUT or a wrong one ends the connection.
function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
export function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
const local = pc.localDescription!;
const remote = pc.remoteDescription!;
const statement = (type: string, own: string, peer: string) =>
@@ -502,7 +508,7 @@ function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, e
// pass, a failed check, a peer that left or end closes the connection and calls next: tracker
// signaling goes on with another peer. Without next, as in the manual exchange, the session is over
// and the reason is an error. From start on, sendFile and receiveFile handle a loss.
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
export type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
function connected(
pc: RTCPeerConnection,
@@ -548,7 +554,7 @@ function connected(
// { done } once the download manager read the last byte, or { error } when its download was
// cancelled or failed. Any other message, or one out of turn, is ignored. Every way out of the
// transfer closes the connection.
async function sendFile(
export async function sendFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
file: File,
@@ -640,63 +646,19 @@ async function sendFile(
if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest');
}
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
const downloads = registerDownloads();
// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window.
downloads.catch(() => {});
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
async function registerDownloads() {
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
const pending = registration.installing ?? registration.waiting;
if (!registration.active && pending) {
await new Promise((resolve) =>
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
);
}
if (!registration.active) throw new Error('service worker did not activate');
}
// Awaited before receiving starts, so a browser without service workers fails before connecting.
function downloadsReady() {
return downloads.catch((error) => {
throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`);
});
}
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
// worker in the middle of the download.
async function holdWorker() {
await downloads;
const frame = document.createElement('iframe');
frame.hidden = true;
frame.src = 'download/';
document.body.append(frame);
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
if (!worker) {
frame.remove();
throw new Error('service worker did not take over');
}
return { frame, worker };
}
// Accepts nothing until checked resolved, then tells the sender with { ok }. Its file is offered to
// the user, chunks are accepted only once they started the download. Nothing the sender sends is
// trusted: a malformed offer ends the connection, more bytes than offered or beyond the window fail
// the download. Once it ended, the connection closes.
function receiveFile(
// the download. Once it ended, the connection closes. startDownload saves it, see src/download.ts.
export function receiveFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
events: ReceiveEvents,
handshake: Handshake,
signal: AbortSignal,
) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let saving: Download | undefined;
let received = 0;
// By the download manager. The rest of received is held in this page and the worker.
let read = 0;
@@ -704,86 +666,50 @@ function receiveFile(
let downloading = false;
let complete = false;
let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | undefined> = Promise.resolve(undefined);
const post = (message: object, transfer: Transferable[] = []) =>
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
// To the sender, see sendFile.
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
// A data channel closes only after sending what it buffered, so the last reply still arrives.
channel.addEventListener('close', () => pc.close());
let keepalive: ReturnType<typeof setInterval> | undefined;
// Releases the worker, so a waiting update can take over. A finished download keeps its own frame
// for DOWNLOAD_GRACE, that one doesn't hold the worker.
function release(finished = false) {
clearInterval(keepalive);
const [hold, download] = frames;
hold?.remove();
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
else download?.remove();
}
// The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the
// download running instead of failing it.
function fail(reason: string) {
if (ended) return;
saving?.fail(reason);
failed(reason);
}
// Also when the download failed on its own, no telling it then.
function failed(reason: string) {
if (ended) return;
ended = true;
post({ error: reason });
reply({ error: reason });
channel.close();
events.error(`download failed: ${reason}`);
}
function startDownload() {
worker = holdWorker().then(
({ frame, worker }) => {
frames.push(frame);
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
worker.addEventListener('statechange', () => {
if (worker.state !== 'redundant') return;
fail('service worker stopped');
release();
});
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
if (typeof data === 'number') {
read = data;
events.progress(read, meta!.size);
return reply({ read });
}
if (data === 'ready' && !ended) {
// A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe');
download.hidden = true;
download.src = `download/${id}`;
document.body.append(download);
frames.push(download);
return;
}
if (data === 'failed') fail('the service worker refused it');
if (data === 'finished') {
events.log('download complete');
events.status('done', 'Download complete');
events.progress(meta!.size, meta!.size);
reply({ done: true });
}
if (data === 'cancelled' && !ended) {
events.log('download cancelled');
events.status('stopped', 'Download cancelled');
reply({ error: 'download cancelled' });
}
ended = true;
channel.close();
release(data === 'finished');
};
worker.postMessage({ id, ...meta }, [port2]);
return worker;
function startSaving(file: { name: string; size: number }) {
saving = startDownload(file, {
read: (bytes) => {
read = bytes;
events.progress(read, file.size);
reply({ read });
},
(error) => void fail(String(error)),
);
finished: () => {
events.log('download complete');
events.status('done', 'Download complete');
events.progress(file.size, file.size);
reply({ done: true });
ended = true;
channel.close();
},
cancelled: () => {
events.log('download cancelled');
events.status('stopped', 'Download cancelled');
reply({ error: 'download cancelled' });
ended = true;
channel.close();
},
failed,
});
}
void handshake.checked.then(() => {
@@ -795,7 +721,7 @@ function receiveFile(
function receivedAll() {
complete = true;
post({ done: true });
saving!.end();
events.log('received');
}
@@ -809,7 +735,7 @@ function receiveFile(
events.log(`receiving ${meta!.name}`);
events.status('transfer', 'Receiving');
events.progress(0, meta!.size);
startDownload();
startSaving(meta!);
reply({ start: true });
if (!meta!.size) receivedAll();
}
@@ -832,7 +758,7 @@ function receiveFile(
if (received > meta!.size) return fail('the sender sent more than it offered');
// sendFile never has more than WINDOW unread plus the chunk it just sent.
if (received - read > WINDOW + CHUNK_SIZE) return fail('the sender ignored the flow control');
post({ chunk: data }, [data]);
saving!.write(data);
if (received === meta!.size) receivedAll();
}
};
@@ -938,7 +864,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
// later one only concerns that message and is logged. message may be async, the next message doesn't
// wait for it. lost runs once it closed without close() being called: unreachable, lost, rejected or
// without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names.
function trackerSocket(
export function trackerSocket(
url: string,
signal: AbortSignal,
events: Events,
@@ -998,7 +924,7 @@ function trackerSocket(
type Tracker = ReturnType<typeof trackerSocket>;
// Once none of the trackers is left: what the user can do about it, and why if any rejected.
function noTracker(trackers: (Tracker | undefined)[]) {
export function noTracker(trackers: (Tracker | undefined)[]) {
const rejected = trackers.flatMap((tracker) => tracker?.rejected ?? []);
const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable';
return `${reason}, check the list under Servers and try again`;