WIP improve UX [snapshot task 2]

This commit is contained in:
Schluffe committed 2026-10-16 15:39:31 +02:00
1 parent 3ae47dde8e
commit cd66321ea6
13 files changed
+703 -87

No files matched your search

+5 -6
View File
@@ -1,9 +1,9 @@
<script setup lang="ts">
import { ref } from 'vue';
import SendPanel from './components/SendPanel.vue';
import ReceivePanel from './components/ReceivePanel.vue';
import TransferPanel from './components/TransferPanel.vue';
const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false);
const isLocal = location.protocol === 'file:';
const canDownloadApp = import.meta.env.PROD && !isLocal;
</script>
@@ -21,12 +21,11 @@ const canDownloadApp = import.meta.env.PROD && !isLocal;
<p v-if="canDownloadApp || isLocal" class="status">For large files in the downloaded local version, use desktop Chrome on the receiving machine and choose “Choose destination &amp; receive to disk”.</p>
<div class="tabs" role="group" aria-label="Transfer mode">
<button :class="{ active: mode === 'send' }" :aria-pressed="mode === 'send'" @click="mode = 'send'">Send</button>
<button :class="{ active: mode === 'receive' }" :aria-pressed="mode === 'receive'" @click="mode = 'receive'">Receive</button>
<button :disabled="sessionActive" :class="{ active: mode === 'send' }" :aria-pressed="mode === 'send'" @click="mode = 'send'">Send</button>
<button :disabled="sessionActive" :class="{ active: mode === 'receive' }" :aria-pressed="mode === 'receive'" @click="mode = 'receive'">Receive</button>
</div>
<SendPanel v-if="mode === 'send'" />
<ReceivePanel v-else />
<TransferPanel :key="mode" :sending="mode === 'send'" @session-change="sessionActive = $event" />
</main>
<footer>
+119 -49
View File
@@ -5,23 +5,32 @@ import type { FileMetadata, TransferState, FileDestination } from '../lib/transf
import { computed, onBeforeUnmount, ref } from 'vue';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.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';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
pc: RTCPeerConnection;
options: IceOptions;
file: File | null;
controller: AbortController;
transfer: Transfer | null;
transfer: FileSession | null;
diagnostics: ConnectionDiagnostics;
timer?: ReturnType<typeof setTimeout>;
}
const props = defineProps<{ sending?: boolean }>();
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 history = ref<string[]>([]);
const emit = defineEmits<{ sessionChange: [active: boolean] }>();
const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
@@ -32,6 +41,9 @@ 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 choosing = ref(false);
const dragover = ref(false);
const diagnosticLines = ref<string[]>([]);
@@ -45,8 +57,9 @@ const canStreamDownload = supportsStreamingDownload();
const streamedDownload = ref(false);
let active: Session | null = null;
let copyTimer: ReturnType<typeof setTimeout> | undefined;
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
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 your code through an authenticated channel, then paste the answer.',
@@ -56,7 +69,7 @@ const status = computed(() => ({
'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.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'),
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : '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.',
@@ -64,11 +77,12 @@ const status = computed(() => ({
function revokeDownload() {
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
downloadUrl.value = '';
downloadUrl.value = ''; downloadName.value = '';
}
function dispose() {
const old = active;
active = null;
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
managedCredentials.value = null; settings.value.allowTurn = false;
if (!old) return;
clearTimeout(old.timer);
// Start the snapshot before aborting/closing anything; close the peer after
@@ -79,58 +93,98 @@ function dispose() {
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 = '';
fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false;
progress.value = 0; step.value = 'idle'; streamedDownload.value = false;
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
sendState.value = receiveState.value = null; outgoing.value = null; history.value = [];
}
function fail(session: Session, err: unknown) {
if (active !== session) return;
session.diagnostics.record('session failed');
dispose(); revokeDownload();
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 selected = event.target instanceof HTMLInputElement ? event.target.files?.[0]
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined;
if (!selected) return;
reset();
if (!Number.isSafeInteger(selected.size) || selected.size < 0) { file.value = null; error.value = 'This file’s size cannot be represented accurately.'; return; }
file.value = selected;
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(message: string) { history.value = [...history.value.slice(-49), message]; }
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-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
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 Transfer(channel, {
file: props.sending ? session.file : null,
onState: state => { if (active === session) { step.value = state; session.diagnostics.record(`transfer ${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 }) => {
session.transfer = new FileSession(channel, !!props.sending, {
onReady: () => { if (active === session) { connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer); } },
onQueue: items => { if (active === session) queuedFiles.value = items; },
onState: (direction, state, meta) => {
if (active !== session) return;
progress.value = 100;
managedCredentials.value = null;
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);
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; streamedDownload.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 === 'send' ? 'Sent' : 'Received'}: ${meta.name}`);
void session.diagnostics.capture();
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; }
},
onDecline: (direction, meta) => {
if (active !== session) return;
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
remember(`Declined: ${meta.name}`);
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; }
if (verified.value) session.transfer.verify();
}
function start() {
@@ -147,15 +201,16 @@ function start() {
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
});
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null, diagnostics };
active = session;
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)) {
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.'));
const unfinished = [sendState.value, receiveState.value].some(state => state && state !== 'done' && state !== 'closed');
if (connected.value && !unfinished) disconnect();
else fail(session, new Error('Connection failed. Unfinished files were cancelled. Direct connections may be blocked; TURN is available only if both people opt in.'));
}
};
return session;
@@ -175,7 +230,7 @@ async function createCode() {
session.pc.setConfiguration(iceConfiguration(configured));
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
if (active !== session) return;
outputCode.value = code;
@@ -221,7 +276,7 @@ function verify() {
}
async function acceptFile(destination: 'disk' | 'memory' | 'download') {
const session = active;
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
if (!session?.transfer || !incoming.value || choosing.value || receiveState.value !== 'choose-storage') return;
choosing.value = true; error.value = '';
let writable: FileDestination | undefined;
try {
@@ -235,6 +290,7 @@ async function acceptFile(destination: 'disk' | 'memory' | 'download') {
writable = await handle.createWritable();
if (active !== session) { await writable.abort(); return; }
}
revokeDownload();
streamedDownload.value = destination === 'download';
session.diagnostics.record(`storage ${destination}`);
session.transfer.accept(writable);
@@ -252,6 +308,9 @@ async function copy() {
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
}
function stateLabel(state: TransferState | null) {
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Choose where to save', 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)));
@@ -265,21 +324,24 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<template>
<div class="panel">
<template v-if="sending">
<label class="step" for="file-input">Choose one file</label>
<template v-if="sending || connected">
<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>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" />
<p>Choose or drop files. Each direction sends one file at a time; both people can send on this connection.</p>
<input id="file-input" type="file" multiple @change="pickFiles" />
</div>
<p v-if="file" class="file-chip"><span>{{ file.name }}</span><span>{{ formatBytes(file.size) }}</span></p>
<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>
</template>
<NetworkSettings v-model="settings" :disabled="busy" :managed-credentials="managedCredentials" />
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
<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>
<button 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-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
@@ -297,7 +359,8 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<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">
<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="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download ({{ formatBytes(incoming.size) }})</button>
@@ -306,7 +369,9 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" 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 v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</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>
<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>
<p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<details v-if="diagnosticLines.length">
@@ -315,8 +380,13 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<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>
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save file</a></div>
<p v-if="downloadUrl && receiveState === 'choose-storage'" class="status">Save the previous file before accepting this one. Accepting replaces its memory download.</p>
<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>
<ul v-if="history.length" aria-label="Recent file results"><li v-for="(entry, index) in history" :key="index">{{ entry }}</li></ul>
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
<p class="status">Switching HellCon’s Send/Receive mode cancels the connection. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
<p class="status">Send/Receive chooses who starts the connection. Disconnect before changing this setup choice. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div>
</template>
+166
View File
@@ -0,0 +1,166 @@
import { Transfer, validateMetadata, type TransferChannel, type FileDestination, type FileMetadata, type TransferState, type TransferResult } from './transfer.ts';
import { CHUNK_SIZE } from './webrtc.ts';
import { asError, isRecord } from './validation.ts';
export const QUEUE_LIMIT = 32;
export interface QueueItem { id: number; file: File }
export interface SessionCallbacks {
onReady(): void;
onQueue(items: QueueItem[]): void;
onState(direction: 'send' | 'receive', state: TransferState, meta: FileMetadata): void;
onProgress(direction: 'send' | 'receive', bytes: number, size: number): void;
onComplete(direction: 'send' | 'receive', result: TransferResult): void;
onDecline(direction: 'send' | 'receive', meta: FileMetadata): void;
onError(error: Error): void;
onClose(): void;
}
interface Active { id: number; transfer: Transfer; meta: FileMetadata }
// One sequential queue per direction. At most two active transfers share the
// transport, with separate bounded Transfer windows and unique session IDs.
export class FileSession {
private pending: QueueItem[] = [];
private outgoing: Active | null = null;
private incoming: Active | null = null;
private nextId: number;
private lastRemoteId = 0;
private verified = false;
private peerReady = false;
private readySent = false;
private started = false;
private closed = false;
private timer: ReturnType<typeof setTimeout>;
private readonly dc: TransferChannel;
private readonly initiator: boolean;
private readonly callbacks: SessionCallbacks;
constructor(dc: TransferChannel, initiator: boolean, callbacks: SessionCallbacks) {
this.dc = dc; this.initiator = initiator; this.callbacks = callbacks;
this.nextId = initiator ? 1 : 2;
dc.binaryType = 'arraybuffer';
dc.onopen = () => this.ready();
dc.onmessage = event => { try { this.message(event.data); } catch (error) { this.fail(error); } };
dc.onclose = () => this.outgoing || this.incoming ? this.fail(new Error('Connection closed. Unfinished files were cancelled.')) : this.close();
dc.onerror = () => this.fail(new Error('Connection failed. Exchange fresh codes.'));
this.timer = setTimeout(() => this.fail(new Error('Verification timed out.')), 5 * 60 * 1000);
}
private control(data: object) { this.dc.send(JSON.stringify({ v: 3, ...data })); }
verify() { this.verified = true; this.ready(); }
private ready() {
if (this.closed || !this.verified || this.dc.readyState !== 'open') return;
try {
if (!this.readySent) { this.readySent = true; this.control({ type: 'ready' }); }
if (this.peerReady && !this.started) {
this.started = true; clearTimeout(this.timer); this.callbacks.onReady(); this.pump();
}
} catch (error) { this.fail(error); }
}
add(files: File[]) {
if (this.closed) throw new Error('Connection ended.');
if (files.length + this.pending.length + (this.outgoing ? 1 : 0) > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
for (const file of files) validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
if (this.nextId + files.length * 2 > 0xffffffff) throw new Error('Start a new session.');
for (const file of files) { this.pending.push({ id: this.nextId, file }); this.nextId += 2; }
this.callbacks.onQueue([...this.pending]); this.pump();
}
remove(id: number) { this.pending = this.pending.filter(item => item.id !== id); this.callbacks.onQueue([...this.pending]); }
accept(destination: FileDestination | null = null) {
if (!this.incoming) throw new Error('File is no longer available.');
this.incoming.transfer.accept(destination);
}
decline() {
const item = this.incoming;
if (!item || item.transfer.state !== 'choose-storage') return;
this.control({ type: 'decline', id: item.id });
this.incoming = null; item.transfer.close(); this.callbacks.onDecline('receive', item.meta);
}
private pump() {
if (!this.started || this.closed || this.outgoing || !this.pending.length) return;
const item = this.pending.shift()!;
this.callbacks.onQueue([...this.pending]);
const meta = validateMetadata({ name: item.file.name, size: item.file.size, mime: item.file.type || '' });
this.control({ type: 'start', id: item.id });
this.outgoing = this.create(item.id, item.file, meta);
this.outgoing.transfer.verify();
}
private create(id: number, file: File | null, meta: FileMetadata): Active {
const raw = this.dc;
const channel = new EventTarget() as TransferChannel;
channel.binaryType = 'arraybuffer'; channel.bufferedAmountLowThreshold = 0;
channel.onopen = channel.onmessage = channel.onclose = channel.onerror = null;
let ended = false;
Object.defineProperties(channel, {
readyState: { get: () => ended ? 'closed' : raw.readyState },
bufferedAmount: { get: () => raw.bufferedAmount },
bufferedAmountLowThreshold: { get: () => raw.bufferedAmountLowThreshold, set: value => { raw.bufferedAmountLowThreshold = value; } },
});
const drain = () => channel.dispatchEvent(new Event('bufferedamountlow'));
const close = () => channel.dispatchEvent(new Event('close'));
raw.addEventListener('bufferedamountlow', drain);
raw.addEventListener('close', close);
channel.close = () => { ended = true; raw.removeEventListener('bufferedamountlow', drain); raw.removeEventListener('close', close); channel.dispatchEvent(new Event('close')); };
channel.send = data => {
if (ended || this.closed) throw new Error('Connection ended.');
if (typeof data === 'string') this.control({ type: 'frame', id, data });
else {
const packet = new Uint8Array(data.byteLength + 4);
new DataView(packet.buffer).setUint32(0, id);
packet.set(new Uint8Array(data), 4); raw.send(packet.buffer);
}
};
const direction = file ? 'send' : 'receive';
const item: Active = { id, meta, transfer: new Transfer(channel, {
file,
onState: state => this.callbacks.onState(direction, state, item.meta),
onMeta: metadata => { item.meta = metadata; this.callbacks.onState(direction, 'choose-storage', metadata); },
onProgress: (bytes, size) => this.callbacks.onProgress(direction, bytes, size),
onComplete: result => {
if (this.closed) return;
if (direction === 'send') this.outgoing = null; else this.incoming = null;
item.transfer.close(); this.callbacks.onComplete(direction, result);
queueMicrotask(() => { try { this.pump(); } catch (error) { this.fail(error); } });
},
onError: error => this.fail(error),
}) };
return item;
}
private message(data: unknown) {
if (this.closed) return;
if (data instanceof ArrayBuffer) {
if (!this.started || data.byteLength <= 4 || data.byteLength > CHUNK_SIZE + 4) throw new Error('Invalid file packet.');
const id = new DataView(data).getUint32(0);
if (!this.incoming || this.incoming.id !== id) throw new Error('Unexpected file ID.');
this.incoming.transfer.enqueue(data.slice(4)); return;
}
if (typeof data !== 'string' || data.length > 4096) throw new Error('Invalid session message.');
const msg: unknown = JSON.parse(data);
if (!isRecord(msg) || msg.v !== 3) throw new Error('Unsupported session protocol.');
if (msg.type === 'ready' && !this.peerReady) { this.peerReady = true; this.ready(); return; }
if (!this.started) throw new Error('File data arrived before verification.');
if (typeof msg.id !== 'number' || !Number.isInteger(msg.id) || msg.id <= 0 || msg.id > 0xffffffff) throw new Error('Invalid file ID.');
if (msg.type === 'start') {
if (this.incoming || msg.id % 2 !== (this.initiator ? 0 : 1) || msg.id <= this.lastRemoteId) throw new Error('Unexpected file offer.');
this.lastRemoteId = msg.id;
this.incoming = this.create(msg.id, null, { name: '', size: 0, mime: '' });
this.incoming.transfer.verify(); return;
}
if (msg.type === 'decline') {
const item = this.outgoing;
if (!item || item.id !== msg.id || item.transfer.state !== 'waiting-accept') throw new Error('Unexpected decline.');
this.outgoing = null; item.transfer.close(); this.callbacks.onDecline('send', item.meta); this.pump(); return;
}
if (msg.type === 'frame' && typeof msg.data === 'string') {
const item = [this.incoming, this.outgoing].find(item => item?.id === msg.id);
if (!item) throw new Error('Unexpected file ID.');
item.transfer.enqueue(msg.data); return;
}
throw new Error('Unexpected session message.');
}
private fail(error: unknown) { if (!this.closed) { this.callbacks.onError(asError(error)); this.close(); } }
close() {
if (this.closed) return;
this.closed = true; clearTimeout(this.timer);
this.outgoing?.transfer.close(); this.incoming?.transfer.close(); this.pending = [];
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close(); this.callbacks.onQueue([]); this.callbacks.onClose();
}
}
+38 -7
View File
@@ -27,6 +27,7 @@ export interface TransferOptions {
onProgress?: (bytes: number, size: number) => void;
onComplete?: (result: TransferResult) => void;
onError?: (error: Error) => void;
onClose?: () => void;
timeout?: number;
}
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
@@ -48,7 +49,10 @@ export function validateMetadata(meta: unknown): FileMetadata {
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
export class Transfer {
readonly dc: TransferChannel;
readonly file: File | null;
file: File | null;
readonly sending: boolean;
peerSupportsRepeat = false;
readonly onClose: () => void;
readonly onState: NonNullable<TransferOptions['onState']>;
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
@@ -77,9 +81,11 @@ export class Transfer {
if (!this.meta) throw new Error('Missing file metadata.');
return this.meta;
}
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 }: TransferOptions = {}) {
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, onClose = () => {}, timeout = 60000 }: TransferOptions = {}) {
this.dc = dc;
this.file = file;
this.sending = !!file;
this.onClose = onClose;
this.onState = onState;
this.onMeta = onMeta;
this.onProgress = onProgress;
@@ -115,7 +121,7 @@ export class Transfer {
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
}
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number } = {}) {
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number; repeat?: boolean } = {}) {
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.');
@@ -128,7 +134,7 @@ export class Transfer {
}
ready() {
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
if (!this.readySent) { this.control('ready'); this.readySent = true; }
if (!this.readySent) { this.control('ready', { repeat: true }); 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');
@@ -167,11 +173,14 @@ export class Transfer {
const msg: unknown = JSON.parse(data);
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
this.peerSupportsRepeat = msg.repeat === true;
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);
if (msg.type === 'meta' && !this.sending && (this.state === 'verification' || (this.state === 'done' && this.peerSupportsRepeat))) {
const meta = validateMetadata(msg);
this.resetFile();
this.meta = meta;
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
}
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
@@ -191,15 +200,36 @@ export class Transfer {
// 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.writable = null;
this.control('complete', { bytes: this.received });
this.setState('done'); clearTimeout(this.timer);
this.onComplete({ blob, meta: this.metadata }); 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.metadata }); this.close(); return;
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata });
if (!this.peerSupportsRepeat) this.close();
return;
}
throw new Error('Unexpected transfer message.');
}
get canSendAnother() {
return this.sending && this.state === 'done' && !this.closed && this.peerSupportsRepeat && this.dc.readyState === 'open';
}
private resetFile() {
this.received = this.sent = this.acked = 0;
this.chunks = [];
this.writable = null;
this.meta = null;
}
sendAnother(file: File) {
if (!this.canSendAnother) throw new Error('Start a new connection to send another file.');
const meta = validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
this.resetFile();
this.file = file;
this.meta = meta;
this.setState('waiting-accept');
this.guard(() => { this.control('meta', meta); this.touch(5 * 60 * 1000); });
}
accept(writable: FileDestination | null = null) {
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
@@ -235,5 +265,6 @@ export class Transfer {
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close();
this.onClose();
}
}
+2 -2
View File
@@ -132,7 +132,7 @@ export function getFingerprints(pc: { localDescription: { sdp: string } | null;
}
export function encodeSignal(sdp: string) {
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, '');
const code = btoa(JSON.stringify({ version: 3, 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;
}
@@ -142,7 +142,7 @@ export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTur
try {
const clean = text.trim().replace(/\s+/g, '');
const data: unknown = JSON.parse(atob(clean));
if (!isRecord(data) || data.version !== 2) throw new Error('Both people need the current HellCon version.');
if (!isRecord(data) || data.version !== 3) throw new Error('Both people need the current HellCon version.');
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
validateDescription(data.sdp, options);
return data.sdp;