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

+106 -29
View File
@@ -10,6 +10,8 @@ import {
settings as coreSettings,
type Check,
type Events,
type Incoming,
type ReceiveEvents,
} from './main';
const SETTINGS_KEY = 'hellcon:settings';
@@ -87,7 +89,8 @@ const check = ref<Check>();
const confirmed = ref(false);
const log = ref<string[]>([]);
const events: Events = {
// Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
check: (result) => {
check.value = result;
@@ -95,12 +98,47 @@ const events: Events = {
},
};
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
// a transfer starts.
type Progress = { read: number; size: number };
const sent = ref<Progress>();
const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) };
const incoming = ref<Incoming>();
const received = ref<Progress>();
const receiveEvents: ReceiveEvents = {
...events,
progress: (read, size) => (received.value = { read, size }),
incoming: (file) => {
incoming.value = file;
received.value = undefined;
},
};
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
function onConfirm() {
confirmed.value = true;
check.value?.confirm();
}
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
// The text copied last, its button says so for a moment.
const copied = ref('');
let copiedTimer: number | undefined;
async function onCopy(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
return events.log('copy failed, the browser blocked the clipboard');
}
copied.value = text;
clearTimeout(copiedTimer);
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
}
let acceptAnswer:((answer: string) => Promise<void>) | undefined;
function onPick(event: Event) {
file.value = (event.target as HTMLInputElement).files?.[0];
@@ -124,7 +162,8 @@ function formatSize(bytes: number) {
}
async function onCreateOffer() {
const result = await createOffer(file.value!, events);
sent.value = undefined;
const result = await createOffer(file.value!, sendEvents);
offer.value = result.offer;
acceptAnswer = result.accept;
}
@@ -134,15 +173,16 @@ function onAcceptAnswer() {
}
async function onCreateAnswer() {
answer.value = await answerOffer(offerInput.value, events);
answer.value = await answerOffer(offerInput.value, receiveEvents);
}
async function onShare() {
sendCode.value = await sendViaTracker(file.value!, events);
sent.value = undefined;
sendCode.value = await sendViaTracker(file.value!, sendEvents);
}
function onReceive() {
receiveViaTracker(receiveCode.value, events);
receiveViaTracker(receiveCode.value, receiveEvents);
}
</script>
@@ -189,46 +229,83 @@ function onReceive() {
</template>
<template v-else>Drop a file or click to choose</template>
</label>
<section>
<h3>Manual</h3>
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea>
<label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" @click="onAcceptAnswer">Connect</button>
</template>
</section>
<p v-if="sent">
<progress id="send-progress" max="100" :value="percent(sent)"></progress>
{{ percent(sent) }} %
</p>
<section>
<h3>Tracker</h3>
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
<p v-if="sendCode">Code: <output id="send-code">{{ sendCode }}</output></p>
<template v-if="sendCode">
<label for="send-code">Code, give this to the receiver:</label>
<div role="group">
<output id="send-code">{{ sendCode }}</output>
<button id="copy-send-code" @click="onCopy(sendCode)">{{ copied === sendCode ? 'Copied' : 'Copy' }}</button>
</div>
</template>
</section>
<details id="send-manual">
<summary>Manual</summary>
<section>
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" data-copy @click="onCopy(offer)">{{ copied === offer ? 'Copied' : 'Copy' }}</button>
<label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" @click="onAcceptAnswer">Connect</button>
</template>
</section>
</details>
</article>
<article>
<h2>Receive</h2>
<section>
<h3>Manual</h3>
<textarea id="offer-input" v-model="offerInput" placeholder="Paste the offer"></textarea>
<button id="create-answer" @click="onCreateAnswer">Create answer</button>
<template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea>
<div id="incoming">
<template v-if="incoming">
<strong>{{ incoming.name }}</strong>
{{ formatSize(incoming.size) }}
<button v-if="!received" id="download" @click="incoming.download()">Download</button>
</template>
</section>
<template v-else>The sender's file shows up here after the security check</template>
</div>
<p v-if="received">
<progress id="receive-progress" max="100" :value="percent(received)"></progress>
{{ percent(received) }} %
</p>
<section>
<h3>Tracker</h3>
<label for="receive-code">Code from the sender:</label>
<div role="group">
<input id="receive-code" v-model="receiveCode" placeholder="Code" />
<input
id="receive-code"
v-model="receiveCode"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button id="receive" :disabled="!settings.trackers.length" @click="onReceive">Receive</button>
</div>
</section>
<details id="receive-manual">
<summary>Manual</summary>
<section>
<label for="offer-input">Offer from the sender:</label>
<textarea id="offer-input" v-model="offerInput"></textarea>
<button id="create-answer" @click="onCreateAnswer">Create answer</button>
<template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" data-copy @click="onCopy(answer)">{{ copied === answer ? 'Copied' : 'Copy' }}</button>
</template>
</section>
</details>
</article>
<details id="servers">
+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);
+102 -16
View File
@@ -144,7 +144,7 @@ section {
border-top: 1px solid var(--color-border);
}
h3 {
h3, article summary {
font-size: var(--text-sm);
font-weight: 600;
text-transform: uppercase;
@@ -152,12 +152,6 @@ h3 {
color: var(--color-text-muted);
}
small {
font-weight: normal;
text-transform: none;
letter-spacing: normal;
}
label, section p {
font-size: var(--text-sm);
color: var(--color-text-muted);
@@ -223,22 +217,63 @@ button:disabled {
[role='group'] {
display: flex;
gap: var(--space-2);
width: 100%;
}
[role='group'] > input {
border-start-end-radius: 0;
border-end-end-radius: 0;
/* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
#send-code, #receive-code {
color: var(--color-secondary);
font-family: ui-monospace, monospace;
font-size: var(--text-lg);
font-weight: 600;
letter-spacing: 0.15em;
}
[role='group'] > button {
border-start-start-radius: 0;
border-end-start-radius: 0;
#send-code {
flex: 1;
padding: var(--space-2) var(--space-3);
background: var(--color-input);
border: 1px solid var(--color-border);
border-radius: var(--radius);
user-select: all;
}
/* Drop zone, the invisible file input covers the whole label */
/* Copy buttons, secondary next to the value they copy */
label:has(> [type='file']) {
[data-copy] {
padding: var(--space-1) var(--space-3);
background: transparent;
border-color: var(--color-border);
font-size: var(--text-sm);
}
[data-copy]:hover:not(:disabled) {
background: var(--color-border);
}
/* Manual signaling, folded away below the tracker in each card */
article details {
background: none;
border: none;
border-top: 1px solid var(--color-border);
border-radius: 0;
box-shadow: none;
}
article summary {
padding: var(--space-4) 0 0;
}
article details section {
padding-top: var(--space-2);
border-top: none;
}
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
label:has(> [type='file']), #incoming {
position: relative;
display: flex;
flex-direction: column;
@@ -265,6 +300,16 @@ label:has(> [type='file']:focus-visible) {
outline-offset: 2px;
}
#incoming {
border-style: solid;
font-size: var(--text-sm);
color: var(--color-text-muted);
}
#incoming button {
margin-top: var(--space-2);
}
[type='file'] {
position: absolute;
inset: 0;
@@ -272,11 +317,52 @@ label:has(> [type='file']:focus-visible) {
cursor: pointer;
}
label strong {
label strong, #incoming strong {
color: var(--color-text);
overflow-wrap: anywhere;
}
/* Progress, below the file on both sides */
p:has(> progress) {
display: flex;
align-items: center;
gap: var(--space-3);
font-size: var(--text-sm);
font-variant-numeric: tabular-nums;
color: var(--color-text-muted);
}
progress {
flex: 1;
height: 0.5rem;
appearance: none;
border: none;
border-radius: 999px;
background: var(--color-input);
overflow: hidden;
}
progress::-webkit-progress-bar {
background: var(--color-input);
}
progress::-webkit-progress-value {
background: var(--color-primary);
}
progress::-moz-progress-bar {
background: var(--color-primary);
}
progress[value='100']::-webkit-progress-value {
background: var(--color-success);
}
progress[value='100']::-moz-progress-bar {
background: var(--color-success);
}
/* Switch, like Pico's role="switch" */
label:has([role='switch']) {