Remove shareable invitation links

Codes are exchanged by copy and paste again. The URL fragment intake,
the invitation dialog, the BroadcastChannel answer relay and the Share
link / Copy link controls are gone, along with their tests, browser
check scenarios and design doc. Code fields no longer accept links.

The compressed HC1 codes with typed offers/answers and echoed refs stay.
An optional signaling backend is the intended way to simplify the
exchange instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-20 19:47:07 +02:00
1 parent f320bfb541
commit a5935a8324
16 files changed
+57 -602

No files matched your search

+4 -29
View File
@@ -2,14 +2,9 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.vue';
import InvitationDialog from './components/InvitationDialog.vue';
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, 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 giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`;
const connections = ref<SavedConnection[]>([]), selected = ref('');
@@ -22,10 +17,6 @@ let renameContainer: HTMLElement | null = null;
const removalTarget = computed(() => connections.value.find(item => item.id === removalId.value));
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) {
@@ -81,15 +72,8 @@ 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); 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 };
}
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
async function add() {
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
adding.value = true;
@@ -97,18 +81,10 @@ 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));
const id = connections.value.at(-1)!.id;
select(id); updates?.postMessage('changed');
return id;
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
} 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;
@@ -214,8 +190,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" :invitation="handoff?.connection === item.id ? handoff : null"
@status="setStatus" @update="update" @invitation-taken="handoff = null" />
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust"
@status="setStatus" @update="update" />
</KeepAlive>
</template>
<p v-if="!current" class="status">Opening your connections…</p>
@@ -231,5 +207,4 @@ 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>
+2 -13
View File
@@ -1,12 +1,11 @@
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
import { ref } from 'vue';
import TransferPanel from './TransferPanel.vue';
import type { SavedConnection, ConnectionUpdate } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; invitation?: { code: string } | null }>();
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection> }>();
const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
update: [id: string, change: ConnectionUpdate];
invitationTaken: [];
}>();
const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false), connected = ref(false);
@@ -17,16 +16,6 @@ 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 });
</script>
<template>
-110
View File
@@ -1,110 +0,0 @@
<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>
+22 -63
View File
@@ -2,13 +2,12 @@
import { asError } from '../lib/validation.ts';
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import DeviceSettings from './DeviceSettings.vue';
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { codeLink, createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.ts';
import { listenForAnswers } from '../lib/invitations.ts';
import { createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.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';
@@ -29,8 +28,6 @@ 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>;
}
@@ -53,7 +50,7 @@ const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
const error = ref('');
const copied = ref<'' | 'link' | 'code'>('');
const copied = ref(false);
const fps = ref<Fingerprints | null>(null);
const verified = ref(false);
const progress = ref(0);
@@ -63,22 +60,13 @@ const downloadName = ref('');
const connected = ref(false);
const sendSection = ref<HTMLElement | null>(null);
const receiveSection = ref<HTMLElement | null>(null);
const acceptButton = ref<HTMLButtonElement | null>(null);
watch(connected, value => emit('connectedChange', value));
function focusDirection(direction: 'send' | 'receive') {
const section = direction === 'send' ? sendSection.value : receiveSection.value;
section?.focus({ preventScroll: true });
section?.scrollIntoView({ block: 'start', behavior: 'auto' });
}
// Fills an invitation's code without creating the answer, which would reveal
// this device's addresses before the user chose to.
function importCode(code: string) {
if (busy.value || connected.value || props.sending) return;
if (step.value !== 'idle') reset();
inputCode.value = code;
void nextTick(() => acceptButton.value?.focus());
}
defineExpose({ focusDirection, importCode });
defineExpose({ focusDirection });
const choosing = ref(false);
const dragover = ref(false);
@@ -88,9 +76,6 @@ 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(() => {
@@ -107,8 +92,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 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.',
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
'answer-ready': 'Send your answer 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.',
@@ -139,7 +124,6 @@ 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());
@@ -157,7 +141,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 = choosing.value = false; copied.value = '';
verified.value = copied.value = choosing.value = false;
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
sendState.value = receiveState.value = null; outgoing.value = null;
}
@@ -318,12 +302,6 @@ 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'; }
@@ -418,19 +396,14 @@ 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(kind: 'link' | 'code') {
async function copy() {
const session = active;
try {
await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value);
await navigator.clipboard.writeText(outputCode.value);
if (active !== session) return;
copied.value = kind; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = ''; }, 1500);
} catch { if (active === session) error.value = `Clipboard unavailable. Select and copy the ${kind} manually.`; }
}
async function share() {
const session = active;
try { await navigator.share({ url: outputLink.value }); }
catch (err) { if (active === session && asError(err).name !== 'AbortError') error.value = 'Sharing failed. Copy the link instead.'; }
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.'; }
}
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';
@@ -441,7 +414,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 instanceof HTMLInputElement) event.target.select();
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script>
@@ -466,35 +439,21 @@ 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 links or codes privately. They contain your IP address and connection details.</p>
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
<template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s link or code</label>
<label class="step" for="offer-input">Paste the sender’s connection code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template>
<button ref="acceptButton" class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<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-link">{{ sending ? 'Send this link to the receiver' : 'Send this answer link back to the sender' }}</label>
<input id="output-link" class="stun-input" :value="outputLink" readonly @focus="selectCode" />
<div class="share-actions">
<button v-if="canShare" class="primary" @click="share">Share link</button>
<button @click="copy('link')">{{ copied === 'link' ? 'Copied!' : 'Copy link' }}</button>
</div>
<p class="status">A link is as sensitive as a code: send it privately. It may stay in browser history and only works while this page stays open, for up to 5 minutes.</p>
<details class="code-details">
<summary>Show code instead</summary>
<div class="code-entry">
<label class="step" for="output-code">{{ sending ? 'Connection code' : 'Answer code' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy('code')">{{ copied === 'code' ? 'Copied!' : 'Copy code' }}</button>
</div>
</details>
<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" />
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
</template>
<template v-if="sending && outputCode">
<div class="code-entry">
<label class="step" for="answer-input">Paste the receiver’s answer or answer link</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</div>
<label class="step" for="answer-input">Paste the receiver’s answer</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>
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
<div v-if="fps" class="fingerprint">
+4 -16
View File
@@ -2,15 +2,14 @@ import { parseHello, type IdentityHello } from './identity.ts';
import { asError, isRecord } from './validation.ts';
import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts';
// Connection codes: "HC1." + base64url(deflate-raw(JSON)). The same text works
// pasted or as a link fragment, which browsers never send to the app host.
// Connection codes: "HC1." + base64url(deflate-raw(JSON)).
// Codes carry connection details, not secrets; fingerprints authenticate peers.
export const CODE_PREFIX = 'HC1.';
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH;
// Pasted text may be a full link around the code.
// Pasted text may contain line breaks or other whitespace around the code.
export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024;
const INVALID = 'Invalid connection code. Paste the complete code or link.';
const INVALID = 'Invalid connection code. Paste the complete code.';
export interface Signal {
type: 'offer' | 'answer';
@@ -55,17 +54,6 @@ async function inflate(bytes: Uint8Array<ArrayBuffer>) {
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); }
// Accepts a bare code or a full link and returns the code text.
export function codeFromText(text: string) {
return text.slice(text.lastIndexOf('#') + 1).replace(/\s+/g, '');
}
export function codeLink(code: string, base: string) {
const url = new URL(base);
url.hash = code;
return url.href;
}
export async function encodeCode({ type, ref, sdp, identity }: Signal) {
const payload = identity ? { version: 4, type, ref, sdp, identity: parseHello(identity) } : { version: 3, type, ref, sdp };
const code = CODE_PREFIX + toBase64Url(await deflate(JSON.stringify(payload)));
@@ -75,7 +63,7 @@ export async function encodeCode({ type, ref, sdp, identity }: Signal) {
export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise<Signal> {
if (typeof text !== 'string' || text.length > MAX_INPUT_LENGTH) throw new Error('Connection code is too large.');
const code = codeFromText(text);
const code = text.replace(/\s+/g, '');
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
if (!code.startsWith(CODE_PREFIX)) {
let legacy = false;
-43
View File
@@ -1,43 +0,0 @@
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();
}
+1 -5
View File
@@ -104,10 +104,6 @@ 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.');
@@ -122,7 +118,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 && hasRelay(sdp)) {
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
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(':', ' ');
+1 -3
View File
@@ -1,7 +1,5 @@
import { createApp } from 'vue';
import App from './App.vue';
import { takeFragment } from './lib/invitations.ts';
import './style.css';
// Read and clear an invitation fragment before anything else can see the URL.
createApp(App, { initialCode: takeFragment() }).mount('#app');
createApp(App).mount('#app');
+2 -6
View File
@@ -329,12 +329,8 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.dropzone p { font-size: 0.85rem; line-height: 1.65; margin: 0 0 1rem; }
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; }
.share-actions, .session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.share-actions button, .session-actions button { font-size: 0.88rem; }
.code-details { width: 100%; min-width: 0; }
.code-details > .code-entry { margin-top: var(--space-md); }
.code-entry { display: flex; flex-direction: column; gap: var(--space-md); min-width: 0; }
.code-entry > button { align-self: start; font-size: 0.88rem; }
.session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.session-actions button { font-size: 0.88rem; }
.storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; }
.mobile-bar { display: none; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }