Own each transfer in a session and harden the protocol
Every operation (share, receive, manual offer or answer) now runs as one session tied to an AbortSignal. Starting another ends it: its connections, tracker sockets and timers close, and it can no longer touch the shared security check, progress or incoming file. Finished, failed and cancelled transfers close their connections, and the sender's tracker sockets close once the download starts. - A malformed or never-connecting tracker offer no longer blocks a share - The receiver validates the file offer and rejects excess bytes and data beyond the flow control window; sw.js checks name and size too - Failures show up in the card instead of disappearing into rejected promises: bad manual codes, unreachable trackers, lost connections - Primary buttons and pink text meet 4.5:1 contrast, the STUN switch shows keyboard focus again, the tracker Copy button matches the others - Split the core into src/core.ts, src/main.ts only mounts the app, which removes the main.ts <-> App.vue import cycle - Bring back the Gitea source link, write the README - Tests reuse one browser per worker with fresh contexts, fail on page errors, check cleanup after transfers, use a local fake STUN server and cover empty files, window boundaries, odd names, malformed messages, session replacement and the production build Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bacc15baaf
commit
2abd0b504d
7 files changed
+1442
-752
No files matched your search
+70
-15
@@ -12,7 +12,7 @@ import {
|
||||
type Events,
|
||||
type Incoming,
|
||||
type ReceiveEvents,
|
||||
} from './main';
|
||||
} from './core';
|
||||
|
||||
const SETTINGS_KEY = 'hellcon:settings';
|
||||
|
||||
@@ -88,10 +88,16 @@ const receiveCode = ref('');
|
||||
const check = ref<Check>();
|
||||
const confirmed = ref(false);
|
||||
const log = ref<string[]>([]);
|
||||
// Of the session, shown in the card of its side.
|
||||
const error = ref('');
|
||||
|
||||
// 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}`),
|
||||
error: (message) => {
|
||||
events.log(message);
|
||||
error.value = message;
|
||||
},
|
||||
check: (result) => {
|
||||
check.value = result;
|
||||
confirmed.value = false;
|
||||
@@ -138,7 +144,40 @@ async function onCopy(text: string) {
|
||||
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
|
||||
}
|
||||
|
||||
let acceptAnswer:((answer: string) => Promise<void>) | undefined;
|
||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||
|
||||
// One session at a time, started by Share, Create offer, Receive or Create answer. Starting one ends
|
||||
// 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'>();
|
||||
|
||||
function begin(on: 'send' | 'receive') {
|
||||
session?.abort();
|
||||
session = new AbortController();
|
||||
side.value = on;
|
||||
error.value = '';
|
||||
check.value = undefined;
|
||||
confirmed.value = false;
|
||||
sent.value = undefined;
|
||||
incoming.value = undefined;
|
||||
received.value = undefined;
|
||||
sendCode.value = '';
|
||||
offer.value = '';
|
||||
answer.value = '';
|
||||
acceptAnswer = undefined;
|
||||
return session.signal;
|
||||
}
|
||||
|
||||
// Resolves with the result of a session step, or undefined if it failed, which is shown, or if a
|
||||
// newer session replaced it meanwhile.
|
||||
async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
|
||||
try {
|
||||
const result = await step;
|
||||
return signal.aborted ? undefined : result;
|
||||
} catch (failure) {
|
||||
if (!signal.aborted) events.error(failure instanceof Error ? failure.message : String(failure));
|
||||
}
|
||||
}
|
||||
|
||||
function onPick(event: Event) {
|
||||
file.value = (event.target as HTMLInputElement).files?.[0];
|
||||
@@ -162,27 +201,34 @@ function formatSize(bytes: number) {
|
||||
}
|
||||
|
||||
async function onCreateOffer() {
|
||||
sent.value = undefined;
|
||||
const result = await createOffer(file.value!, sendEvents);
|
||||
const signal = begin('send');
|
||||
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
|
||||
if (!result) return;
|
||||
offer.value = result.offer;
|
||||
acceptAnswer = result.accept;
|
||||
}
|
||||
|
||||
// Part of the current session, a wrong answer can be corrected.
|
||||
function onAcceptAnswer() {
|
||||
acceptAnswer?.(answerInput.value);
|
||||
error.value = '';
|
||||
if (acceptAnswer) attempt(session!.signal, acceptAnswer(answerInput.value));
|
||||
}
|
||||
|
||||
async function onCreateAnswer() {
|
||||
answer.value = await answerOffer(offerInput.value, receiveEvents);
|
||||
const signal = begin('receive');
|
||||
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
||||
if (result) answer.value = result;
|
||||
}
|
||||
|
||||
async function onShare() {
|
||||
sent.value = undefined;
|
||||
sendCode.value = await sendViaTracker(file.value!, sendEvents);
|
||||
const signal = begin('send');
|
||||
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
||||
if (code) sendCode.value = code;
|
||||
}
|
||||
|
||||
function onReceive() {
|
||||
receiveViaTracker(receiveCode.value, receiveEvents);
|
||||
const signal = begin('receive');
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -230,9 +276,10 @@ function onReceive() {
|
||||
<template v-else>Drop a file or click to choose</template>
|
||||
</label>
|
||||
<p v-if="sent">
|
||||
<progress id="send-progress" max="100" :value="percent(sent)"></progress>
|
||||
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
|
||||
{{ percent(sent) }} %
|
||||
</p>
|
||||
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
@@ -241,7 +288,7 @@ function onReceive() {
|
||||
<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>
|
||||
<button id="copy-send-code" data-copy @click="onCopy(sendCode)">{{ copied === sendCode ? 'Copied' : 'Copy' }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
@@ -256,7 +303,7 @@ function onReceive() {
|
||||
<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>
|
||||
<button id="accept-answer" :disabled="!answerInput.trim()" @click="onAcceptAnswer">Connect</button>
|
||||
</template>
|
||||
</section>
|
||||
</details>
|
||||
@@ -273,9 +320,10 @@ function onReceive() {
|
||||
<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>
|
||||
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress>
|
||||
{{ percent(received) }} %
|
||||
</p>
|
||||
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
@@ -289,7 +337,7 @@ function onReceive() {
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<button id="receive" :disabled="!settings.trackers.length" @click="onReceive">Receive</button>
|
||||
<button id="receive" :disabled="!settings.trackers.length || !receiveCode.trim()" @click="onReceive">Receive</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -298,7 +346,7 @@ function onReceive() {
|
||||
<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>
|
||||
<button id="create-answer" :disabled="!offerInput.trim()" @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>
|
||||
@@ -332,4 +380,11 @@ function onReceive() {
|
||||
<pre id="log">{{ log.join('\n') }}</pre>
|
||||
</details>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||
<img src="/gitea.svg" alt="" width="20" height="20" />
|
||||
Source code
|
||||
</a>
|
||||
</footer>
|
||||
</template>
|
||||
+782
@@ -0,0 +1,782 @@
|
||||
export const DEFAULT_TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
|
||||
|
||||
export const DEFAULT_STUN_SERVERS = [
|
||||
'stun:stun.pagequit.net:3478',
|
||||
'stun:stun.cloudflare.com:3478',
|
||||
'stun:stun.l.google.com:19302',
|
||||
'stun:stun.nextcloud.com:443',
|
||||
];
|
||||
|
||||
// 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 = {
|
||||
stun: true,
|
||||
stunServers: [...DEFAULT_STUN_SERVERS],
|
||||
trackers: [...DEFAULT_TRACKERS],
|
||||
};
|
||||
|
||||
const CHUNK_SIZE = 16 * 1024;
|
||||
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;
|
||||
const ICE_GRACE = 300;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
// 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: its connection never even fails.
|
||||
const CONNECT_TIMEOUT = 30_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 type Check = {
|
||||
local: string;
|
||||
remote: string;
|
||||
// Once the user compared the codes: confirm if they match, else reject.
|
||||
confirm: () => void;
|
||||
reject: () => void;
|
||||
};
|
||||
|
||||
export type Events = {
|
||||
log: (message: string) => void;
|
||||
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||
error: (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;
|
||||
};
|
||||
|
||||
// Every export runs one session until its signal aborts: then it closes the connections and tracker
|
||||
// sockets it opened, starts nothing new and calls no more events. A new session doesn't touch an old one.
|
||||
|
||||
// Closes it once the session ends, right away if it already did.
|
||||
function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
|
||||
if (signal.aborted) resource.close();
|
||||
else signal.addEventListener('abort', () => resource.close(), { once: true });
|
||||
return resource;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
|
||||
) as T;
|
||||
}
|
||||
|
||||
function createPeerConnection(signal: AbortSignal) {
|
||||
// An empty urls list is a syntax error.
|
||||
const stun = settings.stun && settings.stunServers.length;
|
||||
return own(signal, new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] }));
|
||||
}
|
||||
|
||||
// Peers and trackers send JSON objects. Anything else, malformed or not an object, counts as nothing.
|
||||
// Whatever is read from one has to be checked, the any only saves the casts for that.
|
||||
type Message = Record<string, any>;
|
||||
|
||||
function parse(data: unknown): Message | undefined {
|
||||
if (typeof data !== 'string') return;
|
||||
try {
|
||||
const message = JSON.parse(data);
|
||||
return message && typeof message === 'object' ? message : undefined;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored.
|
||||
function decode(code: string, type: 'offer' | 'answer') {
|
||||
try {
|
||||
return { type, sdp: atob(code.replace(/\s/g, '')) };
|
||||
} catch {
|
||||
throw new Error(`not a valid ${type}, copy all of it`);
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
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.
|
||||
async function infoHash(code: string) {
|
||||
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
||||
return String.fromCharCode(...new Uint8Array(digest));
|
||||
}
|
||||
|
||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
action: 'announce',
|
||||
info_hash: hash,
|
||||
peer_id: peerId,
|
||||
numwant: 0,
|
||||
uploaded: 0,
|
||||
downloaded: 0,
|
||||
...params,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
|
||||
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
|
||||
// the same public address: the first one plus a short grace for the other IP family is enough.
|
||||
async function gatherIce(pc: RTCPeerConnection) {
|
||||
if (pc.iceGatheringState === 'complete') return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(resolve, ICE_TIMEOUT);
|
||||
const done = () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', () => {
|
||||
if (pc.iceGatheringState === 'complete') done();
|
||||
});
|
||||
pc.addEventListener('icecandidate', ({ candidate }) => {
|
||||
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const short = (sdp = '') =>
|
||||
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 8).join(' ') ?? '?';
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
|
||||
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
|
||||
// needs both confirmations, a rejected 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 };
|
||||
|
||||
function connected(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
via: string,
|
||||
events: Events,
|
||||
next?: () => void,
|
||||
): Handshake {
|
||||
events.log(`connected via ${via}`);
|
||||
events.log('waiting for the security check');
|
||||
let done = false;
|
||||
const end = (reason: string) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
events.check();
|
||||
pc.close();
|
||||
if (!next) return events.error(reason);
|
||||
events.log(reason);
|
||||
next();
|
||||
};
|
||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
||||
channel.addEventListener('close', () => end('peer left before the transfer'));
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||
});
|
||||
return {
|
||||
checked: new Promise((resolve) =>
|
||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||
),
|
||||
start: () => (done = true),
|
||||
end,
|
||||
};
|
||||
}
|
||||
|
||||
// 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. Any other message, or one out of turn, is ignored. Every way out of the
|
||||
// transfer closes the connection.
|
||||
async function sendFile(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
file: File,
|
||||
events: Events,
|
||||
handshake: Handshake,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
let read = 0;
|
||||
let accepted = false;
|
||||
let offered = false;
|
||||
let sending = false;
|
||||
let stopped = false;
|
||||
// Every event the send loop can wait for calls this.
|
||||
let wake = () => {};
|
||||
const stop = (error?: string) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
if (error) events.error(error);
|
||||
pc.close();
|
||||
wake();
|
||||
};
|
||||
channel.onmessage = ({ data }) => {
|
||||
const message = parse(data);
|
||||
if (!offered) accepted ||= message?.ok === true;
|
||||
else if (!sending) sending = message?.start === true;
|
||||
else if (Number.isSafeInteger(message?.read) && message!.read > read && message!.read <= file.size) {
|
||||
read = message!.read;
|
||||
events.progress(read, file.size);
|
||||
} else if (message?.done === true && !stopped) {
|
||||
events.log('delivered');
|
||||
events.progress(file.size, file.size);
|
||||
stop();
|
||||
} else if (typeof message?.error === 'string') {
|
||||
stop(`receiver stopped: ${message.error.slice(0, 200)}`);
|
||||
}
|
||||
wake();
|
||||
};
|
||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection. Before
|
||||
// sending, connected reports it.
|
||||
const lost = () => stop(sending ? 'connection lost' : undefined);
|
||||
channel.addEventListener('close', lost);
|
||||
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
||||
channel.addEventListener('bufferedamountlow', () => wake());
|
||||
signal.addEventListener('abort', () => stop(), { once: true });
|
||||
// Also false once the channel closes, its close event may still be on the way.
|
||||
const open = () => !stopped && channel.readyState === 'open';
|
||||
|
||||
if (channel.readyState === 'connecting') {
|
||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||
}
|
||||
await handshake.checked;
|
||||
if (!accepted && open()) events.log("waiting for the receiver's security check");
|
||||
while (open() && !accepted) await new Promise<void>((resolve) => (wake = resolve));
|
||||
if (!open()) return;
|
||||
|
||||
channel.send(JSON.stringify({ name: file.name, size: file.size }));
|
||||
offered = true;
|
||||
events.log(`offered ${file.name} (${file.size} bytes)`);
|
||||
events.log('waiting for the receiver to download');
|
||||
while (open() && !sending) await new Promise<void>((resolve) => (wake = resolve));
|
||||
if (!open()) return;
|
||||
|
||||
handshake.start();
|
||||
events.log(`sending ${file.name}`);
|
||||
events.progress(0, file.size);
|
||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
while (open() && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
|
||||
await new Promise<void>((resolve) => (wake = resolve));
|
||||
}
|
||||
// E.g. the file was changed or deleted since it was picked.
|
||||
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer().catch(() => undefined);
|
||||
if (!chunk) return stop(`could not read ${file.name} anymore`);
|
||||
if (!open()) return;
|
||||
channel.send(chunk);
|
||||
}
|
||||
events.log('sent');
|
||||
}
|
||||
|
||||
// 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(
|
||||
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 received = 0;
|
||||
// By the download manager. The rest of received is held in this page and the worker.
|
||||
let read = 0;
|
||||
let confirmed = false;
|
||||
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 | void> = Promise.resolve();
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
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.
|
||||
function release() {
|
||||
clearInterval(keepalive);
|
||||
for (const frame of frames) frame.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;
|
||||
ended = true;
|
||||
post({ error: reason });
|
||||
reply({ error: reason });
|
||||
channel.close();
|
||||
events.error(`download failed: ${reason}`);
|
||||
}
|
||||
signal.addEventListener('abort', () => fail('stopped'), { once: true });
|
||||
|
||||
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.progress(meta!.size, meta!.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
events.log('download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
channel.close();
|
||||
release();
|
||||
};
|
||||
worker.postMessage({ id, ...meta }, [port2]);
|
||||
return worker;
|
||||
}, (error) => fail(String(error)));
|
||||
}
|
||||
|
||||
handshake.checked.then(() => {
|
||||
confirmed = true;
|
||||
reply({ ok: true });
|
||||
events.log('waiting for the sender');
|
||||
});
|
||||
|
||||
function receivedAll() {
|
||||
complete = true;
|
||||
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) receivedAll();
|
||||
}
|
||||
|
||||
channel.binaryType = 'arraybuffer';
|
||||
channel.onmessage = ({ data }) => {
|
||||
if (ended || !confirmed) return;
|
||||
if (typeof data === 'string') {
|
||||
if (meta) return;
|
||||
const { name, size } = parse(data) ?? {};
|
||||
if (typeof name !== 'string' || name.length > MAX_NAME || !Number.isSafeInteger(size) || size < 0) {
|
||||
return handshake.end('the sender offered no valid file');
|
||||
}
|
||||
meta = { name, size };
|
||||
events.log(`offered ${name} (${size} bytes)`);
|
||||
events.incoming({ name, size, download });
|
||||
} else if (downloading && !complete) {
|
||||
received += data.byteLength;
|
||||
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]);
|
||||
if (received === meta!.size) receivedAll();
|
||||
}
|
||||
};
|
||||
// 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. Before the download
|
||||
// started, connected reports it and only the offer goes.
|
||||
function lost() {
|
||||
if (!meta || ended) return;
|
||||
if (!downloading) events.incoming();
|
||||
else if (!complete) fail('connection lost');
|
||||
}
|
||||
channel.addEventListener('close', lost);
|
||||
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
||||
}
|
||||
|
||||
// The manual exchange has nobody else to try: a connection that fails before the data channel opened,
|
||||
// e.g. after a wrong answer or between networks without STUN, ends the session.
|
||||
function failUnconnected(pc: RTCPeerConnection, opened: () => boolean, events: Events) {
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState !== 'failed' || opened()) return;
|
||||
pc.close();
|
||||
events.error('could not connect, check the codes. Between different networks both sides need STUN');
|
||||
});
|
||||
}
|
||||
|
||||
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
|
||||
// The sender offers, the receiver answers, no tracker involved.
|
||||
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const pc = createPeerConnection(signal);
|
||||
const channel = pc.createDataChannel('file');
|
||||
channel.onopen = () =>
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
failUnconnected(pc, () => channel.readyState !== 'connecting', events);
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return {
|
||||
offer: btoa(pc.localDescription!.sdp),
|
||||
// Rejects with a message for the user. After a wrong answer the offer is still good for the right one.
|
||||
accept: async (answer: string) => {
|
||||
const description = decode(answer, 'answer');
|
||||
if (pc.signalingState === 'closed') throw new Error('this offer is used up, create a new one');
|
||||
// Already connecting with an earlier answer.
|
||||
if (pc.signalingState !== 'have-local-offer') return;
|
||||
await pc.setRemoteDescription(description).catch(() => {
|
||||
throw new Error('not a valid answer to this offer, copy all of it');
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function answerOffer(offer: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const description = decode(offer, 'offer');
|
||||
await downloadsReady();
|
||||
const pc = createPeerConnection(signal);
|
||||
let opened = false;
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
// The sender's file channel, anything more is none of ours.
|
||||
if (opened) return;
|
||||
opened = true;
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
};
|
||||
failUnconnected(pc, () => opened, events);
|
||||
await pc.setRemoteDescription(description).catch(() => {
|
||||
pc.close();
|
||||
throw new Error('not a valid offer, copy all of it');
|
||||
});
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return btoa(pc.localDescription!.sdp);
|
||||
}
|
||||
|
||||
const NO_TRACKER = 'no tracker reachable, check the list under Servers and try again';
|
||||
|
||||
// A socket to the tracker at url, closed with the session. Messages arrive parsed, a tracker's failure
|
||||
// reason is only logged. lost runs once it closed without close() being called, e.g. unreachable.
|
||||
function trackerSocket(
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
events: Events,
|
||||
message: (msg: Message) => void,
|
||||
lost: () => void,
|
||||
) {
|
||||
const ws = own(signal, new WebSocket(url));
|
||||
let opened = false;
|
||||
let closed = false;
|
||||
ws.addEventListener('open', () => (opened = true));
|
||||
ws.addEventListener('message', ({ data }) => {
|
||||
const msg = parse(data);
|
||||
if (typeof msg?.['failure reason'] === 'string') events.log(`${url}: ${msg['failure reason']}`);
|
||||
else if (msg) message(msg);
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
events.log(opened ? `lost ${url}` : `${url} unreachable`);
|
||||
lost();
|
||||
});
|
||||
return {
|
||||
ws,
|
||||
alive: () => !closed,
|
||||
close: () => {
|
||||
closed = true;
|
||||
ws.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type Tracker = ReturnType<typeof trackerSocket>;
|
||||
|
||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
||||
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
|
||||
// the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be
|
||||
// answered or never connects. Once the download started the share is used up, the trackers go.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const code = randomCode();
|
||||
const hash = await infoHash(code);
|
||||
const peerId = randomBinary(20);
|
||||
const trackers: Tracker[] = [];
|
||||
let busy = false;
|
||||
let shared = false;
|
||||
// The latest offer that came while busy, answered once that peer is out.
|
||||
let waiting: (() => void) | undefined;
|
||||
|
||||
// Without a tracker no further receiver can find the share.
|
||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||
|
||||
function next() {
|
||||
busy = false;
|
||||
if (signal.aborted) return;
|
||||
if (stranded()) return events.error(NO_TRACKER);
|
||||
events.log('waiting for the next receiver');
|
||||
const offer = waiting;
|
||||
waiting = undefined;
|
||||
offer?.();
|
||||
}
|
||||
|
||||
async function answer(ws: WebSocket, url: string, msg: { offer: { sdp: string }; peer_id: string; offer_id: string }) {
|
||||
busy = true;
|
||||
events.log(`offer via ${url}`);
|
||||
const pc = createPeerConnection(signal);
|
||||
// Until the data channel opens this ends the turn, from then on connected does.
|
||||
let settled = false;
|
||||
const giveUp = (reason: string) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
events.log(reason);
|
||||
pc.close();
|
||||
next();
|
||||
};
|
||||
const timeout = setTimeout(() => giveUp('receiver did not connect'), CONNECT_TIMEOUT);
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
const handshake = connected(pc, channel, url, events, next);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
shared = true;
|
||||
waiting = undefined;
|
||||
for (const tracker of trackers) tracker.close();
|
||||
};
|
||||
sendFile(pc, channel, file, events, { ...handshake, start }, signal);
|
||||
};
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
||||
});
|
||||
try {
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp });
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
} catch (error) {
|
||||
return giveUp(`unusable offer via ${url}: ${error}`);
|
||||
}
|
||||
if (settled) return;
|
||||
announce(ws, hash, peerId, {
|
||||
left: 0,
|
||||
to_peer_id: msg.peer_id,
|
||||
offer_id: msg.offer_id,
|
||||
answer: pc.localDescription,
|
||||
});
|
||||
}
|
||||
|
||||
for (const url of settings.trackers) {
|
||||
const tracker = trackerSocket(
|
||||
url,
|
||||
signal,
|
||||
events,
|
||||
(msg) => {
|
||||
// What a tracker relays from a receiver, anything else is ignored.
|
||||
if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return;
|
||||
if (typeof msg.offer_id !== 'string') return;
|
||||
const offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||
else answer(tracker.ws, url, offer);
|
||||
},
|
||||
() => stranded() && events.error(NO_TRACKER),
|
||||
);
|
||||
tracker.ws.onopen = () => {
|
||||
announce(tracker.ws, hash, peerId, { left: 0, event: 'started' });
|
||||
events.log(`waiting on ${url}`);
|
||||
};
|
||||
trackers.push(tracker);
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
// 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. An answer that can't be used or never connects is replaced right away. Once the
|
||||
// download started, every other offer and tracker socket goes.
|
||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
await downloadsReady();
|
||||
const hash = await infoHash(code.trim());
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
||||
// before that.
|
||||
const offers = new Map<string, { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean }>();
|
||||
let isConnected = false;
|
||||
let started = false;
|
||||
|
||||
const next = () => {
|
||||
isConnected = false;
|
||||
if (signal.aborted) return;
|
||||
events.log('looking again');
|
||||
for (const [url, { pc }] of offers) if (pc.signalingState === 'closed') offer(url);
|
||||
};
|
||||
|
||||
function offer(url: string) {
|
||||
const pc = createPeerConnection(signal);
|
||||
const entry: { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean } = { pc, lost: false };
|
||||
offers.set(url, entry);
|
||||
const channel = pc.createDataChannel('file');
|
||||
const offerId = randomBinary(20);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
// Unless another offer is connected, next replaces this one then.
|
||||
const retry = (reason: string) => {
|
||||
clearTimeout(timeout);
|
||||
if (pc.signalingState === 'closed') return;
|
||||
events.log(reason);
|
||||
pc.close();
|
||||
if (!isConnected && !started && !signal.aborted) offer(url);
|
||||
};
|
||||
channel.onopen = () => {
|
||||
clearTimeout(timeout);
|
||||
if (isConnected || started) return pc.close();
|
||||
isConnected = true;
|
||||
const handshake = connected(pc, channel, url, events, next);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
started = true;
|
||||
for (const other of offers.values()) {
|
||||
other.tracker?.close();
|
||||
if (other.pc !== pc) other.pc.close();
|
||||
}
|
||||
};
|
||||
receiveFile(pc, channel, events, { ...handshake, start }, signal);
|
||||
};
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed' && channel.readyState === 'connecting') retry(`sender via ${url} did not connect`);
|
||||
});
|
||||
|
||||
pc.setLocalDescription()
|
||||
.then(() => gatherIce(pc))
|
||||
.then(() => {
|
||||
if (pc.signalingState === 'closed') return;
|
||||
const tracker = trackerSocket(
|
||||
url,
|
||||
signal,
|
||||
events,
|
||||
(msg) => {
|
||||
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
|
||||
events.log(`answer via ${url}`);
|
||||
// Only one answer per offer, a replacement opens its own socket.
|
||||
tracker.close();
|
||||
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
|
||||
pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() =>
|
||||
retry(`unusable answer via ${url}`),
|
||||
);
|
||||
},
|
||||
() => {
|
||||
entry.lost = true;
|
||||
if (!isConnected && !started && [...offers.values()].every((other) => other.lost)) events.error(NO_TRACKER);
|
||||
},
|
||||
);
|
||||
entry.tracker = tracker;
|
||||
tracker.ws.onopen = () => {
|
||||
announce(tracker.ws, hash, peerId, {
|
||||
left: 1,
|
||||
numwant: 1,
|
||||
event: 'started',
|
||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
||||
});
|
||||
events.log(`looking on ${url}`);
|
||||
};
|
||||
})
|
||||
// Closed in the meantime, nothing to report then.
|
||||
.catch((error) => pc.signalingState === 'closed' || events.error(String(error)));
|
||||
}
|
||||
|
||||
for (const url of settings.trackers) offer(url);
|
||||
}
|
||||
-551
@@ -2,555 +2,4 @@ import { createApp } from 'vue';
|
||||
import App from './App.vue';
|
||||
import './style.css';
|
||||
|
||||
export const DEFAULT_TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
|
||||
|
||||
export const DEFAULT_STUN_SERVERS = [
|
||||
'stun:stun.pagequit.net:3478',
|
||||
'stun:stun.cloudflare.com:3478',
|
||||
'stun:stun.l.google.com:19302',
|
||||
'stun:stun.nextcloud.com:443',
|
||||
];
|
||||
|
||||
// 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 = {
|
||||
stun: true,
|
||||
stunServers: [...DEFAULT_STUN_SERVERS],
|
||||
trackers: [...DEFAULT_TRACKERS],
|
||||
};
|
||||
|
||||
const CHUNK_SIZE = 16 * 1024;
|
||||
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;
|
||||
const ICE_GRACE = 300;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
|
||||
export type Check = {
|
||||
local: string;
|
||||
remote: string;
|
||||
// Once the user compared the codes: confirm if they match, else reject.
|
||||
confirm: () => void;
|
||||
reject: () => void;
|
||||
};
|
||||
|
||||
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() {
|
||||
// An empty urls list is a syntax error.
|
||||
const stun = settings.stun && settings.stunServers.length;
|
||||
return new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] });
|
||||
}
|
||||
|
||||
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() {
|
||||
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.
|
||||
async function infoHash(code: string) {
|
||||
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
||||
return String.fromCharCode(...new Uint8Array(digest));
|
||||
}
|
||||
|
||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
action: 'announce',
|
||||
info_hash: hash,
|
||||
peer_id: peerId,
|
||||
numwant: 0,
|
||||
uploaded: 0,
|
||||
downloaded: 0,
|
||||
...params,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
|
||||
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
|
||||
// the same public address: the first one plus a short grace for the other IP family is enough.
|
||||
async function gatherIce(pc: RTCPeerConnection) {
|
||||
if (pc.iceGatheringState === 'complete') return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(resolve, ICE_TIMEOUT);
|
||||
const done = () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', () => {
|
||||
if (pc.iceGatheringState === 'complete') done();
|
||||
});
|
||||
pc.addEventListener('icecandidate', ({ candidate }) => {
|
||||
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const short = (sdp = '') =>
|
||||
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 8).join(' ') ?? '?';
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
|
||||
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
|
||||
// needs both confirmations, a rejected check or a peer that left closes the connection and calls next:
|
||||
// tracker signaling goes on with another peer. From start on, sendFile and receiveFile handle a loss.
|
||||
type Handshake = { checked: Promise<void>; start: () => void };
|
||||
|
||||
function connected(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
via: string,
|
||||
events: Events,
|
||||
next = () => {},
|
||||
): Handshake {
|
||||
events.log(`connected via ${via}`);
|
||||
events.log('waiting for the security check');
|
||||
let done = false;
|
||||
const end = (reason: string) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
events.log(reason);
|
||||
events.check();
|
||||
pc.close();
|
||||
next();
|
||||
};
|
||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
||||
channel.addEventListener('close', () => end('peer left before the transfer'));
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||
});
|
||||
return {
|
||||
checked: new Promise((resolve) =>
|
||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||
),
|
||||
start: () => (done = true),
|
||||
};
|
||||
}
|
||||
|
||||
// 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,
|
||||
file: File,
|
||||
events: Events,
|
||||
handshake: Handshake,
|
||||
) {
|
||||
if (channel.readyState !== 'open') {
|
||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||
}
|
||||
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.
|
||||
let wake = () => {};
|
||||
const stop = (message?: string) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
if (message) events.log(message);
|
||||
wake();
|
||||
};
|
||||
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;
|
||||
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;
|
||||
}
|
||||
if (message.error) stop(`receiver stopped: ${message.error}`);
|
||||
wake();
|
||||
};
|
||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection. Before
|
||||
// sending, connected reports it.
|
||||
const lost = () => stop(sending ? 'connection lost' : undefined);
|
||||
channel.addEventListener('close', lost);
|
||||
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
||||
channel.addEventListener('bufferedamountlow', () => wake());
|
||||
|
||||
await handshake.checked;
|
||||
if (!accepted && !stopped) events.log("waiting for the receiver's security check");
|
||||
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}`);
|
||||
events.progress(0, file.size);
|
||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
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));
|
||||
}
|
||||
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
if (stopped) return;
|
||||
channel.send(chunk);
|
||||
}
|
||||
events.log('sent');
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// 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(events: Events) {
|
||||
return downloads.catch((error) => {
|
||||
events.log(`downloads unavailable: ${error}`);
|
||||
throw 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.
|
||||
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();
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
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));
|
||||
|
||||
let keepalive: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
// Releases the worker, so a waiting update can take over.
|
||||
function release() {
|
||||
clearInterval(keepalive);
|
||||
for (const frame of frames) frame.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;
|
||||
ended = true;
|
||||
post({ error: reason });
|
||||
reply({ error: reason });
|
||||
events.log(`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') {
|
||||
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');
|
||||
download.hidden = true;
|
||||
download.src = `download/${id}`;
|
||||
document.body.append(download);
|
||||
frames.push(download);
|
||||
return;
|
||||
}
|
||||
if (data === 'finished') {
|
||||
events.log('download complete');
|
||||
events.progress(meta!.size, meta!.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
events.log('download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
release();
|
||||
};
|
||||
worker.postMessage({ id, ...meta }, [port2]);
|
||||
return worker;
|
||||
}, (error) => fail(String(error)));
|
||||
}
|
||||
|
||||
handshake.checked.then(() => {
|
||||
confirmed = true;
|
||||
reply({ ok: true });
|
||||
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);
|
||||
events.log(`offered ${meta!.name} (${meta!.size} bytes)`);
|
||||
events.incoming({ ...meta!, download });
|
||||
} else if (downloading) {
|
||||
received += data.byteLength;
|
||||
post({ chunk: data }, [data]);
|
||||
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. Before the download
|
||||
// started, connected reports it and only the offer goes.
|
||||
function 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());
|
||||
}
|
||||
|
||||
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
|
||||
// The sender offers, the receiver answers, no tracker involved.
|
||||
export async function createOffer(file: File, events: Events) {
|
||||
const pc = createPeerConnection();
|
||||
const channel = pc.createDataChannel('file');
|
||||
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events));
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return {
|
||||
offer: btoa(pc.localDescription!.sdp),
|
||||
accept: (answer: string) => pc.setRemoteDescription({ type: 'answer', sdp: atob(answer.trim()) }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function answerOffer(offer: string, events: ReceiveEvents) {
|
||||
await downloadsReady(events);
|
||||
const pc = createPeerConnection();
|
||||
pc.ondatachannel = ({ channel }) =>
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events));
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
|
||||
return btoa(pc.localDescription!.sdp);
|
||||
}
|
||||
|
||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
||||
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
|
||||
// the code, or got the same one by chance, doesn't end the share.
|
||||
export async function sendViaTracker(file: File, events: Events) {
|
||||
const code = randomCode();
|
||||
const hash = await infoHash(code);
|
||||
const peerId = randomBinary(20);
|
||||
let busy = false;
|
||||
// The latest offer that came while busy, answered once that peer is out.
|
||||
let waiting: (() => void) | undefined;
|
||||
|
||||
async function answer(ws: WebSocket, url: string, msg: { offer: RTCSessionDescriptionInit; peer_id: string; offer_id: string }) {
|
||||
busy = true;
|
||||
events.log(`offer via ${url}`);
|
||||
const pc = createPeerConnection();
|
||||
const next = () => {
|
||||
busy = false;
|
||||
events.log('waiting for the next receiver');
|
||||
const offer = waiting;
|
||||
waiting = undefined;
|
||||
offer?.();
|
||||
};
|
||||
let checking = false;
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
checking = true;
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, url, events, next));
|
||||
};
|
||||
// An offer whose receiver is gone never gets to the check.
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState !== 'failed' || checking) return;
|
||||
pc.close();
|
||||
next();
|
||||
});
|
||||
await pc.setRemoteDescription(msg.offer);
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
announce(ws, hash, peerId, {
|
||||
left: 0,
|
||||
to_peer_id: msg.peer_id,
|
||||
offer_id: msg.offer_id,
|
||||
answer: pc.localDescription,
|
||||
});
|
||||
}
|
||||
|
||||
for (const url of settings.trackers) {
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => {
|
||||
announce(ws, hash, peerId, { left: 0, event: 'started' });
|
||||
events.log(`waiting on ${url}`);
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (!msg.offer) return;
|
||||
if (busy) waiting = () => answer(ws, url, msg);
|
||||
else answer(ws, url, msg);
|
||||
};
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
// 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: ReceiveEvents) {
|
||||
await downloadsReady(events);
|
||||
const hash = await infoHash(code);
|
||||
const peerId = randomBinary(20);
|
||||
const offers = new Map<string, RTCPeerConnection>();
|
||||
let isConnected = false;
|
||||
|
||||
const next = () => {
|
||||
isConnected = false;
|
||||
events.log('looking again');
|
||||
for (const [url, pc] of offers) if (pc.signalingState === 'closed') offer(url);
|
||||
};
|
||||
|
||||
function offer(url: string) {
|
||||
const pc = createPeerConnection();
|
||||
offers.set(url, pc);
|
||||
const channel = pc.createDataChannel('file');
|
||||
const offerId = randomBinary(20);
|
||||
channel.onopen = () => {
|
||||
if (isConnected) return pc.close();
|
||||
isConnected = true;
|
||||
receiveFile(pc, channel, events, connected(pc, channel, url, events, next));
|
||||
};
|
||||
|
||||
pc.setLocalDescription()
|
||||
.then(() => gatherIce(pc))
|
||||
.then(() => {
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => {
|
||||
announce(ws, hash, peerId, {
|
||||
left: 1,
|
||||
numwant: 1,
|
||||
event: 'started',
|
||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
||||
});
|
||||
events.log(`looking on ${url}`);
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.answer && msg.offer_id === offerId) {
|
||||
events.log(`answer via ${url}`);
|
||||
pc.setRemoteDescription(msg.answer);
|
||||
// Only one answer per offer, a replacement opens its own connection.
|
||||
ws.close();
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
for (const url of settings.trackers) offer(url);
|
||||
}
|
||||
|
||||
// Mounted last: App.vue imports the core from this module.
|
||||
createApp(App).mount('#app');
|
||||
+61
-13
@@ -48,7 +48,10 @@ h1, h2, h3, h4, h5, h6 {
|
||||
|
||||
--color-primary: #5865f2;
|
||||
--color-primary-hover: #4752c4;
|
||||
--color-on-primary: #fff;
|
||||
--color-secondary: #eb459e;
|
||||
/* The secondary is too dark for text on the surfaces, this one keeps 4.5:1 */
|
||||
--color-secondary-text: #f278b7;
|
||||
--color-success: #23a559;
|
||||
|
||||
--color-bg: #313338;
|
||||
@@ -82,7 +85,7 @@ body {
|
||||
|
||||
/* Layout */
|
||||
|
||||
header, main {
|
||||
header, main, footer {
|
||||
max-width: 64rem;
|
||||
margin-inline: auto;
|
||||
padding-inline: var(--space-4);
|
||||
@@ -175,6 +178,10 @@ input, textarea {
|
||||
|
||||
input:focus, textarea:focus {
|
||||
border-color: var(--color-secondary);
|
||||
}
|
||||
|
||||
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||
input:not([type='checkbox'], [type='file']):focus-visible, textarea:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -195,7 +202,7 @@ button {
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius);
|
||||
background: var(--color-primary);
|
||||
color: var(--color-text);
|
||||
color: var(--color-on-primary);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition);
|
||||
@@ -223,7 +230,7 @@ button:disabled {
|
||||
|
||||
/* 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);
|
||||
color: var(--color-secondary-text);
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: var(--text-lg);
|
||||
font-weight: 600;
|
||||
@@ -245,6 +252,7 @@ button:disabled {
|
||||
padding: var(--space-1) var(--space-3);
|
||||
background: transparent;
|
||||
border-color: var(--color-border);
|
||||
color: var(--color-text);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
@@ -322,7 +330,16 @@ label strong, #incoming strong {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Progress, below the file on both sides */
|
||||
/* Progress and what went wrong, below the file on both sides */
|
||||
|
||||
article > p[role='alert'] {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
|
||||
article > p[role='alert']::first-letter {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
p:has(> progress) {
|
||||
display: flex;
|
||||
@@ -405,23 +422,23 @@ label:has([role='switch']) {
|
||||
|
||||
/* Security check callout */
|
||||
|
||||
[role='alert'] {
|
||||
aside {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4) var(--space-6);
|
||||
background: color-mix(in srgb, var(--color-secondary) 10%, var(--color-surface));
|
||||
background: color-mix(in srgb, var(--color-secondary) 8%, var(--color-surface));
|
||||
border: 1px solid var(--color-secondary);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
[role='alert'] p {
|
||||
aside p {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
/* Monospaced in a grid, so both codes line up byte by byte */
|
||||
[role='alert'] dl {
|
||||
aside dl {
|
||||
flex: 1 1 auto;
|
||||
display: grid;
|
||||
grid-template-columns: auto auto;
|
||||
@@ -429,31 +446,62 @@ label:has([role='switch']) {
|
||||
column-gap: var(--space-3);
|
||||
}
|
||||
|
||||
[role='alert'] dt {
|
||||
aside dt {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
[role='alert'] div {
|
||||
aside div {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
[role='alert'] button + button {
|
||||
aside button + button {
|
||||
background: transparent;
|
||||
border-color: var(--color-border);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
[role='alert'] button + button:hover {
|
||||
aside button + button:hover {
|
||||
background: var(--color-border);
|
||||
}
|
||||
|
||||
output {
|
||||
color: var(--color-secondary);
|
||||
color: var(--color-secondary-text);
|
||||
font-family: ui-monospace, monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Source link, quiet below everything */
|
||||
|
||||
footer {
|
||||
padding-bottom: var(--space-6);
|
||||
}
|
||||
|
||||
footer a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
footer a:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
footer img {
|
||||
filter: grayscale(1);
|
||||
opacity: 0.6;
|
||||
transition: opacity var(--transition);
|
||||
}
|
||||
|
||||
footer a:hover img {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* Servers */
|
||||
|
||||
#servers > div {
|
||||
|
||||
Reference in new issue
Block a user