diff --git a/CHANGELOG.md b/CHANGELOG.md index 3610b5f..a4c5b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index f08eda3..bec1507 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/invitations.md b/docs/invitations.md index 62a35ec..bd5d748 100644 --- a/docs/invitations.md +++ b/docs/invitations.md @@ -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. diff --git a/docs/ux-roadmap.md b/docs/ux-roadmap.md index 2fe1e08..693a6b2 100644 --- a/docs/ux-roadmap.md +++ b/docs/ux-roadmap.md @@ -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 diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 56c70bd..550dc09 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -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(); 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('#output-link').value); + const offerCode = await evaluate(inviter, () => window.__hellcon.element('#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('#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('#output-link').value); + const answerCode = await evaluate(invited, () => window.__hellcon.element('#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('#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('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); diff --git a/src/App.vue b/src/App.vue index 3a8b3de..3ea2091 100644 --- a/src/App.vue +++ b/src/App.vue @@ -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([]), selected = ref(''); const states = ref>({}); @@ -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(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() {

Opening your connections…

@@ -170,4 +195,5 @@ async function remove() { + diff --git a/src/components/ConnectionWorkspace.vue b/src/components/ConnectionWorkspace.vue index 777ec62..c1070ee 100644 --- a/src/components/ConnectionWorkspace.vue +++ b/src/components/ConnectionWorkspace.vue @@ -1,12 +1,13 @@ + +