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:
1 parent
d198332c92
commit
752d0cf3af
16 files changed
+1352
-603
No files matched your search
@@ -0,0 +1,259 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
||||
|
||||
const props = defineProps({ sending: Boolean });
|
||||
const file = ref(null);
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref(null);
|
||||
const downloadUrl = ref('');
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const settings = ref({ stunChoice: 'google', customStun: '', allowTurn: false, turnUrl: '', username: '', credential: '' });
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
let active = null;
|
||||
let copyTimer;
|
||||
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
|
||||
const status = computed(() => ({
|
||||
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
|
||||
gathering: 'Gathering connection info (up to 30 seconds)…',
|
||||
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
|
||||
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
|
||||
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.',
|
||||
'waiting-accept': 'Waiting for the receiver to accept the file…',
|
||||
'choose-storage': 'Choose how to receive this file.',
|
||||
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
|
||||
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
|
||||
done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : 'File saved to disk.'),
|
||||
closed: props.sending
|
||||
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
|
||||
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
|
||||
}[step.value] || ''));
|
||||
|
||||
function revokeDownload() {
|
||||
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
|
||||
downloadUrl.value = '';
|
||||
}
|
||||
function dispose() {
|
||||
const old = active;
|
||||
active = null;
|
||||
if (!old) return;
|
||||
clearTimeout(old.timer);
|
||||
old.controller.abort();
|
||||
old.transfer?.close();
|
||||
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
|
||||
old.pc.close();
|
||||
}
|
||||
function reset(keepNetwork = false) {
|
||||
dispose(); revokeDownload(); clearTimeout(copyTimer);
|
||||
if (!keepNetwork) settings.value.allowTurn = false;
|
||||
inputCode.value = outputCode.value = error.value = '';
|
||||
fps.value = incoming.value = null;
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; step.value = 'idle';
|
||||
}
|
||||
function fail(session, err) {
|
||||
if (active !== session) return;
|
||||
dispose(); revokeDownload();
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
settings.value.allowTurn = false;
|
||||
error.value = err.message || 'Connection failed.'; step.value = 'closed';
|
||||
}
|
||||
function pickFiles(event) {
|
||||
const selected = event.target?.files?.[0] ?? event.dataTransfer?.files?.[0];
|
||||
if (!selected) return;
|
||||
reset();
|
||||
if (selected.size > FILE_LIMIT) { file.value = null; error.value = 'The maximum file size is 64 GiB.'; return; }
|
||||
file.value = selected;
|
||||
}
|
||||
function attach(session, channel) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
}
|
||||
session.transfer = new Transfer(channel, {
|
||||
file: props.sending ? session.file : null,
|
||||
onState: state => { if (active === session) step.value = state; },
|
||||
onMeta: meta => { if (active === session) incoming.value = meta; },
|
||||
onProgress: (bytes, size) => { if (active === session) progress.value = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100)); },
|
||||
onComplete: ({ blob }) => {
|
||||
if (active !== session) return;
|
||||
progress.value = 100;
|
||||
settings.value.allowTurn = false;
|
||||
if (blob) downloadUrl.value = URL.createObjectURL(blob);
|
||||
// The receiver leaves the channel open until its completion ACK reaches the sender.
|
||||
if (props.sending) dispose();
|
||||
else {
|
||||
clearTimeout(session.timer);
|
||||
session.timer = setTimeout(() => { if (active === session) dispose(); }, 10000);
|
||||
}
|
||||
},
|
||||
onError: err => fail(session, err),
|
||||
});
|
||||
if (verified.value) session.transfer.verify();
|
||||
}
|
||||
function start() {
|
||||
const chosen = settings.value;
|
||||
const options = {
|
||||
...chosen,
|
||||
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
||||
turnUrl: chosen.turnUrl.trim(),
|
||||
};
|
||||
const pc = createPeerConnection(options);
|
||||
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
active = session;
|
||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||
pc.ondatachannel = event => attach(session, event.channel);
|
||||
pc.onconnectionstatechange = () => {
|
||||
if (active !== session) return;
|
||||
if (['failed', 'closed'].includes(pc.connectionState)) {
|
||||
if (step.value === 'done') dispose();
|
||||
else fail(session, new Error('Connection failed. Direct connections may be blocked; TURN is available only if both people opt in.'));
|
||||
}
|
||||
};
|
||||
return session;
|
||||
}
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session;
|
||||
try {
|
||||
if (props.sending) {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||
}
|
||||
session = start();
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
|
||||
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
||||
if (active !== session) return;
|
||||
outputCode.value = code;
|
||||
if (!props.sending) fps.value = getFingerprints(session.pc, options);
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = err.message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
const session = active;
|
||||
if (!session || step.value !== 'offer-ready') return;
|
||||
error.value = '';
|
||||
step.value = 'verification';
|
||||
try {
|
||||
await acceptAnswerCode(session.pc, inputCode.value, session.options);
|
||||
if (active !== session) return;
|
||||
fps.value = getFingerprints(session.pc, session.options);
|
||||
} catch (err) {
|
||||
if (active !== session) return;
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${err.message || 'Invalid answer.'} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
}
|
||||
function verify() {
|
||||
if (!active || !fps.value || verified.value) return;
|
||||
verified.value = true; step.value = 'verification';
|
||||
// Gathering/handshake timeout ends; Transfer manages verification and transfer deadlines.
|
||||
const session = active;
|
||||
clearTimeout(session.timer);
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(toDisk) {
|
||||
const session = active;
|
||||
if (!session?.transfer || choosing.value || step.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable;
|
||||
try {
|
||||
if (toDisk) {
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
}
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
if (active === session && err.name !== 'AbortError') error.value = err.message || 'Could not open the destination file.';
|
||||
} finally { if (active === session) choosing.value = false; }
|
||||
}
|
||||
async function copy() {
|
||||
const session = active;
|
||||
try {
|
||||
await navigator.clipboard.writeText(outputCode.value);
|
||||
if (active !== session) return;
|
||||
copied.value = true; clearTimeout(copyTimer);
|
||||
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
|
||||
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
|
||||
}
|
||||
function formatBytes(bytes) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(3, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB'][index]}`;
|
||||
}
|
||||
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="panel">
|
||||
<template v-if="sending">
|
||||
<label class="step" for="file-input">Choose one file (up to 64 GiB)</label>
|
||||
<div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)">
|
||||
<p>Drop a file here or choose one below. Choosing a new file cancels the current connection.</p>
|
||||
<input id="file-input" type="file" @change="pickFiles" />
|
||||
</div>
|
||||
<p v-if="file" class="file-chip"><span>{{ file.name }}</span><span>{{ formatBytes(file.size) }}</span></p>
|
||||
</template>
|
||||
<NetworkSettings v-model="settings" :disabled="busy" />
|
||||
<p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</p>
|
||||
<template v-if="!sending">
|
||||
<label class="step" for="offer-input">Paste the sender’s connection code</label>
|
||||
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" />
|
||||
</template>
|
||||
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
|
||||
<template v-if="outputCode">
|
||||
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="$event.target.select()" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
</template>
|
||||
<template v-if="sending && outputCode">
|
||||
<label class="step" for="answer-input">Paste the receiver’s answer</label>
|
||||
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="step !== 'offer-ready'" />
|
||||
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
|
||||
</template>
|
||||
<div v-if="fps" class="fingerprint">
|
||||
<label class="step">Verify both full SHA-256 fingerprints</label>
|
||||
<div class="fp-row"><span>Your fingerprint</span><code>{{ fps.local }}</code></div>
|
||||
<div class="fp-row"><span>Their fingerprint</span><code>{{ fps.remote }}</code></div>
|
||||
<p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p>
|
||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Fingerprints confirmed' : 'Both fingerprints match — confirm' }}</button>
|
||||
</div>
|
||||
<div v-if="incoming && step === 'choose-storage'" class="incoming">
|
||||
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
|
||||
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
|
||||
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile(true)">Choose destination & receive to disk</button>
|
||||
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile(false)">Receive in memory (up to 64 MiB)</button>
|
||||
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
|
||||
</div>
|
||||
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
|
||||
</div>
|
||||
</template>
|
||||
Reference in new issue
Block a user