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

+25
View File
@@ -0,0 +1,25 @@
<script setup>
import { STUN_PROVIDERS } from '../lib/webrtc.js';
const settings = defineModel({ required: true });
defineProps({ disabled: Boolean });
</script>
<template>
<fieldset :disabled="disabled" class="network-settings">
<legend>Connection settings</legend>
<label for="stun-provider">STUN provider</label>
<select id="stun-provider" v-model="settings.stunChoice" class="stun-select">
<option v-for="provider in STUN_PROVIDERS" :key="provider.id" :value="provider.id">{{ provider.label }}</option>
<option value="custom">Custom…</option>
</select>
<input v-if="settings.stunChoice === 'custom'" v-model="settings.customStun" class="stun-input" aria-label="Custom STUN address" placeholder="stun:your.domain:3478" />
<p class="status">STUN helps discover a reachable address. Its operator sees your public IP and request timing, but does not carry your file. Direct connections may fail on restrictive networks.</p>
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
<template v-if="settings.allowTurn">
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
</template>
</fieldset>
</template>
+2 -188
View File
@@ -1,190 +1,4 @@
<script setup>
import { ref, computed, onBeforeUnmount } from 'vue';
import {
createPeerConnection,
createAnswerCode,
getFingerprints,
STUN_PROVIDERS,
} from '../lib/webrtc';
const STATUS = {
idle: 'Paste the sender\'s connection code to start.',
'creating-answer': 'Gathering connection info…',
'answer-ready': 'Send the code below back to the sender.',
connecting: 'Waiting for the P2P connection…',
receiving: 'Receiving…',
done: 'File received!',
closed: 'Connection closed.',
};
const step = ref('idle');
const offerInput = ref('');
const answerCode = ref('');
const progress = ref(0);
const error = ref('');
const copied = ref(false);
const fps = ref(null);
const stunChoice = ref('google');
const customStun = ref('');
const fileName = ref('');
const fileSize = ref(0);
const downloadUrl = ref('');
let pc = null;
const statusText = computed(() => STATUS[step.value] ?? '');
const resolvedStun = computed(() => {
if (stunChoice.value === 'custom') {
const raw = customStun.value.trim();
return raw ? raw : null;
}
return STUN_PROVIDERS.find((p) => p.id === stunChoice.value)?.url ?? null;
});
onBeforeUnmount(() => {
pc?.close();
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
});
async function acceptOffer() {
error.value = '';
if (downloadUrl.value) {
URL.revokeObjectURL(downloadUrl.value);
downloadUrl.value = '';
}
progress.value = 0;
fps.value = null;
pc?.close();
pc = createPeerConnection(resolvedStun.value);
pc.ondatachannel = (e) => setupReceiver(e.channel);
pc.onconnectionstatechange = () => {
if (['disconnected', 'failed', 'closed'].includes(pc.connectionState)) {
if (step.value !== 'done') step.value = 'closed';
}
};
step.value = 'creating-answer';
try {
answerCode.value = await createAnswerCode(pc, offerInput.value);
fps.value = getFingerprints(pc);
step.value = 'answer-ready';
} catch {
step.value = 'idle';
error.value = 'Invalid offer code — paste the full code from the sender.';
}
}
function setupReceiver(dc) {
dc.binaryType = 'arraybuffer';
let meta = null;
let chunks = [];
let received = 0;
dc.onopen = () => {
if (step.value === 'answer-ready') step.value = 'connecting';
};
dc.onmessage = (e) => {
if (typeof e.data === 'string') {
// Metadata frame
meta = JSON.parse(e.data);
fileName.value = meta.name;
fileSize.value = meta.size;
received = 0;
if (meta.size === 0) finish(meta, []);
else step.value = 'receiving';
return;
}
chunks.push(e.data);
received += e.data.byteLength;
if (meta) {
progress.value = Math.min(100, Math.floor((received / meta.size) * 100));
if (received >= meta.size) finish(meta, chunks);
}
};
}
function finish(meta, chunks) {
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
const blob = new Blob(chunks, { type: meta.type || 'application/octet-stream' });
downloadUrl.value = URL.createObjectURL(blob);
progress.value = 100;
step.value = 'done';
}
async function copy(text) {
await navigator.clipboard.writeText(text);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
}
import TransferPanel from './TransferPanel.vue';
</script>
<template>
<div class="panel">
<label class="step">1 — Choose a STUN provider</label>
<select v-model="stunChoice" class="stun-select">
<option v-for="p in STUN_PROVIDERS" :key="p.id" :value="p.id">
{{ p.label }}
</option>
<option value="custom">Custom…</option>
</select>
<input
v-if="stunChoice === 'custom'"
v-model="customStun"
class="stun-input"
type="text"
placeholder="stun:your.domain:3478"
/>
<p class="status stun-hint">
STUN is only needed for peers on different networks — a stateless UDP
lookup of your public IP; it never sees the connection or the file.
Same-network or VPN peers work with "None".
</p>
<label class="step">2 — Paste the sender's connection code</label>
<textarea
v-model="offerInput"
placeholder="Paste the code from the sender…"
/>
<button class="primary" :disabled="!offerInput.trim()" @click="acceptOffer">
Accept & create answer
</button>
<template v-if="answerCode">
<label class="step">3 — Send this answer code back to the sender</label>
<textarea :value="answerCode" readonly @focus="$event.target.select()" />
<button @click="copy(answerCode)">{{ copied ? 'Copied!' : 'Copy code' }}</button>
</template>
<div class="progress" v-if="step === 'receiving' || step === 'done'">
<div :style="{ width: progress + '%' }"></div>
</div>
<div v-if="fps" class="fingerprint">
<label class="step">Security check</label>
<div class="fp-row">
<span>Your code</span>
<code>{{ fps.local }}</code>
</div>
<div class="fp-row">
<span>Their code</span>
<code>{{ fps.remote }}</code>
</div>
<p class="status">
To rule out an intercepted exchange, compare with your peer over a
channel you trust: your "Your code" must equal their "Their code",
and vice versa.
</p>
</div>
<p class="status">{{ statusText }}</p>
<p class="error" v-if="error">{{ error }}</p>
<div v-if="downloadUrl" class="file-chip">
<span>{{ fileName }}</span>
<a class="download" :href="downloadUrl" :download="fileName">Save file</a>
</div>
</div>
</template>
<template><TransferPanel /></template>
+2 -246
View File
@@ -1,248 +1,4 @@
<script setup>
import { ref, computed } from 'vue';
import {
createPeerConnection,
createOfferCode,
acceptAnswerCode,
getFingerprints,
STUN_PROVIDERS,
CHUNK_SIZE,
MAX_BUFFERED,
waitForBufferDrain,
} from '../lib/webrtc';
const STATUS = {
idle: 'Pick a file to start.',
'creating-offer': 'Gathering connection info…',
'offer-ready': 'Send the code below to the receiver (any chat works).',
connecting: 'Answer accepted — waiting for the P2P connection…',
sending: 'Transferring…',
done: 'Transfer complete!',
closed: 'Connection closed.',
};
const file = ref(null);
const step = ref('idle');
const offerCode = ref('');
const answerInput = ref('');
const progress = ref(0);
const error = ref('');
const copied = ref(false);
const dragover = ref(false);
const fps = ref(null);
const stunChoice = ref('google');
const customStun = ref('');
let pc = null;
let dc = null;
const statusText = computed(() => STATUS[step.value] ?? '');
const resolvedStun = computed(() => {
if (stunChoice.value === 'custom') {
const raw = customStun.value.trim();
return raw ? raw : null;
}
return STUN_PROVIDERS.find((p) => p.id === stunChoice.value)?.url ?? null;
});
function reset() {
pc?.close();
pc = null;
dc = null;
offerCode.value = '';
answerInput.value = '';
progress.value = 0;
error.value = '';
copied.value = false;
fps.value = null;
step.value = 'idle';
}
function pickFiles(e) {
const f = e.target?.files?.[0] ?? e.dataTransfer?.files?.[0];
if (f) {
reset();
file.value = f;
}
}
async function makeOffer() {
if (!file.value) return;
error.value = '';
step.value = 'creating-offer';
pc = createPeerConnection(resolvedStun.value);
pc.onconnectionstatechange = () => {
if (pc && ['disconnected', 'failed', 'closed'].includes(pc.connectionState)) {
step.value = 'closed';
}
};
dc = pc.createDataChannel('file');
dc.binaryType = 'arraybuffer';
dc.onopen = () => sendFile();
dc.onclose = () => {
if (step.value === 'sending' && progress.value < 100) step.value = 'closed';
};
try {
offerCode.value = await createOfferCode(pc);
step.value = 'offer-ready';
} catch (err) {
error.value = String(err);
step.value = 'idle';
}
}
async function useAnswer() {
if (!pc) return;
error.value = '';
try {
await acceptAnswerCode(pc, answerInput.value);
fps.value = getFingerprints(pc);
step.value = 'connecting';
} catch {
error.value = 'Invalid answer code — paste the full code from the receiver.';
}
}
async function sendFile() {
const f = file.value;
if (!dc || !f) return;
step.value = 'sending';
progress.value = 0;
// First frame: metadata as JSON. Everything after is raw bytes.
dc.send(JSON.stringify({ name: f.name, size: f.size, type: f.type }));
let sent = 0;
try {
for (let offset = 0; offset < f.size; offset += CHUNK_SIZE) {
if (dc.readyState !== 'open') break;
if (dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(dc);
const buf = await f.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
dc.send(buf);
sent += buf.byteLength;
progress.value = Math.floor((sent / Math.max(f.size, 1)) * 100);
}
if (dc.readyState === 'open') {
progress.value = 100;
step.value = 'done';
}
} catch (err) {
error.value = String(err);
step.value = 'closed';
}
}
async function copy(text) {
await navigator.clipboard.writeText(text);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
}
function formatBytes(n) {
if (n < 1024) return n + ' B';
const u = ['KiB', 'MiB', 'GiB'];
let v = n;
let i = -1;
do {
v /= 1024;
i++;
} while (v >= 1024 && i < u.length - 1);
return v.toFixed(1) + ' ' + u[i];
}
import TransferPanel from './TransferPanel.vue';
</script>
<template>
<div class="panel">
<label class="step">1 — Choose a file</label>
<div
class="dropzone"
:class="{ dragover }"
@dragover.prevent="dragover = true"
@dragleave="dragover = false"
@drop.prevent="dragover = false; pickFiles($event)"
@click="$refs.input.click()"
>
<span v-if="!file">Drop a file here or click to browse</span>
<div v-else class="file-chip" @click.stop>
<span>{{ file.name }}</span>
<span class="status">{{ formatBytes(file.size) }}</span>
</div>
<input
ref="input"
type="file"
style="display: none"
@change="pickFiles"
/>
</div>
<template v-if="file">
<label class="step">2 — Choose a STUN provider</label>
<select v-model="stunChoice" class="stun-select">
<option v-for="p in STUN_PROVIDERS" :key="p.id" :value="p.id">
{{ p.label }}
</option>
<option value="custom">Custom…</option>
</select>
<input
v-if="stunChoice === 'custom'"
v-model="customStun"
class="stun-input"
type="text"
placeholder="stun:your.domain:3478"
/>
<p class="status stun-hint">
STUN is only needed for peers on different networks — a stateless UDP
lookup of your public IP; it never sees the connection or the file.
Same-network or VPN peers work with "None".
</p>
<label class="step">3 — Create your connection code</label>
<button class="primary" :disabled="step !== 'idle'" @click="makeOffer">
Create code
</button>
<template v-if="offerCode">
<textarea :value="offerCode" readonly @focus="$event.target.select()" />
<button @click="copy(offerCode)">{{ copied ? 'Copied!' : 'Copy code' }}</button>
</template>
<template v-if="offerCode">
<label class="step">4 — Paste the receiver's answer code</label>
<textarea
v-model="answerInput"
placeholder="Paste the code the receiver sends back…"
/>
<button class="primary" :disabled="!answerInput.trim()" @click="useAnswer">
Connect
</button>
</template>
<div class="progress" v-if="step === 'sending' || step === 'done'">
<div :style="{ width: progress + '%' }"></div>
</div>
<div v-if="fps" class="fingerprint">
<label class="step">Security check</label>
<div class="fp-row">
<span>Your code</span>
<code>{{ fps.local }}</code>
</div>
<div class="fp-row">
<span>Their code</span>
<code>{{ fps.remote }}</code>
</div>
<p class="status">
To rule out an intercepted exchange, compare with your peer over a
channel you trust: your "Your code" must equal their "Their code",
and vice versa.
</p>
</div>
<p class="status">{{ statusText }}</p>
<p class="error" v-if="error">{{ error }}</p>
</template>
</div>
</template>
<template><TransferPanel sending /></template>
+259
View File
@@ -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>