Files
HellCon/src/App.vue
T
SchluffeandClaude Fable 5.2 3c47047ddd Release 1.0.2: take a file picked again, refuse a dropped folder
Chromium fires no change event when the picker returns the file its input
already holds. The page kept the old one then, though the file may have
changed on disk, which makes the old one unreadable, or another file was
dropped in between, which the input never saw. The input is now emptied as
soon as its file is taken, so every pick fires. Its title names the file
taken, the browser's own tooltip would say no file is chosen.

A dropped folder came as a file of 0 B that can't be read and failed only
once the receiver downloaded it. It is refused with a note now, the file
picked before stays.

Both are covered for Chromium, whose protocol is the only one that reaches
the real picker and a drag from the file manager.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 13:00:35 +01:00

635 lines
23 KiB
Vue

<script setup lang="ts">
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
import {
answerOffer,
type Check,
settings as coreSettings,
createOffer,
DEFAULT_STUN_SERVERS,
DEFAULT_TRACKERS,
type Events,
formatTime,
type Incoming,
type Phase,
PROTOCOL,
type ReceiveEvents,
randomCode,
receiveViaTracker,
type SendEvents,
sendViaTracker,
} from './core';
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
// defaults.
const settings = reactive(coreSettings);
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
const ownSalt = reactive({ on: false, text: '' });
// Empty is no salt, Share and Receive wait for one.
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
// From the code's alphabet, 16 characters are about 95 bits.
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
// contacts nobody before an offer, but typing makes one per keystroke, so each line is checked once.
const stunChecks = new Map<string, boolean>();
function isStun(url: string) {
if (!stunChecks.has(url)) {
try {
new RTCPeerConnection({ iceServers: [{ urls: url }] }).close();
stunChecks.set(url, /^stuns?:/i.test(url));
} catch {
stunChecks.set(url, false);
}
}
return stunChecks.get(url)!;
}
// public/ in the build, which works under any path, see vite.config.ts.
const BASE = import.meta.env.BASE_URL;
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
const secure = location.protocol === 'https:';
const isLocal = (hostname: string) =>
hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
hostname === '[::1]';
const isTracker = (url: string) => {
if (!URL.canParse(url) || url.includes('#')) return false;
const { protocol, hostname } = new URL(url);
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
};
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
const text = ref(settings[key].join('\n'));
const lines = computed(() =>
text.value
.split('\n')
.map((line) => line.trim())
.filter(Boolean),
);
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
// Immediate, a default may be a line this browser rejects.
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
// Unwraps both refs, so the template can bind them as plain properties.
return reactive({ text, invalid });
}
const stunServers = serverList('stunServers', isStun);
const trackers = serverList('trackers', isTracker);
function onResetServers() {
stunServers.text = DEFAULT_STUN_SERVERS.join('\n');
trackers.text = DEFAULT_TRACKERS.join('\n');
}
const file = ref<File>();
// The file of the send session, the user may have picked another one since.
const shared = ref<File>();
const offer = ref('');
const answerInput = ref('');
const sendCode = ref('');
// Until when a receiver can find the share with its code, whether with an own salt and whether that
// passed, as the core tells.
const sendUntil = ref(0);
const sendExpired = ref(false);
const offerInput = ref('');
const answer = ref('');
const receiveCode = ref('');
const check = ref<Check>();
const confirmed = ref(false);
// Changed in place and triggered, a deep ref would make each line cost every line kept.
const log = shallowRef<string[]>([]);
// Lines kept, the oldest go first and dropped counts them. A session logs a few dozen, a tracker or
// peer that sends garbage could add lines until the tab freezes.
const MAX_LOG = 1000;
const dropped = ref(0);
// Of the session, shown in the card of its side.
const error = ref('');
const status = ref<{ phase: Phase; text: string }>();
// The bar's look, an error colors whatever it showed.
const phase = computed(() => (error.value ? 'error' : status.value?.phase));
// Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => {
const lines = log.value;
lines.push(`${new Date().toISOString().slice(11, 23)} ${message}`);
if (lines.length > MAX_LOG) dropped.value += lines.splice(0, lines.length - MAX_LOG).length;
triggerRef(log);
},
error: (message) => {
events.log(message);
error.value = message;
},
status: (phase, text) => (status.value = { phase, text }),
check: (result) => {
check.value = result;
confirmed.value = false;
},
};
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
// a transfer starts.
type Progress = { read: number; size: number };
const sent = ref<Progress>();
const sendEvents: SendEvents = {
...events,
progress: (read, size) => (sent.value = { read, size }),
expired: () => (sendExpired.value = true),
};
const incoming = ref<Incoming>();
const received = ref<Progress>();
const receiveEvents: ReceiveEvents = {
...events,
progress: (read, size) => (received.value = { read, size }),
incoming: (file) => {
incoming.value = file;
received.value = undefined;
},
};
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
// Undefined makes the bar indeterminate: until the transfer starts it only shows how the session is
// doing. After it, or an error before it, the bar is full.
function barValue(progress?: Progress) {
if (progress) return percent(progress);
return ['start', 'wait', 'retry'].includes(phase.value!) ? undefined : 100;
}
function onConfirm() {
confirmed.value = true;
check.value?.confirm();
}
// The text copied last and whether that worked. Its button says so, after a success for a moment.
const copied = ref<{ text: string; ok: boolean }>();
let copiedTimer: number | undefined;
const copyLabel = (text: string) => (copied.value?.text !== text ? 'Copy' : copied.value.ok ? 'Copied' : 'Copy failed');
const copyFailed = (text: string) => copied.value?.text === text && !copied.value.ok;
// Copies text, shown in the element with id. If the browser blocks that, the text gets selected, so
// the user can copy it themselves.
async function onCopy(text: string, id: string) {
clearTimeout(copiedTimer);
try {
await navigator.clipboard.writeText(text);
} catch {
events.log('copy failed, the browser blocked the clipboard');
copied.value = { text, ok: false };
const element = document.getElementById(id);
if (element instanceof HTMLTextAreaElement) {
element.focus();
element.select();
} else if (element) getSelection()?.selectAllChildren(element);
return;
}
copied.value = { text, ok: true };
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
}
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
// One session at a time, started by Share, Create offer, Receive or Create answer. Starting one ends
// the one before: its connections close and what it showed goes, so nothing else can write here.
let session: AbortController | undefined;
const side = ref<'send' | 'receive'>();
// Whether the session is a tracker share or search, which runs with the salt it started with.
const viaTracker = ref(false);
// what goes into the log, so the sessions in it can be told apart.
function begin(on: 'send' | 'receive', what: string, tracker = false) {
session?.abort();
session = new AbortController();
side.value = on;
viaTracker.value = tracker;
events.log(`--- ${what} ---`);
error.value = '';
status.value = undefined;
check.value = undefined;
confirmed.value = false;
sent.value = undefined;
incoming.value = undefined;
received.value = undefined;
sendCode.value = '';
sendExpired.value = false;
offer.value = '';
answer.value = '';
acceptAnswer = undefined;
return session.signal;
}
// Resolves with the result of a session step, or undefined if it failed, which is shown, or if a
// newer session replaced it meanwhile.
async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
try {
const result = await step;
return signal.aborted ? undefined : result;
} catch (failure) {
if (!signal.aborted) events.error(failure instanceof Error ? failure.message : String(failure));
}
}
// The name of a dropped folder, until a file takes its place.
const folder = ref('');
function take(picked: File) {
file.value = picked;
folder.value = '';
}
// The input is emptied right away: Chromium fires no change event for the file its input already
// holds, though that file may have changed on disk, or another one was dropped since, which the
// input never saw. An event without a file has nothing to take. Empty, the input's own tooltip says no
// file is chosen, so its title names the one taken.
function onPick(event: Event) {
const input = event.target as HTMLInputElement;
const picked = input.files?.[0];
input.value = '';
if (picked) take(picked);
}
const dragging = ref(false);
// A folder comes as a file too, one that can't be read: refused here, it would fail only once the
// receiver downloads it. The file picked before stays.
function onDrop(event: DragEvent) {
dragging.value = false;
const dropped = event.dataTransfer?.files[0];
const entry = [...(event.dataTransfer?.items ?? [])].find((item) => item.kind === 'file')?.webkitGetAsEntry();
if (entry?.isDirectory) folder.value = entry.name;
else if (dropped) take(dropped);
}
function formatSize(bytes: number) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let unit = 0;
while (bytes >= 1024 && unit < units.length - 1) {
bytes /= 1024;
unit++;
}
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
}
async function onCreateOffer() {
const signal = begin('send', `manual offer for ${file.value!.name}`);
shared.value = file.value;
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
if (!result) return;
offer.value = result.offer;
acceptAnswer = result.accept;
}
// Part of the current session, a wrong answer can be corrected.
function onAcceptAnswer() {
error.value = '';
if (acceptAnswer) attempt(session!.signal, acceptAnswer(answerInput.value));
}
async function onCreateAnswer() {
const signal = begin('receive', 'manual answer');
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
if (result) answer.value = result;
}
async function onShare() {
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
shared.value = file.value;
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
if (!result) return;
sendCode.value = result.code;
sendUntil.value = result.until;
}
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
// the tracker ends it.
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
function onReceive() {
const signal = begin('receive', 'receive via tracker', true);
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
}
// The salt stays as it is while a tracker share runs: it waits in the swarm of the salt it started
// with, another one shown would be the wrong one to give the receiver. A search only takes the salt
// on Receive, so a wrong one can be fixed and searched with again.
const saltLocked = computed(
() => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!),
);
// While a share waits or a transfer runs. A phone that dims and locks may suspend the tab and the
// connection dies, a reload or a closed tab ends it for sure.
const busy = computed(() => ['start', 'wait', 'retry', 'transfer'].includes(phase.value!));
// The screen's, held while busy. The browser releases it whenever the page is hidden, so it's
// requested again once the page is visible.
let wakeLock: Promise<WakeLockSentinel | undefined> | undefined;
function holdWakeLock() {
// Missing outside a secure context, e.g. the dev server opened by its LAN address.
if (!busy.value || document.hidden || wakeLock || !navigator.wakeLock) return;
const request = navigator.wakeLock.request('screen').then(
(sentinel) => {
sentinel.addEventListener('release', () => {
if (wakeLock === request) wakeLock = undefined;
});
// Unless let go of meanwhile, releaseWakeLock releases it then.
if (wakeLock === request) events.log('keeping the screen on');
return sentinel;
},
(failure) => {
if (wakeLock === request) wakeLock = undefined;
events.log(`screen may lock: ${failure instanceof Error ? failure.message : failure}`);
return undefined;
},
);
wakeLock = request;
}
// Forgotten right away, a session started before the browser released it requests a new one.
function releaseWakeLock() {
const request = wakeLock;
wakeLock = undefined;
request?.then((sentinel) => sentinel?.release());
}
// The browser asks before a reload or a closed tab ends it. Only while busy, a page with the handler
// may be kept out of the back/forward cache.
const confirmLeave = (event: BeforeUnloadEvent) => event.preventDefault();
watch(busy, (busy) => {
if (busy) {
holdWakeLock();
addEventListener('beforeunload', confirmLeave);
} else {
releaseWakeLock();
removeEventListener('beforeunload', confirmLeave);
}
});
document.addEventListener('visibilitychange', holdWakeLock);
</script>
<template>
<header>
<div>
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
<h1>HellCon</h1>
</div>
<div id="options">
<div>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
Use STUN
</label>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
Use own salt
</label>
</div>
<div v-if="ownSalt.on" role="group">
<input
id="salt"
v-model="ownSalt.text"
aria-label="Own salt"
placeholder="Same salt on both sides"
:aria-invalid="saltMissing"
:disabled="saltLocked"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
Generate
</button>
</div>
</div>
</header>
<main>
<p v-if="!settings.stun" id="no-stun" role="note">
STUN is off: only devices on the same network or VPN can connect.
</p>
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
No STUN server under Servers: only devices on the same network or VPN can connect.
</p>
<aside v-if="check" role="alert">
<p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
before.
</p>
<dl>
<dt>You</dt>
<dd><output id="check-local">{{ check.local }}</output></dd>
<dt>Peer</dt>
<dd><output id="check-remote">{{ check.remote }}</output></dd>
</dl>
<div v-if="!confirmed">
<button id="confirm" type="button" @click="onConfirm">Codes match</button>
<button id="reject" type="button" @click="check.reject()">Codes don't match</button>
</div>
</aside>
<article>
<h2>Send</h2>
<label
:data-dragging="dragging || undefined"
@dragover.prevent="dragging = true"
@dragleave="dragging = false"
@drop.prevent="onDrop"
>
<input type="file" :title="file?.name" @change="onPick" />
<template v-if="file">
<strong>{{ file.name }}</strong>
{{ formatSize(file.size) }}
</template>
<template v-else>Drop a file or click to choose</template>
<span v-if="folder" id="not-a-file" role="alert">{{ folder }} is a folder, only a single file can be sent</span>
</label>
<div v-if="side === 'send' && phase" :data-phase="phase">
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
<div>
<progress id="send-progress" max="100" :value="barValue(sent)" aria-label="Sent"></progress>
</div>
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="send-status">{{ status!.text }}</span>
<span v-if="sent">{{ percent(sent) }}&nbsp;%</span>
</p>
</div>
<section>
<h3>Tracker</h3>
<button id="share" type="button" :disabled="!file || !settings.trackers.length || saltMissing" @click="onShare">
Share via tracker
</button>
<template v-if="sendCode">
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
<label v-else for="send-code">
Code, give this {{ ownSalt.on ? 'and your salt ' : '' }}to the receiver, valid until
{{ formatTime(sendUntil) }}:
</label>
<div role="group">
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
<button
id="copy-send-code"
type="button"
data-copy
:disabled="codeGone"
@click="onCopy(sendCode, 'send-code')"
>
{{ copyLabel(sendCode) }}
</button>
</div>
<p v-if="copyFailed(sendCode)" role="alert">
The browser blocked copying. The code is selected, copy it yourself.
</p>
</template>
</section>
<details id="send-manual">
<summary>Manual</summary>
<section>
<button id="create-offer" type="button" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
{{ copyLabel(offer) }}
</button>
<p v-if="copyFailed(offer)" role="alert">
The browser blocked copying. The offer is selected, copy it yourself.
</p>
<label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
Connect
</button>
</template>
</section>
</details>
</article>
<article>
<h2>Receive</h2>
<div id="incoming">
<template v-if="incoming">
<strong>{{ incoming.name }}</strong>
{{ formatSize(incoming.size) }}
<button v-if="!received" id="download" type="button" @click="incoming.download()">Download</button>
</template>
<template v-else>The sender's file shows up here after the security check</template>
</div>
<div v-if="side === 'receive' && phase" :data-phase="phase">
<div>
<progress id="receive-progress" max="100" :value="barValue(received)" aria-label="Received"></progress>
</div>
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="receive-status">{{ status!.text }}</span>
<span v-if="received">{{ percent(received) }}&nbsp;%</span>
</p>
</div>
<section>
<h3>Tracker</h3>
<label for="receive-code">Code from the sender:</label>
<div role="group">
<input
id="receive-code"
v-model="receiveCode"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button
id="receive"
type="button"
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
@click="onReceive"
>
Receive
</button>
</div>
</section>
<details id="receive-manual">
<summary>Manual</summary>
<section>
<label for="offer-input">Offer from the sender:</label>
<textarea id="offer-input" v-model="offerInput"></textarea>
<button id="create-answer" type="button" :disabled="!offerInput.trim()" @click="onCreateAnswer">
Create answer
</button>
<template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
{{ copyLabel(answer) }}
</button>
<p v-if="copyFailed(answer)" role="alert">
The browser blocked copying. The answer is selected, copy it yourself.
</p>
</template>
</section>
</details>
</article>
<details id="servers">
<summary>Servers</summary>
<div>
<section>
<h3>STUN</h3>
<label for="stun-servers">Tell each side its public address, one URL per line:</label>
<textarea
id="stun-servers"
v-model="stunServers.text"
:aria-invalid="!!stunServers.invalid.length"
></textarea>
<p v-if="stunServers.invalid.length">
Skipped, not a STUN URL this browser accepts: {{ stunServers.invalid.join(', ') }}
</p>
</section>
<section>
<h3>Trackers</h3>
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label>
<textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
<p v-if="trackers.invalid.length">
Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
{{ trackers.invalid.join(', ') }}
</p>
</section>
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
</div>
</details>
<details>
<summary>Log</summary>
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
</details>
</main>
<footer>
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
Source code
</a>
<span>Protocol {{ PROTOCOL }}</span>
</footer>
</template>