Files
HellCon/src/components/TransferPanel.vue
T

546 lines
33 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { asError } from '../lib/validation.ts';
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import DeviceSettings from './DeviceSettings.vue';
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { codeLink, createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.ts';
import { listenForAnswers } from '../lib/invitations.ts';
import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
import type { ConnectionActivity, ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
pc: RTCPeerConnection;
options: IceOptions;
controller: AbortController;
transfer: FileSession | null;
diagnostics: ConnectionDiagnostics;
localHello?: IdentityHello;
remoteHello?: IdentityHello;
identityContext?: IdentityContext;
identity?: IdentityState['identity'];
expected?: string;
// Shared by this session's offer and answer codes.
ref?: string;
// Stops accepting answer links from other tabs.
stopAnswers?: () => void;
timer?: ReturnType<typeof setTimeout>;
}
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection> }>();
const devices = ref<InstanceType<typeof DeviceSettings> | null>(null);
const identityStatus = ref('');
// Offered on the verification step whenever the verified peer would change
// this connection's paired device: 'new' starts ticked, 'replace' does not.
const pairing = ref<'' | 'new' | 'replace'>(''), rememberPeer = ref(false);
const file = ref<File | null>(null);
const selectedFiles = ref<File[]>([]);
const queuedFiles = ref<QueueItem[]>([]);
const sendState = ref<TransferState | null>(null);
const receiveState = ref<TransferState | null>(null);
const outgoing = ref<FileMetadata | null>(null);
const receiveProgress = ref(0);
const lastDirection = ref<'send' | 'receive'>('send');
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; activity: [item: ConnectionActivity]; update: [change: ConnectionUpdate] }>();
const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
const error = ref('');
const copied = ref<'' | 'link' | 'code'>('');
const fps = ref<Fingerprints | null>(null);
const verified = ref(false);
const progress = ref(0);
const incoming = ref<FileMetadata | null>(null);
const downloadUrl = ref('');
const downloadName = ref('');
const connected = ref(false);
const sendSection = ref<HTMLElement | null>(null);
const receiveSection = ref<HTMLElement | null>(null);
const acceptButton = ref<HTMLButtonElement | null>(null);
watch(connected, value => emit('connectedChange', value));
function focusDirection(direction: 'send' | 'receive') {
const section = direction === 'send' ? sendSection.value : receiveSection.value;
section?.focus({ preventScroll: true });
section?.scrollIntoView({ block: 'start', behavior: 'auto' });
}
// Fills an invitation's code without creating the answer, which would reveal
// this device's addresses before the user chose to.
function importCode(code: string) {
if (busy.value || connected.value || props.sending) return;
if (step.value !== 'idle') reset();
inputCode.value = code;
void nextTick(() => acceptButton.value?.focus());
}
defineExpose({ focusDirection, importCode });
const choosing = ref(false);
const dragover = ref(false);
const diagnosticLines = ref<string[]>([]);
let latestDiagnostics: ConnectionDiagnostics | null = null;
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
const defaultStun = import.meta.env.VITE_STUN_URL || '';
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
const managedCredentials = ref<IceOptions | null>(null);
// Links keep this page's own path and query, so any self-hosted location works.
const outputLink = computed(() => outputCode.value ? codeLink(outputCode.value, location.href) : '');
const canShare = typeof navigator.share === 'function' && (navigator.canShare?.({ url: location.href }) ?? true);
// Every size is received the same way: streamed to Downloads where supported, otherwise
// through the native save picker, otherwise buffered in memory (capped) and saved on completion.
const receiveMethod = computed(() => {
if (!incoming.value) return null;
if (supportsStreamingDownload()) return 'download';
if (typeof window.showSaveFilePicker === 'function') return 'disk';
return incoming.value.size <= MEMORY_LIMIT ? 'memory' : null;
});
const savedToDisk = ref(false);
let active: Session | null = null;
let copyTimer: ReturnType<typeof setTimeout> | undefined;
const busy = computed(() => !['idle', 'closed', 'done', 'session-ready'].includes(step.value));
const status = computed(() => ({
'session-ready': 'Connected. Add files to send, or wait for your peer.',
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 the link privately, then paste the answer or open the answer link in this browser.',
'answer-ready': 'Send the answer link 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': 'Accept or decline this file.',
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (savedToDisk.value ? 'File saved to disk.' : 'File handed to your browser. Check Downloads for the final save result.'),
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 = ''; downloadName.value = '';
}
function saveDownload() {
const link = document.createElement('a');
link.href = downloadUrl.value; link.download = downloadName.value;
document.body.append(link); link.click(); link.remove();
}
function dispose() {
const old = active;
if (old) {
if (outgoing.value && sendState.value && !['done', 'closed'].includes(sendState.value)) { remember('send', outgoing.value, 'interrupted'); sendState.value = 'closed'; }
if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) { remember('receive', incoming.value, 'interrupted'); receiveState.value = 'closed'; }
}
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
managedCredentials.value = null; settings.value.allowTurn = false;
if (!old) return;
clearTimeout(old.timer);
old.stopAnswers?.();
// Start the snapshot before aborting/closing anything; close the peer after
// stats resolve (bounded to 300 ms), so failure evidence remains available.
void old.diagnostics.finish(() => old.pc.close());
old.controller.abort();
old.transfer?.close();
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
}
function reset(keepNetwork = false) {
const allowTurn = settings.value.allowTurn;
dispose(); revokeDownload(); clearTimeout(copyTimer);
if (keepNetwork) settings.value.allowTurn = allowTurn;
latestDiagnostics = null; diagnosticLines.value = [];
managedCredentials.value = null;
if (!keepNetwork) settings.value.allowTurn = false;
inputCode.value = outputCode.value = error.value = '';
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
fps.value = incoming.value = null;
verified.value = choosing.value = false; copied.value = '';
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
sendState.value = receiveState.value = null; outgoing.value = null;
}
function fail(session: Session, err: unknown) {
if (active !== session) return;
session.diagnostics.record('session failed');
dispose();
managedCredentials.value = null;
fps.value = incoming.value = null;
outputCode.value = ''; verified.value = false;
settings.value.allowTurn = false;
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
error.value = asError(err).message; step.value = 'closed';
}
function pickFiles(event: Event) {
const list = event.target instanceof HTMLInputElement ? event.target.files
: event instanceof DragEvent ? event.dataTransfer?.files : null;
const files = Array.from(list || []);
if (!files.length) return;
try {
if (files.length > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
for (const item of files) validateMetadata({ name: item.name, size: item.size, mime: item.type || '' });
if (active?.transfer) active.transfer.add(files);
else {
if (active) throw new Error('Finish connecting before adding more files.');
selectedFiles.value = files; file.value = files[0]!;
}
error.value = '';
} catch (err) { error.value = asError(err).message; }
if (event.target instanceof HTMLInputElement) event.target.value = '';
}
function removeQueued(id: number) { active?.transfer?.remove(id); }
function remember(direction: ConnectionActivity['direction'], meta: FileMetadata, result: ConnectionActivity['result']) {
emit('activity', { id: crypto.randomUUID(), time: Date.now(), direction, name: meta.name, size: meta.size, result });
}
function disconnect() {
dispose(); step.value = 'closed';
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
incoming.value = null; outputCode.value = ''; fps.value = null; verified.value = false;
}
function declineFile() { if (!choosing.value) active?.transfer?.decline(); }
function attach(session: Session, channel: RTCDataChannel) {
if (active !== session) { channel.close(); return; }
if (session.transfer || channel.label !== 'hellcon-v3' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
}
session.transfer = new FileSession(channel, !!props.sending, {
onReady: () => { if (active === session) {
connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer);
// Ready implies both fresh proofs verified, so the key may now be saved.
if (session.identityContext && session.remoteHello) {
const key = session.remoteHello.key;
if (session.expected === key) identityStatus.value = 'Paired device authenticated for this connection.';
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; }
else identityStatus.value = 'Device proof checked. This device was not remembered.';
}
} },
onQueue: items => { if (active === session) queuedFiles.value = items; },
onState: (direction, state, meta) => {
if (active !== session) return;
step.value = state; lastDirection.value = direction;
session.diagnostics.record(`transfer ${direction} ${state}`);
if (state === 'done') session.diagnostics.record('transfer done');
if (direction === 'send') { sendState.value = state; outgoing.value = meta; if (state === 'waiting-accept') progress.value = 0; }
else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; savedToDisk.value = false; } }
},
onProgress: (direction, bytes, size) => {
if (active !== session) return;
const percent = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100));
if (direction === 'send') progress.value = percent; else receiveProgress.value = percent;
},
onComplete: (direction, { blob, meta }) => {
if (active !== session) return;
if (direction === 'send') progress.value = 100; else receiveProgress.value = 100;
remember(direction, meta, 'complete');
void session.diagnostics.capture();
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
},
onDecline: (direction, meta) => {
if (active !== session) return;
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
remember(direction, meta, 'declined');
if (lastDirection.value === direction) {
const other = direction === 'send' ? receiveState.value : sendState.value;
step.value = other && other !== 'done' ? other : 'session-ready';
lastDirection.value = direction === 'send' ? 'receive' : 'send';
}
},
onClose: () => { if (active === session) disconnect(); },
onError: err => fail(session, err),
});
if (props.sending) { session.transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
configureIdentity(session);
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(),
};
// Fetch managed credentials before gathering, while retaining normal cancellation.
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
let diagnostics: ConnectionDiagnostics;
diagnostics = new ConnectionDiagnostics(pc, lines => {
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
});
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
const session: Session = { pc, options, controller: new AbortController(), transfer: null, diagnostics };
active = session; emit('sessionChange', true);
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)) {
const unfinished = [sendState.value, receiveState.value].some(state => state && state !== 'done' && state !== 'closed');
if (connected.value && !unfinished) disconnect();
else fail(session, new Error(connected.value
? 'Connection lost. Unfinished files were cancelled. Exchange fresh codes to reconnect.'
: 'Could not establish the peer connection. Retry with fresh codes. If it fails again, copy Connection diagnostics from both devices.'));
}
};
return session;
}
async function createCode() {
const pasted = inputCode.value;
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
let session: Session | undefined;
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();
// Re-read saved trust for each connection; another tab may have forgotten
// the paired peer or replaced the local identity since this page loaded.
if (props.connection.rememberDevice) {
const trust = await props.loadTrust();
const identity = trust.rememberDevice ? await devices.value?.refreshIdentity() : null;
if (active !== session) return;
if (trust.rememberDevice) session.expected = trust.peerKey;
if (identity) { session.identity = identity; session.localHello = hello(identity); }
}
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
if (active !== session) return;
session.pc.setConfiguration(iceConfiguration(configured));
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
const offer = props.sending ? null : await decodeCode(pasted, { type: 'offer', allowTurn: session.options.allowTurn });
if (active !== session) return;
session.ref = offer ? offer.ref : createRef(); session.remoteHello = offer?.identity;
const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
const sdp = offer ? await createAnswer(session.pc, offer.sdp, options) : await createOffer(session.pc, options);
if (active !== session) return;
const code = await encodeCode({ type: props.sending ? 'offer' : 'answer', ref: session.ref, sdp, identity: session.localHello });
if (active !== session) return;
outputCode.value = code;
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
session.diagnostics.descriptions();
void session.diagnostics.capture();
if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); }
step.value = props.sending ? 'offer-ready' : 'answer-ready';
// An answer link opened in another tab of this browser arrives here.
if (props.sending) session.stopAnswers = listenForAnswers(session.ref, answer => {
if (active !== session || step.value !== 'offer-ready') return false;
inputCode.value = answer; void useAnswer();
return true;
});
} catch (err) {
if (session) fail(session, err);
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
}
}
async function useAnswer() {
const session = active;
if (!session || step.value !== 'offer-ready') return;
error.value = '';
step.value = 'verification';
try {
const answer = await decodeCode(inputCode.value, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
if (active !== session) return;
session.remoteHello = answer.identity;
await acceptAnswer(session.pc, answer.sdp, session.options);
if (active !== session) return;
session.diagnostics.record('answer applied');
session.diagnostics.descriptions();
void session.diagnostics.capture();
fps.value = getFingerprints(session.pc, session.options);
offerPairing(session);
configureIdentity(session);
} 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 = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
step.value = 'offer-ready';
} else fail(session, err);
}
}
function offerPairing(session: Session) {
const key = session.localHello && session.remoteHello?.key;
pairing.value = !key || key === session.expected ? '' : session.expected ? 'replace' : 'new';
rememberPeer.value = pairing.value === 'new';
}
function configureIdentity(session: Session) {
if (!fps.value || !session.transfer || session.identityContext) return;
if (!session.identity || !session.localHello || !session.remoteHello) {
if (session.expected) identityStatus.value = 'A device identity is missing. Compare both fingerprints manually; the paired device is not being used.';
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must use their device identity to remember each other. Compare fingerprints manually for this connection.';
return;
}
const initiator = !!props.sending;
const context: IdentityContext = {
offer: initiator ? session.localHello : session.remoteHello,
answer: initiator ? session.remoteHello : session.localHello,
offerFingerprint: initiator ? fps.value.local : fps.value.remote,
answerFingerprint: initiator ? fps.value.remote : fps.value.local,
};
session.identityContext = context;
const identity = session.identity;
session.transfer.authenticate({ sign: () => signIdentity(identity, context, initiator), verify: proof => verifyIdentity(proof, context, !initiator) });
if (session.expected === session.remoteHello.key) {
identityStatus.value = 'Checking the paired device’s fresh proof…'; verify();
} else {
identityStatus.value = session.expected ? 'Device identity differs from the paired device. Compare both fingerprints manually before continuing. The paired device is only replaced if you choose to.' : 'New device. Compare both fingerprints manually before remembering it.';
}
}
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() {
const session = active, destination = receiveMethod.value;
if (!session?.transfer || !incoming.value || !destination || choosing.value || receiveState.value !== 'choose-storage') return;
choosing.value = true; error.value = '';
let writable: FileDestination | undefined;
try {
if (destination === 'download') {
writable = await createDownloadDestination(incoming.value, session.controller.signal);
if (active !== session) { await writable.abort(); return; }
} else if (destination === 'disk') {
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
if (active !== session) return;
writable = await handle.createWritable();
if (active !== session) { await writable.abort(); return; }
}
revokeDownload();
savedToDisk.value = destination === 'disk';
session.diagnostics.record(`storage ${destination}`);
session.transfer.accept(writable);
} catch (err) {
if (writable) await writable.abort().catch(() => {});
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
} finally { if (active === session) choosing.value = false; }
}
async function copy(kind: 'link' | 'code') {
const session = active;
try {
await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value);
if (active !== session) return;
copied.value = kind; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = ''; }, 1500);
} catch { if (active === session) error.value = `Clipboard unavailable. Select and copy the ${kind} manually.`; }
}
async function share() {
const session = active;
try { await navigator.share({ url: outputLink.value }); }
catch (err) { if (active === session && asError(err).name !== 'AbortError') error.value = 'Sharing failed. Copy the link instead.'; }
}
function stateLabel(state: TransferState | null) {
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Awaiting acceptance', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
}
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`;
const index = Math.min(5, Math.floor(Math.log(bytes) / Math.log(1024)));
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) event.target.select();
}
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script>
<template>
<div class="panel">
<section v-if="sending || connected" ref="sendSection" class="transfer-section" tabindex="-1" aria-labelledby="send-heading">
<h2 id="send-heading" class="step">Send files</h2>
<label class="step" for="file-input">{{ connected ? 'Add files to send' : 'Choose files' }}</label>
<div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)">
<p>Choose or drop files.</p>
<input id="file-input" type="file" multiple @change="pickFiles" />
</div>
<p v-if="!connected && selectedFiles.length" class="status">{{ selectedFiles.length }} file(s) selected</p>
<ul v-if="!connected && selectedFiles.length"><li v-for="(item, index) in selectedFiles" :key="index">{{ item.name }} — {{ formatBytes(item.size) }}</li></ul>
<ul v-if="queuedFiles.length" aria-label="Files waiting to send"><li v-for="item in queuedFiles" :key="item.id">{{ item.file.name }} — {{ formatBytes(item.file.size) }} <button @click="removeQueued(item.id)" :aria-label="'Remove ' + item.file.name">Remove</button></li></ul>
<p v-if="outgoing" class="status">Sending: {{ outgoing.name }} — {{ stateLabel(sendState) }} ({{ progress }}%)</p>
<div v-if="outgoing" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Sending progress"><div :style="{ width: progress + '%' }"></div></div>
</section>
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :disabled="busy || connected" @update="emit('update', $event)" />
<details class="config-details">
<summary>Network settings</summary>
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
</details>
<p v-if="!connected" class="status">Exchange links or codes privately. They contain your IP address and connection details.</p>
<template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s link or code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template>
<button ref="acceptButton" class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode">
<label class="step" for="output-link">{{ sending ? 'Send this link to the receiver' : 'Send this answer link back to the sender' }}</label>
<input id="output-link" class="stun-input" :value="outputLink" readonly @focus="selectCode" />
<div class="share-actions">
<button v-if="canShare" class="primary" @click="share">Share link</button>
<button @click="copy('link')">{{ copied === 'link' ? 'Copied!' : 'Copy link' }}</button>
</div>
<p class="status">A link is as sensitive as a code: send it privately. It may stay in browser history and only works while this page stays open, for up to 5 minutes.</p>
<details class="code-details">
<summary>Show code instead</summary>
<div class="code-entry">
<label class="step" for="output-code">{{ sending ? 'Connection code' : 'Answer code' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy('code')">{{ copied === 'code' ? 'Copied!' : 'Copy code' }}</button>
</div>
</details>
</template>
<template v-if="sending && outputCode">
<div class="code-entry">
<label class="step" for="answer-input">Paste the receiver’s answer or answer link</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</div>
</template>
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
<div v-if="fps" class="fingerprint">
<h2 class="step">Verify both full SHA-256 fingerprints</h2>
<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>
<label v-if="pairing"><input v-model="rememberPeer" type="checkbox" :disabled="verified" /> {{ pairing === 'new' ? `Remember this device for ${connection.name}` : `Replace the paired device of ${connection.name}` }}</label>
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
</div>
<section v-if="connected || incoming || downloadUrl" ref="receiveSection" class="transfer-section" tabindex="-1" aria-labelledby="receive-heading">
<h2 id="receive-heading" class="step">Receive files</h2>
<p v-if="!incoming" class="status">Waiting for your peer to send a file. You can send files yourself using Send above.</p>
<div v-if="incoming && receiveState === 'choose-storage'" class="incoming">
<button :disabled="choosing" @click="declineFile">Decline file</button>
<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="receiveMethod" class="primary" :disabled="choosing" @click="acceptFile">Accept file</button>
<p v-if="receiveMethod === 'disk'" class="status">Your browser asks where to save this file. Keep this page open until the transfer finishes.</p>
<p v-else-if="receiveMethod" class="status">Your browser downloads this file. Allow the download and keep this page open until the transfer finishes.</p>
<p v-else class="error">This browser cannot receive files over 64 MiB. Use a browser with streaming-download or file-system saving support, or send a smaller file.</p>
</div>
<p v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</p>
<div v-if="incoming" class="progress" role="progressbar" :aria-valuenow="receiveProgress" aria-valuemin="0" aria-valuemax="100" aria-label="Receiving progress"><div :style="{ width: receiveProgress + '%' }"></div></div>
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save again</a></div>
</section>
<p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<details v-if="diagnosticLines.length">
<summary>Connection diagnostics</summary>
<p class="status">Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.</p>
<label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label>
<textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" />
</details>
<p v-if="!connected && step === 'done'" class="status">Connection ended. Exchange fresh codes to send more files.</p>
<p v-if="connected" class="status">Connection verified. Either person can add files. Keep both tabs open.</p>
<div v-if="step !== 'idle'" class="session-actions">
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
<button @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
</div>
<p class="status">Before connecting, Send/Receive chooses who starts. Once connected, use either button to jump between sending and receiving without disconnecting. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div>
</template>