Every operation (share, receive, manual offer or answer) now runs as one session tied to an AbortSignal. Starting another ends it: its connections, tracker sockets and timers close, and it can no longer touch the shared security check, progress or incoming file. Finished, failed and cancelled transfers close their connections, and the sender's tracker sockets close once the download starts. - A malformed or never-connecting tracker offer no longer blocks a share - The receiver validates the file offer and rejects excess bytes and data beyond the flow control window; sw.js checks name and size too - Failures show up in the card instead of disappearing into rejected promises: bad manual codes, unreachable trackers, lost connections - Primary buttons and pink text meet 4.5:1 contrast, the STUN switch shows keyboard focus again, the tracker Copy button matches the others - Split the core into src/core.ts, src/main.ts only mounts the app, which removes the main.ts <-> App.vue import cycle - Bring back the Gitea source link, write the README - Tests reuse one browser per worker with fresh contexts, fail on page errors, check cleanup after transfers, use a local fake STUN server and cover empty files, window boundaries, odd names, malformed messages, session replacement and the production build Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
391 lines
13 KiB
Vue
391 lines
13 KiB
Vue
<script setup lang="ts">
|
|
import { computed, reactive, ref, watch } from 'vue';
|
|
import {
|
|
answerOffer,
|
|
createOffer,
|
|
DEFAULT_STUN_SERVERS,
|
|
DEFAULT_TRACKERS,
|
|
receiveViaTracker,
|
|
sendViaTracker,
|
|
settings as coreSettings,
|
|
type Check,
|
|
type Events,
|
|
type Incoming,
|
|
type ReceiveEvents,
|
|
} from './core';
|
|
|
|
const SETTINGS_KEY = 'hellcon:settings';
|
|
|
|
// Same object as the core's, so the core sees every change.
|
|
const settings = reactive(coreSettings);
|
|
|
|
// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay.
|
|
try {
|
|
const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}');
|
|
if (typeof saved.stun === 'boolean') settings.stun = saved.stun;
|
|
if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers;
|
|
if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers;
|
|
} catch {}
|
|
|
|
watch(
|
|
settings,
|
|
() => {
|
|
try {
|
|
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
|
} catch {}
|
|
},
|
|
{ deep: true },
|
|
);
|
|
|
|
// 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)!;
|
|
}
|
|
|
|
// Every # starts a fragment, which WebSocket rejects even when empty.
|
|
const isTracker = (url: string) =>
|
|
URL.canParse(url) && ['ws:', 'wss:'].includes(new URL(url).protocol) && !url.includes('#');
|
|
|
|
// 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 saved list may hold lines 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>();
|
|
const offer = ref('');
|
|
const answerInput = ref('');
|
|
const sendCode = ref('');
|
|
|
|
const offerInput = ref('');
|
|
const answer = ref('');
|
|
const receiveCode = ref('');
|
|
|
|
const check = ref<Check>();
|
|
const confirmed = ref(false);
|
|
const log = ref<string[]>([]);
|
|
// Of the session, shown in the card of its side.
|
|
const error = ref('');
|
|
|
|
// Shared by both sides, each adds its own progress.
|
|
const events: Omit<Events, 'progress'> = {
|
|
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
|
|
error: (message) => {
|
|
events.log(message);
|
|
error.value = message;
|
|
},
|
|
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: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) };
|
|
|
|
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);
|
|
|
|
function onConfirm() {
|
|
confirmed.value = true;
|
|
check.value?.confirm();
|
|
}
|
|
|
|
// The text copied last, its button says so for a moment.
|
|
const copied = ref('');
|
|
let copiedTimer: number | undefined;
|
|
|
|
async function onCopy(text: string) {
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
} catch {
|
|
return events.log('copy failed, the browser blocked the clipboard');
|
|
}
|
|
copied.value = text;
|
|
clearTimeout(copiedTimer);
|
|
copiedTimer = window.setTimeout(() => (copied.value = ''), 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'>();
|
|
|
|
function begin(on: 'send' | 'receive') {
|
|
session?.abort();
|
|
session = new AbortController();
|
|
side.value = on;
|
|
error.value = '';
|
|
check.value = undefined;
|
|
confirmed.value = false;
|
|
sent.value = undefined;
|
|
incoming.value = undefined;
|
|
received.value = undefined;
|
|
sendCode.value = '';
|
|
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));
|
|
}
|
|
}
|
|
|
|
function onPick(event: Event) {
|
|
file.value = (event.target as HTMLInputElement).files?.[0];
|
|
}
|
|
|
|
const dragging = ref(false);
|
|
|
|
function onDrop(event: DragEvent) {
|
|
dragging.value = false;
|
|
file.value = event.dataTransfer?.files[0] ?? file.value;
|
|
}
|
|
|
|
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)} ${units[unit]}`;
|
|
}
|
|
|
|
async function onCreateOffer() {
|
|
const signal = begin('send');
|
|
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');
|
|
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
|
if (result) answer.value = result;
|
|
}
|
|
|
|
async function onShare() {
|
|
const signal = begin('send');
|
|
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
|
if (code) sendCode.value = code;
|
|
}
|
|
|
|
function onReceive() {
|
|
const signal = begin('receive');
|
|
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
|
}
|
|
</script>
|
|
|
|
<template>
|
|
<header>
|
|
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
|
<h1>HellCon</h1>
|
|
<label>
|
|
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
|
Use STUN
|
|
</label>
|
|
</header>
|
|
|
|
<main>
|
|
<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" @click="onConfirm">Codes match</button>
|
|
<button id="reject" @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" @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>
|
|
</label>
|
|
<p v-if="sent">
|
|
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
|
|
{{ percent(sent) }} %
|
|
</p>
|
|
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
|
|
|
|
<section>
|
|
<h3>Tracker</h3>
|
|
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
|
|
<template v-if="sendCode">
|
|
<label for="send-code">Code, give this to the receiver:</label>
|
|
<div role="group">
|
|
<output id="send-code">{{ sendCode }}</output>
|
|
<button id="copy-send-code" data-copy @click="onCopy(sendCode)">{{ copied === sendCode ? 'Copied' : 'Copy' }}</button>
|
|
</div>
|
|
</template>
|
|
</section>
|
|
|
|
<details id="send-manual">
|
|
<summary>Manual</summary>
|
|
<section>
|
|
<button id="create-offer" :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" data-copy @click="onCopy(offer)">{{ copied === offer ? 'Copied' : 'Copy' }}</button>
|
|
<label for="answer-input">Answer from the receiver:</label>
|
|
<textarea id="answer-input" v-model="answerInput"></textarea>
|
|
<button id="accept-answer" :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" @click="incoming.download()">Download</button>
|
|
</template>
|
|
<template v-else>The sender's file shows up here after the security check</template>
|
|
</div>
|
|
<p v-if="received">
|
|
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress>
|
|
{{ percent(received) }} %
|
|
</p>
|
|
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
|
|
|
|
<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" :disabled="!settings.trackers.length || !receiveCode.trim()" @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" :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" data-copy @click="onCopy(answer)">{{ copied === answer ? 'Copied' : 'Copy' }}</button>
|
|
</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 #: {{ trackers.invalid.join(', ') }}</p>
|
|
</section>
|
|
<button id="reset-servers" @click="onResetServers">Reset to defaults</button>
|
|
</div>
|
|
</details>
|
|
|
|
<details>
|
|
<summary>Log</summary>
|
|
<pre id="log">{{ log.join('\n') }}</pre>
|
|
</details>
|
|
</main>
|
|
|
|
<footer>
|
|
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
|
<img src="/gitea.svg" alt="" width="20" height="20" />
|
|
Source code
|
|
</a>
|
|
</footer>
|
|
</template>
|