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
+422 -59

No files matched your search

+57 -20
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>
<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>