Add shareable invitation links

Codes now travel as links with the code in the URL fragment, which the
app reads and clears before mounting (and on hashchange). An offer link
opens a preview that suggests an idle slot, preferring the one paired
with the sender's device, and only fills in the code; the user still
creates the answer. Answer links reach the waiting sender tab over a
same-origin BroadcastChannel, are acknowledged once and reported as
used afterwards, and fall back to copy and paste when no tab answers.

The panel offers Share link where the Web Share API accepts URLs, Copy
link, and the bare code under a disclosure. The browser check covers
the offer dialog, clean URL, answer relay, reuse, fallback on another
origin, an invalid fragment, axe on both dialogs and exact bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-19 22:44:15 +02:00
1 parent 8bd37ac8b1
commit 43ee7f119f
14 files changed
+421 -58

No files matched your search

+7
View File
@@ -22,6 +22,13 @@
can use Send to add files without reconnecting. Disconnect
aborts unfinished writes while preserving the last completed memory download.
- Document the hosted-first, serverless UX roadmap.
- Add shareable invitation links. Codes travel in the URL fragment, which is
never sent to the host and is removed from the address bar on opening. An
offer link opens a preview that suggests an idle connection (the one paired
with the sender's device first) and fills in the code without answering. An
answer link opened in the same browser connects the waiting sender tab;
elsewhere it shows the answer to copy. **Share link** uses the Web Share API
where available; **Copy link** and the bare code always remain.
### Changed
+27 -11
View File
@@ -4,7 +4,8 @@ Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for releas
and compatibility changes.
Browser-to-browser file sharing with Vue 3 and WebRTC. No accounts, signaling
backend, or server-side file storage. You exchange connection codes manually.
backend, or server-side file storage. You exchange invitation links or
connection codes yourself, through any messenger.
Direct connections are the default. TURN relaying is optional and requires
explicit opt-in by both people; no relay is configured automatically.
@@ -40,12 +41,18 @@ remain available. Up to 100 connection slots are supported.
## How it works
1. The person starting the connection selects one or more files and configures STUN (PageQuit by default, Google,
Cloudflare, a custom provider, or None). They create a code and send it
privately to the intended receiver through an authenticated channel. Normal
messenger copy/paste is supported; there is no need to transcribe codes.
2. The receiver pastes the code, creates an answer, and sends it back. The sender
pastes the answer. Gathering waits for completion, up to 30 seconds; a timeout
fails rather than quietly exporting incomplete connection information.
Cloudflare, a custom provider, or None). They create a code and send it as a
link (**Share link** where the browser supports it, or **Copy link**)
privately to the intended receiver through an authenticated channel. The bare
code remains available under **Show code instead**; there is no need to
transcribe either.
2. The receiver opens the link or pastes the link or code. An opened link shows a
preview and lets them choose which connection receives it; nothing is sent
until they click **Accept & create answer**. They send the answer link back.
Opened in the browser that holds the sender's tab, it connects that tab
directly; otherwise it shows the answer to copy, and the sender pastes it.
Gathering waits for completion, up to 30 seconds; a timeout fails rather than
quietly exporting incomplete connection information.
3. **Both people compare both full SHA-256 certificate fingerprints** over a
channel whose authenticity and integrity they trust, such as in person.
Your fingerprint must equal their “Their fingerprint”, and vice versa.
@@ -163,10 +170,19 @@ one network. A VPN is not automatically a guarantee against address disclosure.
Connection codes are **compressed and Base64url-encoded, not encrypted**
(`HC1.` followed by deflated JSON). They contain SDP, including candidate
addresses, temporary ICE credentials and certificate fingerprints. Peers and anyone who sees these codes (including the messaging
service used to exchange them) may learn connection details. Local addresses may
be obscured by the browser, but this app does not provide anonymity. Treat codes
as private session information; do not publish them.
addresses, temporary ICE credentials and certificate fingerprints. Peers and
anyone who sees these codes (including the messaging service used to exchange
them) may learn connection details. Local addresses may be obscured by the
browser, but this app does not provide anonymity. Treat codes as private session
information; do not publish them.
Invitation links carry the code after `#`. Browsers do not send this fragment to
the app host, and the app removes it from the address bar on opening. A link is
otherwise exactly as sensitive as its code: recipients and messengers see it, and
browser history (including synced history) may keep it. Opening an offer link
never answers automatically. Answer links reach the waiting tab over a
same-origin `BroadcastChannel`; other sites cannot post to it. See
[the invitation design](docs/invitations.md).
Restrictive NATs or firewalls can prevent direct connections. There is no silent
TURN retry. To permit a relay, both people must explicitly check **Allow a TURN
+6 -1
View File
@@ -1,4 +1,4 @@
# Shareable invitations (planned, not implemented)
# Shareable invitations
Phase 4 of the [UX roadmap](ux-roadmap.md). The sender shares a link instead of
a pasted code; the receiver opens it, previews it and creates an answer, which
@@ -103,6 +103,11 @@ hand-written encoder or a dependency, and scanning adds camera handling.
## Implementation steps and acceptance checks
Steps 1–5 and 7 are implemented (`src/lib/codes.ts`, `src/lib/invitations.ts`,
`InvitationDialog.vue`, and the invitation flow in `scripts/browser-check.ts`,
which opens the fallback on a second origin instead of a separate browser
context). Step 6 still needs manual verification.
1. Codec module with Node tests: round trips for both types and versions, bare
code vs. link, whitespace, invalid base64url, oversized input, decompression
bomb, wrong `type`, `ref` mismatch, old-format detection.
+10 -12
View File
@@ -88,21 +88,19 @@ storage denial/recovery, and protocol-version validation. Design and review note
are in [the device identity protocol](device-identities.md); this is not an
independent cryptographic audit.
## 4. Shareable invitations
## 4. Shareable invitations — implemented
Detailed in [the invitation plan](invitations.md).
Detailed in [the invitation design](invitations.md).
For HTTPS, encode fresh offers in URL fragments with an explicit Share/Copy link
action and an import preview. Keep connection details out of query strings and
server paths. Fragments still expose their contents to link recipients and any
service carrying the full link; explain that invitations are private. Clear the
fragment after import. Provide a similarly convenient answer handoff; an answer
exchange remains necessary. Keep pasteable codes as the universal fallback.
Offers and answers are shared as links with the compressed code in the URL
fragment, through **Share link** where supported or **Copy link**; the bare code
stays available. Opening a link clears the fragment. An offer opens an import
preview with slot selection and never answers automatically. An answer link
reaches the waiting sender tab in the same browser over `BroadcastChannel` and
otherwise falls back to copy and paste. An answer exchange remains necessary.
Bound and validate payloads, handle stale/incompatible links, and test practical
URL limits across messengers and mobile browsers. Do not promise a short link
without a storage service. Consider compressed payloads and QR only after checking
real payload sizes and decoding limits.
Still open: manual checks of link length, previews and in-app browsers across
real messengers and phones. QR codes remain deferred.
## 5. Guided connection flow
+70 -8
View File
@@ -49,6 +49,7 @@ interface ProtocolResults {
'Browser.setDownloadBehavior': object;
'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string };
'Target.closeTarget': object;
'Runtime.enable': object;
'Page.enable': object;
'Page.navigate': object;
@@ -99,9 +100,11 @@ async function wait(session: string, check: () => unknown) {
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
}
const targets = new Map<string, string>();
async function page(url = origin) {
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
targets.set(sessionId, targetId);
await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId);
// Background tabs otherwise skip focus/blur events, which the name editor relies on.
@@ -114,7 +117,8 @@ async function page(url = origin) {
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url }, sessionId);
for (let n = 0; n < 100; n++) {
try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url)) break; }
// The app removes invitation fragments from the address bar.
try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url.split('#')[0]!)) break; }
catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20));
}
@@ -132,6 +136,15 @@ async function checkAccessibility(session: string, mode: string) {
});
assert.deepEqual(violations, [], `${mode} mode accessibility violations`);
}
const screenshot = async (session: string, name: string) => {
if (!screenshotDirectory) return;
await mkdir(screenshotDirectory, { recursive: true });
await call('Page.bringToFront', {}, session);
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64'));
};
const closePage = (session: string) => call('Target.closeTarget', { targetId: targets.get(session) });
const dialogText = (session: string) => evaluate(session, () => document.querySelector('dialog[open]')?.textContent ?? '');
const click = (session: string, label: string) => evaluate(session, (label: string) => window.__hellcon.click(label), label);
const input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value);
const enableTurn = (session: string) => evaluate(session, () => {
@@ -212,13 +225,6 @@ try {
if (!button) throw new Error('Missing connection: ' + name);
button.click();
}, name);
const screenshot = async (session: string, name: string) => {
if (!screenshotDirectory) return;
await mkdir(screenshotDirectory, { recursive: true });
await call('Page.bringToFront', {}, session);
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64'));
};
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
await checkAccessibility(sender, 'Connections desktop');
@@ -475,6 +481,62 @@ try {
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (!turn) {
// Invitation links: the offer opens a dialog in a fresh page, the answer link
// reaches the sender's tab, and other origins fall back to copy and paste.
const inviter = await page();
await evaluate(inviter, () => window.__hellcon.chooseFile(3000, 'invited.bin'));
await input(inviter, '#stun-provider', provider);
await click(inviter, 'Create code'); await wait(inviter, () => !!document.querySelector('#output-link'));
const offerLink = await evaluate(inviter, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const offerCode = await evaluate(inviter, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(offerLink, `${origin}/#${offerCode}`);
const invited = await page(offerLink);
await wait(invited, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files'));
assert.equal(await evaluate(invited, () => location.href), `${origin}/`);
assert.match(await dialogText(invited), /temporary identity/);
await checkAccessibility(invited, 'Invitation dialog');
if (screenshotDirectory) await evaluate(inviter, () => window.__hellcon.element('#output-link').scrollIntoView({ block: 'center' }));
await screenshot(inviter, 'invitation-share');
await screenshot(invited, 'invitation-offer');
await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, invited);
assert.equal(await evaluate(invited, () => document.documentElement.scrollWidth <= innerWidth), true, 'Invitation dialog must not overflow horizontally');
await screenshot(invited, 'invitation-offer-mobile');
await click(invited, 'Open'); await wait(invited, () => !document.querySelector('dialog[open]'));
await wait(invited, () => document.activeElement?.textContent === 'Accept & create answer');
assert.equal(await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offerCode);
assert.equal(await evaluate(invited, () => window.__hellcon.element('.tabs button[aria-pressed=true]').textContent), 'Receive');
await input(invited, '#stun-provider', provider);
await click(invited, 'Accept & create answer'); await wait(invited, () => !!document.querySelector('#output-link'));
const answerLink = await evaluate(invited, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const answerCode = await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
const elsewhere = await page(answerLink.replace('127.0.0.1', 'localhost'));
await wait(elsewhere, () => document.querySelector('dialog[open]')?.textContent?.includes('Paste this answer in the sender’s tab'));
assert.equal(await evaluate(elsewhere, () => window.__hellcon.element<HTMLTextAreaElement>('#invitation-answer').value), answerCode);
await checkAccessibility(elsewhere, 'Answer fallback dialog');
await screenshot(elsewhere, 'invitation-answer-fallback');
assert.equal(await evaluate(inviter, () => !!document.querySelector('.fingerprint')), false);
const relay = await page(answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer delivered'));
await wait(inviter, () => !!document.querySelector('.fingerprint'));
await evaluate(relay, (link: string) => { location.hash = link.split('#')[1]!; }, answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer already used'));
assert.equal(await evaluate(relay, () => location.hash), '');
await click(relay, 'Close');
await evaluate(relay, () => { location.hash = 'HC1.not-a-code'; });
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Link could not be opened'));
await click(inviter, 'Both fingerprints match — confirm'); await click(invited, 'Both fingerprints match — confirm');
await wait(invited, () => !!document.querySelector('.incoming'));
await click(invited, 'Accept file');
await wait(inviter, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
const invitedBytes = await evaluate(invited, async () => {
const link = window.__hellcon.element<HTMLAnchorElement>('a.download');
const bytes = new Uint8Array(await (await fetch(link.href)).arrayBuffer());
return { name: link.download, length: bytes.length, valid: bytes.every(byte => byte === 123) };
});
assert.deepEqual(invitedBytes, { name: 'invited.bin', length: 3000, valid: true });
for (const session of [inviter, invited, elsewhere, relay]) await closePage(session);
console.log('PASS: offer links open a reviewed import with a clean URL; answer links connect the waiting tab once, fall back to copy and paste elsewhere, and transfer exact bytes.');
const identitySender = await page();
const receiverOrigin = origin.replace('127.0.0.1', 'localhost');
const identityReceiver = await page(receiverOrigin);
+29 -3
View File
@@ -3,9 +3,14 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.vue';
import EditableName from './components/EditableName.vue';
import InvitationDialog from './components/InvitationDialog.vue';
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionActivity, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
import { takeFragment } from './lib/invitations.ts';
import { asError } from './lib/validation.ts';
// A code from the link this page was opened with, already removed from the URL.
const props = defineProps<{ initialCode?: string }>();
const logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`;
const connections = ref<SavedConnection[]>([]), selected = ref('');
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
@@ -14,6 +19,10 @@ const sidebarOpen = ref(false), adding = ref(false);
const confirmingRemoval = ref(false), removing = ref(false);
const error = ref(''), removalError = ref('');
const heading = ref<HTMLElement | null>(null);
// An opened link awaiting review, and an accepted offer on its way to a slot.
const invitation = ref<{ code: string } | null>(null);
const handoff = ref<{ connection: string; code: string } | null>(null);
const canAdd = computed(() => !adding.value && !removing.value && connections.value.length < CONNECTION_LIMIT);
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
let updates: BroadcastChannel | undefined;
function select(id: string) {
@@ -48,8 +57,15 @@ onMounted(async () => {
updates.onmessage = () => { void refresh(); };
}
window.addEventListener('focus', refresh);
window.addEventListener('hashchange', openLink);
if (props.initialCode) invitation.value = { code: props.initialCode };
});
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); window.removeEventListener('hashchange', openLink); });
// A link opened in an existing tab only changes the fragment.
function openLink() {
const code = takeFragment();
if (code) invitation.value = { code };
}
async function add() {
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
adding.value = true;
@@ -57,10 +73,18 @@ async function add() {
await writes;
if (persistent) connections.value = await addConnection();
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
const id = connections.value.at(-1)!.id;
select(id); updates?.postMessage('changed');
return id;
} catch (err) { error.value = asError(err).message; }
finally { adding.value = false; }
}
async function openInvitation(target: string, code: string) {
const id = target === 'new' ? await add() : target;
if (!id || !connections.value.some(item => item.id === id)) return;
if ((states.value[id] ?? 'ready') !== 'ready') { error.value = 'That connection is in use. Open the link again and choose another connection.'; return; }
select(id); handoff.value = { connection: id, code };
}
function update(id: string, change: ConnectionUpdate) {
const index = connections.value.findIndex(item => item.id === id);
if (index < 0) return;
@@ -154,7 +178,8 @@ async function remove() {
<p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id">
<KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" @status="setStatus" @activity="record" @update="update" />
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null"
@status="setStatus" @activity="record" @update="update" @invitation-taken="handoff = null" />
</KeepAlive>
</template>
<p v-if="!current" class="status">Opening your connections…</p>
@@ -170,4 +195,5 @@ async function remove() {
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
</template>
</AppDialog>
<InvitationDialog v-if="current" v-model="invitation" :connections="connections" :states="states" :current="current.id" :can-add="canAdd" @open="openInvitation" />
</template>
+13 -2
View File
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { ref } from 'vue';
import { nextTick, ref, watch } from 'vue';
import TransferPanel from './TransferPanel.vue';
import type { SavedConnection, ConnectionActivity, ConnectionUpdate } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection> }>();
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; invitation?: { code: string } | null }>();
const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
activity: [id: string, item: ConnectionActivity];
update: [id: string, change: ConnectionUpdate];
invitationTaken: [];
}>();
const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false), connected = ref(false);
@@ -17,6 +18,16 @@ function navigate(next: 'send' | 'receive') {
if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
else if (!sessionActive.value) mode.value = next;
}
// An accepted invitation switches an idle slot to Receive and fills the code;
// the user still creates the answer.
watch(() => props.invitation, async invitation => {
if (!invitation) return;
emit('invitationTaken');
if (sessionActive.value) return;
mode.value = 'receive';
await nextTick();
panel.value?.importCode(invitation.code);
}, { immediate: true });
function sizeLabel(size: number) {
if (size < 1024) return `${size} B`;
const index = Math.min(5, Math.floor(Math.log(size) / Math.log(1024)));
+110
View File
@@ -0,0 +1,110 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import AppDialog from './AppDialog.vue';
import { decodeCode, type Signal } from '../lib/codes.ts';
import { deliverAnswer, type Delivery } from '../lib/invitations.ts';
import { hasRelay } from '../lib/webrtc.ts';
import { asError } from '../lib/validation.ts';
import type { SavedConnection } from '../lib/connections.ts';
// A link opened in this tab. Offers are previewed and handed to a chosen slot;
// they never create an answer here, because answering reveals this device's
// addresses to whoever made the link.
const invitation = defineModel<{ code: string } | null>({ required: true });
const props = defineProps<{ connections: SavedConnection[]; states: Record<string, 'ready' | 'connecting' | 'connected'>; current: string; canAdd: boolean }>();
const emit = defineEmits<{ open: [target: string, code: string] }>();
const signal = ref<Signal | null>(null), failure = ref('');
const delivery = ref<Delivery | 'pending' | 'manual'>('pending');
const target = ref(''), copied = ref(false), copyError = ref('');
const open = computed({ get: () => !!invitation.value, set: value => { if (!value) invitation.value = null; } });
const idle = (id: string) => (props.states[id] ?? 'ready') === 'ready';
const paired = computed(() => signal.value?.identity && props.connections.find(item => item.peerKey === signal.value!.identity!.key));
const relay = computed(() => !!signal.value && hasRelay(signal.value.sdp));
const available = computed(() => target.value === 'new' ? props.canAdd : !!target.value && idle(target.value));
const title = computed(() => failure.value ? 'Link could not be opened'
: !signal.value ? 'Opening link'
: signal.value.type === 'offer' ? 'Invitation to receive files'
: { pending: 'Delivering answer', delivered: 'Answer delivered', used: 'Answer already used', manual: 'Paste this answer in the sender’s tab' }[delivery.value]);
let token = 0;
// Prefer the slot paired with the sender's device, then the open slot, then a new one.
function suggest() {
const match = paired.value;
if (match && idle(match.id)) return match.id;
if (idle(props.current)) return props.current;
return props.canAdd ? 'new' : props.connections.find(item => idle(item.id))?.id ?? '';
}
watch(invitation, async value => {
const run = ++token;
signal.value = null; failure.value = ''; delivery.value = 'pending'; copied.value = false; copyError.value = '';
if (!value) return;
try {
// TURN consent is checked again when the slot uses the code.
const decoded = await decodeCode(value.code, { allowTurn: true });
if (run !== token) return;
signal.value = decoded;
if (decoded.type === 'offer') { target.value = suggest(); return; }
const result = await deliverAnswer(decoded.ref, value.code);
if (run === token) delivery.value = result ?? 'manual';
} catch (err) { if (run === token) failure.value = asError(err).message; }
}, { immediate: true });
function accept() {
if (!invitation.value || !available.value) return;
emit('open', target.value, invitation.value.code);
invitation.value = null;
}
async function copy() {
try { await navigator.clipboard.writeText(invitation.value?.code ?? ''); copied.value = true; copyError.value = ''; }
catch { copyError.value = 'Clipboard unavailable. Select and copy the answer manually.'; }
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
</script>
<template>
<AppDialog v-model="open" :title="title">
<template v-if="failure">
<p class="error" role="alert">{{ failure }}</p>
<p>Ask your peer for a new link or code.</p>
</template>
<p v-else-if="!signal">Reading the link…</p>
<template v-else-if="signal.type === 'offer'">
<p>Someone invited you to receive files. The invitation only works while the sender’s HellCon page stays open, for up to 5 minutes after they created it.</p>
<p v-if="!signal.identity">The sender uses a temporary identity. Compare fingerprints after connecting.</p>
<p v-else-if="paired">The sender’s device matches the paired device of {{ paired.name }}. Its fresh device proof is still checked when connecting.</p>
<p v-else>The sender’s device is not paired with any of your connections. Compare fingerprints after connecting.</p>
<p v-if="relay">This invitation uses a TURN relay. Enable TURN in Network settings before accepting it.</p>
<label class="step" for="invitation-target">Receive on</label>
<select id="invitation-target" v-model="target" class="stun-select">
<option v-for="item in connections" :key="item.id" :value="item.id" :disabled="!idle(item.id)">
{{ item.name }}{{ item.id === paired?.id ? ' · paired device' : '' }}{{ idle(item.id) ? '' : ' · in use' }}
</option>
<option value="new" :disabled="!canAdd">New connection</option>
</select>
<p v-if="!available" class="error">Choose a connection that is not in use.</p>
<p>Nothing is sent until you press <strong>Accept &amp; create answer</strong>. The answer contains your IP address.</p>
</template>
<template v-else>
<p v-if="delivery === 'pending'">Looking for the sender’s HellCon tab in this browser…</p>
<p v-else-if="delivery === 'delivered'">The sender’s HellCon tab received this answer. Switch back to it to finish connecting; you can close this tab.</p>
<p v-else-if="delivery === 'used'">The sender’s tab already used this answer. Switch back to it, or ask for a new answer if connecting failed.</p>
<template v-else>
<p>No HellCon tab in this browser is waiting for this answer. Copy it and paste it into the sender’s tab, for example in your usual browser if the link opened inside a messenger. It only works for up to 5 minutes after the code was created.</p>
<label class="step" for="invitation-answer">Answer</label>
<textarea id="invitation-answer" :value="invitation?.code" readonly @focus="selectCode" />
<p v-if="copyError" class="error" role="alert">{{ copyError }}</p>
</template>
</template>
<template #actions="{ close }">
<template v-if="signal?.type === 'offer'">
<button @click="close">Cancel</button>
<button class="primary" :disabled="!available" @click="accept">Open</button>
</template>
<template v-else-if="signal?.type === 'answer' && delivery === 'manual'">
<button @click="close">Close</button>
<button class="primary" @click="copy">{{ copied ? 'Copied!' : 'Copy answer' }}</button>
</template>
<button v-else @click="close">Close</button>
</template>
</AppDialog>
</template>
+56 -19
View File
@@ -2,12 +2,13 @@
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, onBeforeUnmount, ref, watch } from 'vue';
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 { createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.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';
@@ -28,6 +29,8 @@ interface Session {
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>;
}
@@ -50,7 +53,7 @@ const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
const error = ref('');
const copied = ref(false);
const copied = ref<'' | 'link' | 'code'>('');
const fps = ref<Fingerprints | null>(null);
const verified = ref(false);
const progress = ref(0);
@@ -60,13 +63,22 @@ 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' });
}
defineExpose({ focusDirection });
// 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);
@@ -76,6 +88,9 @@ 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(() => {
@@ -92,8 +107,8 @@ 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.',
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
'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.',
@@ -124,6 +139,7 @@ function dispose() {
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());
@@ -141,7 +157,7 @@ function reset(keepNetwork = false) {
inputCode.value = outputCode.value = error.value = '';
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false;
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;
}
@@ -307,6 +323,12 @@ async function createCode() {
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'; }
@@ -401,14 +423,19 @@ async function acceptFile() {
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() {
async function copy(kind: 'link' | 'code') {
const session = active;
try {
await navigator.clipboard.writeText(outputCode.value);
await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value);
if (active !== session) return;
copied.value = true; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
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';
@@ -419,7 +446,7 @@ function formatBytes(bytes: number) {
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement) event.target.select();
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) event.target.select();
}
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script>
@@ -444,19 +471,29 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<summary>Network settings</summary>
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
</details>
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
<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 connection code</label>
<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 class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<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-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<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>
<label class="step" for="output-code">{{ sending ? 'Connection code' : 'Answer code' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
<button @click="copy('code')">{{ copied === 'code' ? 'Copied!' : 'Copy code' }}</button>
</details>
</template>
<template v-if="sending && outputCode">
<label class="step" for="answer-input">Paste the receiver’s answer</label>
<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>
</template>
+43
View File
@@ -0,0 +1,43 @@
import { CODE_PREFIX } from './codes.ts';
import { isRecord } from './validation.ts';
// Invitation links carry a code in the fragment, which browsers never send to
// the host. Answers opened in another tab reach the waiting sender over a
// same-origin BroadcastChannel; pasting stays the fallback.
const CHANNEL = 'hellcon-answers';
export type Delivery = 'delivered' | 'used';
// Returns a code from the URL fragment and removes it from the address bar.
// Other fragments, such as the skip link's, are left alone.
export function takeFragment() {
const code = location.hash.slice(1);
if (!code.startsWith(CODE_PREFIX)) return '';
history.replaceState(history.state, '', location.href.split('#')[0]);
return code;
}
// Resolves null when no waiting tab answers in time, for example in a
// messenger's in-app browser or another browser.
export function deliverAnswer(ref: string, code: string, timeout = 1000): Promise<Delivery | null> {
if (typeof BroadcastChannel === 'undefined') return Promise.resolve(null);
const channel = new BroadcastChannel(CHANNEL), id = crypto.randomUUID();
return new Promise(resolve => {
const done = (result: Delivery | null) => { clearTimeout(timer); channel.close(); resolve(result); };
const timer = setTimeout(() => done(null), timeout);
channel.onmessage = ({ data }: MessageEvent) => {
if (isRecord(data) && data.kind === 'ack' && data.id === id && (data.status === 'delivered' || data.status === 'used')) done(data.status);
};
channel.postMessage({ kind: 'answer', id, ref, code });
});
}
// `receive` returns false when the offer no longer waits for an answer.
export function listenForAnswers(ref: string, receive: (code: string) => boolean) {
if (typeof BroadcastChannel === 'undefined') return () => {};
const channel = new BroadcastChannel(CHANNEL);
channel.onmessage = ({ data }: MessageEvent) => {
if (!isRecord(data) || data.kind !== 'answer' || data.ref !== ref || typeof data.id !== 'string' || typeof data.code !== 'string') return;
channel.postMessage({ kind: 'ack', id: data.id, status: receive(data.code) ? 'delivered' : 'used' });
};
return () => channel.close();
}
+5 -1
View File
@@ -104,6 +104,10 @@ export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: Wai
});
}
export function hasRelay(sdp: string) {
return sdp.split(/\r?\n/).some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line));
}
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
throw new Error('Invalid connection description.');
@@ -118,7 +122,7 @@ export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<Ic
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
throw new Error('A single full SHA-256 fingerprint is required.');
}
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
if (!allowTurn && hasRelay(sdp)) {
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
}
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
+3 -1
View File
@@ -1,5 +1,7 @@
import { createApp } from 'vue';
import App from './App.vue';
import { takeFragment } from './lib/invitations.ts';
import './style.css';
createApp(App).mount('#app');
// Read and clear an invitation fragment before anything else can see the URL.
createApp(App, { initialCode: takeFragment() }).mount('#app');
+3
View File
@@ -321,6 +321,9 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
input[type=file] { max-width: 100%; font-size: 0.8rem; }
input[type=file]::file-selector-button { border: 1px solid #505667; border-radius: 6px; padding: 0.45rem 0.65rem; margin-right: 0.6rem; background: #242a36; color: var(--text); cursor: pointer; }
.network-details > fieldset { margin-top: 0.65rem; }
.share-actions { display: flex; flex-wrap: wrap; gap: 0.6rem; }
.share-actions button { font-size: 0.88rem; }
.code-details[open] { display: flex; flex-direction: column; align-items: start; gap: 0.6rem; }
.activity-panel { min-width: 0; border-left: 1px solid var(--border); padding-left: 1.5rem; }
.activity-heading { display: flex; align-items: center; gap: 0.6rem; }
.activity-heading h2 { font-size: 0.9rem; font-weight: 600; margin: 0; }
+39
View File
@@ -0,0 +1,39 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deliverAnswer, listenForAnswers, takeFragment } from '../src/lib/invitations.ts';
test('answers reach the waiting offer once and report later deliveries as used', async () => {
let waiting = true;
const received: string[] = [];
const stop = listenForAnswers('ref-a', code => {
if (!waiting) return false;
waiting = false; received.push(code);
return true;
});
const other = listenForAnswers('ref-b', () => assert.fail('another offer must ignore this answer'));
try {
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'delivered');
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'used');
assert.deepEqual(received, ['HC1.answer']);
} finally { stop(); other(); }
});
test('answers without a waiting tab fall back to manual pasting', async () => {
assert.equal(await deliverAnswer('nobody', 'HC1.answer', 50), null);
const stop = listenForAnswers('ref-a', () => true);
stop();
assert.equal(await deliverAnswer('ref-a', 'HC1.answer', 50), null);
});
test('only code fragments are taken from the URL', () => {
const replaced: string[] = [];
const url = { href: 'https://example.test/app/?x=1#HC1.abc', hash: '#HC1.abc' };
Object.assign(globalThis, { location: url, history: { state: null, replaceState: (_: unknown, __: string, next: string) => replaced.push(next) } });
try {
assert.equal(takeFragment(), 'HC1.abc');
assert.deepEqual(replaced, ['https://example.test/app/?x=1']);
Object.assign(url, { href: 'https://example.test/app/#main-content', hash: '#main-content' });
assert.equal(takeFragment(), '');
assert.equal(replaced.length, 1);
} finally { Reflect.deleteProperty(globalThis, 'location'); Reflect.deleteProperty(globalThis, 'history'); }
});