fix: harden WebRTC transfers for v0.0.1

Require mutual fingerprint confirmation before sharing metadata or files.
Validate incoming messages, bound buffering, and confirm receipt before
reporting success. Add direct-to-disk saving and explicit TURN opt-in.

Fix reset and retry handling, clean up cancelled connections, and preserve
completed Firefox downloads when the sender disconnects.

Update dependencies, clarify security assumptions, and add protocol and
cross-browser regression tests. Set version 0.0.1 and document the release
in CHANGELOG.md, linked from the README.

BREAKING CHANGE: both peers must use signaling and transfer protocol v2;
older connection codes are no longer accepted.
This commit is contained in:
Schluffe committed 2026-10-09 12:11:14 +02:00
1 parent d198332c92
commit 752d0cf3af
16 files changed
+1352 -603

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.js';
export const MEMORY_LIMIT = 64 * 1024 * 1024;
export const FILE_LIMIT = 64 * 1024 * 1024 * 1024;
const CONTROL_LIMIT = 2048;
const WINDOW = MAX_BUFFERED;
export function validateMetadata(meta) {
if (!meta || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
!Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
throw new Error('Invalid file metadata or file exceeds the 64 GiB limit.');
}
return { name: meta.name, size: meta.size, mime: meta.mime };
}
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
export class Transfer {
constructor(dc, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 } = {}) {
Object.assign(this, { dc, file, onState, onMeta, onProgress, onComplete, onError, timeout });
this.state = 'verification';
this.verified = false;
this.peerReady = false;
this.readySent = false;
this.closed = false;
this.received = this.sent = this.acked = this.queued = this.messages = 0;
this.chunks = [];
this.queue = Promise.resolve();
this.controller = new AbortController();
dc.binaryType = 'arraybuffer';
dc.onopen = () => this.guard(() => this.ready());
dc.onmessage = e => this.enqueue(e.data);
const transportEnded = message => {
// Firefox can report an SCTP error when the sender closes its peer
// connection after receiving our completion ACK. The saved file remains
// valid; a transport shutdown must not revoke a completed download.
if (this.state === 'done') this.close();
else this.fail(new Error(message));
};
dc.onclose = () => transportEnded('Connection closed before receipt was confirmed.');
dc.onerror = () => transportEnded('Data channel failed.');
this.touch(5 * 60 * 1000);
}
setState(state) { this.state = state; this.onState(state); }
touch(ms = this.timeout) {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
}
guard(fn) { try { fn(); } catch (err) { this.fail(err); } }
control(type, data = {}) {
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
const text = JSON.stringify({ v: 2, type, ...data });
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
this.dc.send(text);
}
verify() {
if (this.closed || this.verified) return;
this.verified = true;
this.guard(() => this.ready());
}
ready() {
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
if (!this.readySent) { this.control('ready'); this.readySent = true; }
if (this.file && this.peerReady && this.state === 'verification') {
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
this.setState('waiting-accept');
this.control('meta', this.meta);
this.touch(5 * 60 * 1000);
}
}
enqueue(data) {
if (this.closed) return;
const binary = data instanceof ArrayBuffer;
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
if (size > (binary ? CHUNK_SIZE : CONTROL_LIMIT) || this.queued + size > WINDOW * 2 || this.messages >= 128) {
this.fail(new Error('Peer exceeded message or buffering limits.')); return;
}
this.queued += size; this.messages++;
this.queue = this.queue.then(async () => {
if (!this.closed) await this.message(data);
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
}
async message(data) {
if (data instanceof ArrayBuffer) {
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.meta.size) throw new Error('Unexpected or excess file data.');
// Bound per-chunk overhead as well as payload bytes: millions of tiny
// ArrayBuffers would otherwise defeat the in-memory size limit.
if (data.byteLength !== Math.min(CHUNK_SIZE, this.meta.size - this.received)) throw new Error('Invalid file chunk size.');
if (this.writable) await this.writable.write(data);
else this.chunks.push(data);
if (this.closed) return;
this.received += data.byteLength;
this.control('ack', { bytes: this.received });
this.onProgress(this.received, this.meta.size);
this.touch();
return;
}
const msg = JSON.parse(data);
if (!msg || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
this.peerReady = true; this.ready(); return;
}
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
if (msg.type === 'meta' && !this.file && this.state === 'verification') {
this.meta = validateMetadata(msg);
this.setState('choose-storage'); this.onMeta(this.meta); this.touch(5 * 60 * 1000); return;
}
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
this.setState('sending'); this.touch();
void this.sendFile().catch(err => this.fail(err)); return;
}
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
if (!Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
}
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
if (this.received !== this.meta.size) throw new Error('Incomplete file.');
this.setState('saving');
if (this.writable) await this.writable.close();
if (this.closed) return;
// Treat downloads as opaque files, regardless of the sender's MIME claim.
const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' });
this.chunks = [];
this.control('complete', { bytes: this.received });
this.setState('done'); clearTimeout(this.timer);
this.onComplete({ blob, meta: this.meta }); return;
}
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.meta }); this.close(); return;
}
throw new Error('Unexpected transfer message.');
}
accept(writable = null) {
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
if (!writable && this.meta.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
this.writable = writable;
this.setState('receiving'); this.touch();
this.guard(() => this.control('accept'));
}
async sendFile() {
for (let offset = 0; offset < this.file.size; offset += CHUNK_SIZE) {
if (this.sent - this.acked >= WINDOW) await new Promise(resolve => { this.wake = resolve; });
this.wake = null;
if (this.closed) return;
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
const buffer = await this.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
if (this.closed) return;
this.sent += buffer.byteLength;
this.dc.send(buffer);
}
if (this.closed) return;
this.setState('awaiting-receipt'); this.control('end'); this.touch();
}
fail(err) {
if (this.closed) return;
this.close(); this.setState('closed'); this.onError(err);
}
close() {
if (this.closed) return;
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
this.chunks = [];
if (this.writable && this.state !== 'done') Promise.resolve().then(() => this.writable.abort()).catch(() => {});
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close();
}
}
+119 -73
View File
@@ -1,98 +1,144 @@
// P2P with manual signaling: no server, no third party.
// Peers exchange SDP blobs by copy/paste. ICE gathering runs to completion
// so the full connection info fits in a single copyable string.
// Chunking / buffering for the data channel.
export const CHUNK_SIZE = 16 * 1024; // 16 KiB per message
export const MAX_BUFFERED = 1024 * 1024; // backpressure limit (bytes)
// Built-in public STUN providers. STUN is a stateless, unencrypted UDP
// lookup of your public IP — the server never sees connection or file data.
// Manual signaling. Codes are encoded connection details, not encrypted secrets.
export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024;
export const MAX_SIGNAL_LENGTH = 64 * 1024;
export const STUN_PROVIDERS = [
{ id: 'google', label: 'Google', url: 'stun:stun.l.google.com:19302' },
{ id: 'cloudflare', label: 'Cloudflare', url: 'stun:stun.cloudflare.com:3478' },
{ id: 'none', label: 'None (same-network / VPN peers only)', url: null },
{ id: 'none', label: 'None (direct connections only)', url: null },
];
// stunUrl: a URL from STUN_PROVIDERS, or a user-supplied "stun:host:port"
// string, or null for host candidates only.
export function createPeerConnection(stunUrl = null) {
return new RTCPeerConnection({
iceServers: stunUrl ? [{ urls: stunUrl }] : [],
});
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' } = {}) {
const iceServers = [];
if (stunUrl) {
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
iceServers.push({ urls: stunUrl });
}
// Credentials and URLs are ignored unless this user explicitly opts in.
if (allowTurn) {
if (!/^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(turnUrl) || !username || !credential) {
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
}
iceServers.push({ urls: turnUrl, username, credential });
}
return { iceServers };
}
function waitForIceComplete(pc) {
if (pc.iceGatheringState === 'complete') return Promise.resolve();
export function createPeerConnection(options) {
return new RTCPeerConnection(iceConfiguration(options));
}
export function waitForIceComplete(pc, { signal, timeout = 30000 } = {}) {
return new Promise((resolve, reject) => {
const onChange = () => {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', onChange);
resolve();
}
let timer;
const cleanup = () => {
clearTimeout(timer);
pc.removeEventListener('icegatheringstatechange', check);
pc.removeEventListener('connectionstatechange', check);
signal?.removeEventListener('abort', aborted);
};
pc.addEventListener('icegatheringstatechange', onChange);
setTimeout(() => {
pc.removeEventListener('icegatheringstatechange', onChange);
// Resolve anyway — partial candidate lists often still connect fine.
resolve();
}, 5000);
const finish = (err) => { cleanup(); err ? reject(err) : resolve(); };
const aborted = () => finish(new Error('Connection cancelled.'));
const check = () => {
if (signal?.aborted || pc.connectionState === 'closed') aborted();
else if (pc.iceGatheringState === 'complete') finish();
};
pc.addEventListener('icegatheringstatechange', check);
pc.addEventListener('connectionstatechange', check);
signal?.addEventListener('abort', aborted, { once: true });
timer = setTimeout(() => finish(new Error('Connection gathering timed out. Check the server settings and try again.')), timeout);
check();
});
}
// Sender side: create an offer and return it as a copyable code.
export async function createOfferCode(pc) {
await pc.setLocalDescription(await pc.createOffer());
await waitForIceComplete(pc);
return encodeSignal(pc.localDescription.sdp);
export function validateDescription(sdp, { allowTurn = false } = {}) {
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
throw new Error('Invalid connection description.');
}
const lines = sdp.split(/\r?\n/);
const media = lines.filter(line => line.startsWith('m='));
if (media.length !== 1 || !/^m=application \d+ (?:UDP\/DTLS\/SCTP|DTLS\/SCTP) (?:webrtc-datachannel|\d+)$/.test(media[0])) {
throw new Error('Only a single file data channel is supported.');
}
// Deliberately reject ambiguous fingerprints rather than guessing SDP scope.
const fingerprints = lines.filter(line => line.startsWith('a=fingerprint:'));
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
throw new Error('A single full SHA-256 fingerprint is required.');
}
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
}
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
}
// Receiver side: accept an offer code, return the answer code to send back.
export async function createAnswerCode(pc, offerText) {
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(offerText) });
await pc.setLocalDescription(await pc.createAnswer());
await waitForIceComplete(pc);
return encodeSignal(pc.localDescription.sdp);
}
// Sender side: apply the answer code the receiver sent back.
export function acceptAnswerCode(pc, answerText) {
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(answerText) });
}
// Anti-MITM check: extracts the DTLS certificate fingerprints from both
// descriptions and shortens them for human comparison.
// Rule: my "local" must equal the peer's "remote" (and vice versa).
// If both match, nobody interposed on the code exchange.
export function getFingerprints(pc) {
const extract = (sdp) => {
const m = sdp?.match(/a=fingerprint:(?:sha-256|sha-384|sha-512) ([0-9A-Fa-f:]+)/);
return m ? m[1].toUpperCase() : null;
};
// The fingerprint is already a certificate hash — its first 5 bytes
// (40 bits) are plenty for two humans to read to each other.
const shorten = (fp) => (fp ? fp.split(':').slice(0, 5).join(' ') : '—');
export function getFingerprints(pc, options) {
return {
local: shorten(extract(pc.localDescription?.sdp)),
remote: shorten(extract(pc.remoteDescription?.sdp)),
local: validateDescription(pc.localDescription?.sdp, options),
remote: validateDescription(pc.remoteDescription?.sdp, options),
};
}
// SDP is ASCII plus CRLFs, so plain base64 is safe and compact enough (~2-4 KB).
export function encodeSignal(sdp) {
return btoa(sdp).replace(/=+$/, '');
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, '');
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
return code;
}
export function decodeSignal(text) {
const clean = String(text).trim().replace(/\s+/g, '');
const padded = clean + '='.repeat((4 - (clean.length % 4)) % 4);
return atob(padded);
export function decodeSignal(text, options) {
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
try {
const clean = text.trim().replace(/\s+/g, '');
const data = JSON.parse(atob(clean));
if (data?.version !== 2) throw new Error('Both people need the current HellCon version.');
validateDescription(data.sdp, options);
return data.sdp;
} catch (err) {
if (err instanceof SyntaxError || err.name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
throw err;
}
}
// Waits until the channel's send buffer drains below MAX_BUFFERED.
export function waitForBufferDrain(dc) {
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
return new Promise((resolve) => {
dc.addEventListener('bufferedamountlow', resolve, { once: true });
export async function createOfferCode(pc, options = {}) {
await pc.setLocalDescription(await pc.createOffer());
await waitForIceComplete(pc, options);
validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp);
}
export async function createAnswerCode(pc, text, options = {}) {
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) });
await pc.setLocalDescription(await pc.createAnswer());
await waitForIceComplete(pc, options);
validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp);
}
export function acceptAnswerCode(pc, text, options) {
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
}
export function waitForBufferDrain(dc, { signal, timeout = 60000 } = {}) {
return new Promise((resolve, reject) => {
let timer;
const cleanup = () => {
clearTimeout(timer);
dc.removeEventListener('bufferedamountlow', check);
dc.removeEventListener('close', check);
dc.removeEventListener('error', failed);
signal?.removeEventListener('abort', failed);
};
const finish = err => { cleanup(); err ? reject(err) : resolve(); };
const failed = () => finish(new Error('Transfer interrupted.'));
const check = () => {
if (signal?.aborted || dc.readyState !== 'open') failed();
else if (dc.bufferedAmount <= MAX_BUFFERED / 2) finish();
};
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
dc.addEventListener('bufferedamountlow', check);
dc.addEventListener('close', check);
dc.addEventListener('error', failed);
signal?.addEventListener('abort', failed, { once: true });
timer = setTimeout(() => finish(new Error('Transfer stalled.')), timeout);
check();
});
}