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:
1 parent
8bd37ac8b1
commit
43ee7f119f
14 files changed
+422
-59
No files matched your search
+29
-3
@@ -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>
|
||||
@@ -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)));
|
||||
|
||||
@@ -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 & 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>
|
||||
@@ -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>
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
<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('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>
|
||||
|
||||
@@ -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
@@ -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
@@ -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');
|
||||
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user