Ask before downloading and show transfer progress

Tracker codes now use 8 of [0-9a-zA-Z] instead of 8 digits. After both
security checks the receiver sees the offered file and starts the download
itself, the sender waits for it. Both sides show a progress bar of what the
download manager has read. Copy buttons for the tracker code, offer and
answer; the manual exchange is folded away below the tracker on both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-24 14:15:48 +02:00
1 parent 85ccdbfc03
commit bacc15baaf
4 files changed
+321 -72

No files matched your search

+75 -22
View File
@@ -42,6 +42,17 @@ export type Events = {
log: (message: string) => void;
// Called on both sides once connected, and without a check when it ended undecided.
check: (check?: Check) => void;
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
// the transfer starts.
progress: (read: number, size: number) => void;
};
// The sender's file, offered once both sides confirmed the check. download() starts saving it.
export type Incoming = { name: string; size: number; download: () => void };
export type ReceiveEvents = Events & {
// Without a file when the sender left before the download started.
incoming: (file?: Incoming) => void;
};
function createPeerConnection() {
@@ -54,8 +65,15 @@ function randomBinary(length: number) {
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
}
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// 8 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
function randomCode() {
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 100_000_000).padStart(8, '0');
let code = '';
while (code.length < 8)
for (const byte of crypto.getRandomValues(new Uint8Array(8)))
if (byte < 248 && code.length < 8) code += CODE_CHARS[byte % 62];
return code;
}
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
@@ -144,9 +162,10 @@ function connected(
};
}
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers
// with { read } progress, { done } once the download manager read the last byte, or { error } when
// its download was cancelled or failed.
// Offers the file once checked resolved and the receiver confirmed its own check with { ok }, sends
// it once the receiver started the download with { start }. Then it answers with { read } progress,
// { done } once the download manager read the last byte, or { error } when its download was
// cancelled or failed.
async function sendFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
@@ -159,6 +178,7 @@ async function sendFile(
}
let read = 0;
let accepted = false;
let started = false;
let sending = false;
let stopped = false;
// Every event the send loop can wait for calls this.
@@ -172,11 +192,16 @@ async function sendFile(
channel.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.ok) accepted = true;
else if (message.start) started = true;
// Before that, nothing else can come from a receiver that passed its check.
else if (!sending) return;
if (message.read) read = message.read;
if (message.read) {
read = message.read;
events.progress(read, file.size);
}
if (message.done) {
events.log('delivered');
events.progress(file.size, file.size);
// Finished, a later close is no loss.
stopped = true;
}
@@ -195,11 +220,17 @@ async function sendFile(
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
events.log(`offered ${file.name} (${file.size} bytes)`);
if (!started) events.log('waiting for the receiver to download');
while (!stopped && !started) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
sending = true;
handshake.start();
events.log(`sending ${file.name} (${file.size} bytes)`);
events.log(`sending ${file.name}`);
events.progress(0, file.size);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
await new Promise<void>((resolve) => (wake = resolve));
@@ -253,13 +284,15 @@ async function holdWorker() {
return { frame, worker };
}
// Accepts nothing until checked resolved, then tells the sender with { ok }.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, handshake: Handshake) {
// 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.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: ReceiveEvents, handshake: Handshake) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let received = 0;
let confirmed = false;
let downloading = 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 | void> = Promise.resolve();
@@ -298,7 +331,10 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
});
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
if (typeof data === 'number') return reply({ read: data });
if (typeof data === 'number') {
events.progress(data, meta!.size);
return reply({ read: data });
}
if (data === 'ready' && !ended) {
// A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe');
@@ -310,6 +346,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
}
if (data === 'finished') {
events.log('download complete');
events.progress(meta!.size, meta!.size);
reply({ done: true });
}
if (data === 'cancelled' && !ended) {
@@ -330,27 +367,43 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
events.log('waiting for the sender');
});
function complete() {
post({ done: true });
events.log('received');
}
function download() {
if (downloading || ended) return;
downloading = true;
handshake.start();
events.log(`receiving ${meta!.name}`);
events.progress(0, meta!.size);
startDownload();
reply({ start: true });
if (!meta!.size) complete();
}
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (ended || !confirmed) return;
if (typeof data === 'string') {
if (meta) return;
meta = JSON.parse(data);
handshake.start();
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
startDownload();
} else {
events.log(`offered ${meta!.name} (${meta!.size} bytes)`);
events.incoming({ ...meta!, download });
} else if (downloading) {
received += data.byteLength;
post({ chunk: data }, [data]);
}
if (meta && received === meta.size) {
post({ done: true });
events.log('received');
if (received === meta!.size) complete();
}
};
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
// peer only closes the channel in Firefox, Chromium just fails the connection.
// peer only closes the channel in Firefox, Chromium just fails the connection. Before the download
// started, connected reports it and only the offer goes.
function lost() {
if (meta && received < meta.size) fail('connection lost');
if (!meta) return;
if (!downloading) events.incoming();
else if (received < meta.size) fail('connection lost');
}
channel.addEventListener('close', lost);
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
@@ -371,7 +424,7 @@ export async function createOffer(file: File, events: Events) {
};
}
export async function answerOffer(offer: string, events: Events) {
export async function answerOffer(offer: string, events: ReceiveEvents) {
await downloadsReady(events);
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) =>
@@ -447,7 +500,7 @@ export async function sendViaTracker(file: File, events: Events) {
// 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.
export async function receiveViaTracker(code: string, events: Events) {
export async function receiveViaTracker(code: string, events: ReceiveEvents) {
await downloadsReady(events);
const hash = await infoHash(code);
const peerId = randomBinary(20);