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

+2 -9
View File
@@ -21,13 +21,6 @@
- **Disconnect**, which aborts unfinished writes, and Send/Receive navigation - **Disconnect**, which aborts unfinished writes, and Send/Receive navigation
within a live session. The initial receiver can send files without within a live session. The initial receiver can send files without
reconnecting. reconnecting.
- 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.
- The hosted-first, serverless [UX roadmap](docs/ux-roadmap.md). - The hosted-first, serverless [UX roadmap](docs/ux-roadmap.md).
### Changed ### Changed
@@ -38,8 +31,8 @@
Base64url of deflated JSON). Each code states whether it is an offer or an Base64url of deflated JSON). Each code states whether it is an offer or an
answer and carries a reference shared by both, so a pasted offer in the answer and carries a reference shared by both, so a pasted offer in the
answer field, or an answer to a different code, is rejected with a clear answer field, or an answer to a different code, is rejected with a clear
message while the live offer stays valid. Codes may be pasted as part of a message while the live offer stays valid. Codes from earlier 0.0.5 drafts are
link. Codes from earlier 0.0.5 drafts are rejected. rejected.
- Replace the receive-storage choice with a single **Accept file** button that - Replace the receive-storage choice with a single **Accept file** button that
treats every file size the same: stream to Downloads where supported, else treats every file size the same: stream to Downloads where supported, else
use the native save picker, else buffer up to 64 MiB in memory and hand it use the native save picker, else buffer up to 64 MiB in memory and hand it
+9 -20
View File
@@ -4,8 +4,8 @@ Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for releas
notes and compatibility changes. notes and compatibility changes.
Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts, no Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts, no
signaling backend, and no server-side file storage: you exchange invitation links signaling backend, and no server-side file storage: you exchange connection codes
or connection codes yourself, through any messenger. Connections are direct by yourself, through any messenger. Connections are direct by
default. A TURN relay is used only when both people opt in. default. A TURN relay is used only when both people opt in.
This is experimental software, not independently audited or battle-tested. This is experimental software, not independently audited or battle-tested.
@@ -40,16 +40,12 @@ so and temporary sessions still work.
1. **Create a code.** The person starting picks one or more files, chooses a 1. **Create a code.** The person starting picks one or more files, chooses a
STUN provider (PageQuit by default, Google, Cloudflare, custom, or None), and STUN provider (PageQuit by default, Google, Cloudflare, custom, or None), and
clicks **Create code**. They send the link privately to the receiver through clicks **Create code**. They send the code privately to the receiver through
an authenticated channel, with **Share link** where supported or **Copy an authenticated channel.
link**. The bare code is under **Show code instead**. 2. **Answer it.** The receiver pastes the code and clicks **Accept & create
2. **Answer it.** The receiver opens the link or pastes the link or code. An answer**, then sends the answer back for the sender to paste. Gathering waits
opened link shows a preview and lets them pick which connection receives it; up to 30 seconds and fails rather than exporting incomplete connection
nothing is sent until they click **Accept & create answer**. They send the information.
answer link back. Opened in the browser that holds the sender's tab, it
connects that tab directly; elsewhere it shows the answer for the sender to
paste. Gathering waits up to 30 seconds and fails rather than exporting
incomplete connection information.
3. **Compare fingerprints.** Both people compare **both full SHA-256 certificate 3. **Compare fingerprints.** Both people compare **both full SHA-256 certificate
fingerprints** over a channel they trust for authenticity, such as in person. fingerprints** over a channel they trust for authenticity, such as in person.
Your fingerprint must equal their “Their fingerprint”, and vice versa. Compare Your fingerprint must equal their “Their fingerprint”, and vice versa. Compare
@@ -141,7 +137,7 @@ malicious host. See [the identity protocol and storage](docs/device-identities.m
## Privacy and security ## Privacy and security
### Codes and links ### Connection codes
Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.` Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.`
followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE
@@ -150,13 +146,6 @@ messaging service, may learn these details. Treat codes as private and do not
publish them. The browser may obscure local addresses, but this app does not publish them. The browser may obscure local addresses, but this app does not
provide anonymity. provide anonymity.
Invitation links carry the code after `#`. Browsers do not send this fragment to
the host, and the app removes it from the address bar on opening. Otherwise a
link is as sensitive as its code; 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`. See [the invitation
design](docs/invitations.md).
File transfers use protocol **v3**; codes from older builds are rejected before File transfers use protocol **v3**; codes from older builds are rejected before
connecting. connecting.
-128
View File
@@ -1,128 +0,0 @@
# 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
returns as a link as well. Pasteable codes remain the universal fallback. No
server, storage service or new dependency is involved; Vue remains the only
runtime dependency.
## Why the fragment
The code travels after `#`. Browsers never send the fragment in HTTP requests or
`Referer` headers, so the app host, its service worker, proxies and network
observers do not receive it. Over HTTPS, an observer sees the hostname and IP
addresses only, as today.
Everyone the link is shared with sees it: the recipient, the messenger and, for
messengers without end-to-end encryption, their servers. That is the same
exposure as a pasted code. Browser history, including synced history, may keep
the full URL even after the app clears it; this is the one addition compared with
pasting. Codes are not secrets and stop working when the session ends, but they
contain IP addresses. Fingerprint comparison and device proofs, not code secrecy,
prevent a leaked or substituted code from being used for interception.
## Code format
Measured in headless Chromium (2 host candidates, 1 with STUN): current codes are
1.0–1.5 KB; deflated and base64url-encoded they are 650–780 characters, including
a v4 identity. More interfaces and TURN candidates grow both; a code stays well
below 2 KB in typical cases.
One encoding serves codes and links: a versioned prefix followed by base64url of
`deflate-raw`-compressed JSON (native `CompressionStream`). The JSON keeps the
existing session versions (3 temporary, 4 with identity) and adds:
- `type`: `offer` or `answer`. Pasting an offer into the answer field, or the
reverse, fails with a clear message instead of an SDP error.
- `ref`: 16 random bytes chosen by the offerer and echoed by the answerer. An
answer for a different offer is rejected before it reaches the peer connection.
It also addresses answer links to the waiting tab (see below).
Decoding bounds the compressed input and stops decompression once the output
exceeds `MAX_SIGNAL_LENGTH`, so a small hostile link cannot expand without limit.
Decoding becomes asynchronous: parse once into a validated structure
(`type`, `ref`, `sdp`, `identity`) and pass that around instead of re-decoding
text in `TransferPanel`. 0.0.5 is unreleased and already incompatible with 0.0.4,
so no legacy encoding is accepted; a recognizable old code reports that both
people need the current version.
A link is the current app URL (from `location`, so any self-hosted path works)
with the code as its fragment. Every code field accepts either a bare code or a
full link and uses the part after `#`. A link from another HellCon host can be
pasted into one's own instance; opening it directly would use that host's
origin, without one's saved connections and identity.
## Receiving an invitation
`main.ts` reads the fragment before mounting, removes it with
`history.replaceState`, and hands it to the app; `hashchange` covers a link
pasted into an already open tab. Invalid fragments show an error and are
discarded the same way.
An offer opens an import dialog. It never creates an answer automatically,
because answering reveals the receiver's addresses to whoever made the link.
The dialog shows:
- that this is an invitation to receive files and that it only works while the
sender's page is waiting (setup times out after 5 minutes);
- the device status: no identity, a new device, or a key matching a slot's paired
device. A match is a suggestion; the fresh device proof still decides;
- whether the code contains a TURN relay, which requires the receiver's explicit
TURN opt-in as today;
- a slot selector: the matching paired slot if idle, otherwise the current slot
if idle, otherwise **New connection**. Busy slots are unavailable.
**Open** selects the slot, switches it to Receive, fills the code and focuses
**Accept & create answer**. Network settings and identity behave as for a pasted
code.
## Returning the answer
The answer is shared as a link too. Opened from a messenger it lands in a new tab,
but the sender's offer lives only in memory in the original tab. The new tab
posts `{ ref, code }` on a `BroadcastChannel`. A panel waiting in `offer-ready`
with that `ref` acknowledges and applies the answer as if Connect had been
pressed; fingerprint comparison or the device proof follows as usual. A second
delivery of the same answer is acknowledged as already used.
After an acknowledgement the new tab says the answer was delivered and the user
can switch back; pages cannot focus another tab. Without an acknowledgement
within about a second, for example in a messenger's in-app browser with separate
storage or in another browser, it shows the answer with **Copy** and explains
where to paste it. The channel is same-origin; other sites cannot post to it.
## Sharing UI
Where `navigator.share` accepts a URL, offer **Share link**; always offer
**Copy link**, with the bare code in a collapsed section. The privacy note says
that a link is as sensitive as a code, may remain in browser history, and should
be sent privately. Status texts name the 5-minute limit while waiting.
QR codes stay deferred. Measured sizes fit a QR code, but generating one needs a
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.
2. Switch signaling to the parsed structure; keep existing webrtc/session tests
green and add `ref` validation in `useAnswer`.
3. Fragment intake, import dialog and slot selection through `App` →
`ConnectionWorkspace` → `TransferPanel`.
4. Answer relay and fallback; Share/Copy link UI.
5. Browser check: offer link in a second page shows the dialog and a clean URL;
accepting it and opening the answer link in a third page connects the sender's
tab; exact bytes transfer. Repeat the answer link in a separate browser context
for the fallback. Run axe on the dialog.
6. Manually verify on phones with at least two messengers: link length intact,
preview fetches without the fragment, in-app browser behaviour, Web Share.
7. Update README, CHANGELOG and the roadmap.
The shorter encoding also reduces the payload the planned
[tracker reconnect](webtorrent-reconnect.md) carries.
+7 -13
View File
@@ -86,23 +86,17 @@ storage denial/recovery, and protocol-version validation. Design and review note
are in [the device identity protocol](device-identities.md); this is not an are in [the device identity protocol](device-identities.md); this is not an
independent cryptographic audit. independent cryptographic audit.
## 4. Shareable invitations — implemented ## 4. Compressed connection codes — implemented
Detailed in [the invitation design](invitations.md). Offers and answers are compressed `HC1.` codes that state their type and share a
reference, so mixed-up or stale codes are rejected with a specific message.
Offers and answers are shared as links with the compressed code in the URL Shareable invitation links were built on top and removed again: they did not make
fragment, through **Share link** where supported or **Copy link**; the bare code real-world connections more reliable. An optional signaling backend is the
stays available. Opening a link clears the fragment. An offer opens an import intended way to simplify the exchange.
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.
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 ## 5. Guided connection flow
Present one primary next action across Choose files → Share invitation → Connect Present one primary next action across Choose files → Share code → Connect
→ Verify → Transfer. Collapse completed setup steps, expose advanced network → Verify → Transfer. Collapse completed setup steps, expose advanced network
settings on demand, and keep relay consent explicit. Show session state separately settings on demand, and keep relay consent explicit. Show session state separately
from file progress. Distinguish connected, awaiting acceptance, saving, completed, from file progress. Distinguish connected, awaiting acceptance, saving, completed,
+1 -98
View File
@@ -49,7 +49,6 @@ interface ProtocolResults {
'Browser.setDownloadBehavior': object; 'Browser.setDownloadBehavior': object;
'Target.createTarget': { targetId: string }; 'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string }; 'Target.attachToTarget': { sessionId: string };
'Target.closeTarget': object;
'Runtime.enable': object; 'Runtime.enable': object;
'Page.enable': object; 'Page.enable': object;
'Page.navigate': object; 'Page.navigate': object;
@@ -100,11 +99,9 @@ async function wait(session: string, check: () => unknown) {
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session); const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails)); if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
} }
const targets = new Map<string, string>();
async function page(url = origin) { async function page(url = origin) {
const { targetId } = await call('Target.createTarget', { url: 'about:blank' }); const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true }); const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
targets.set(sessionId, targetId);
await call('Runtime.enable', {}, sessionId); await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId); await call('Page.enable', {}, sessionId);
// Background tabs otherwise skip focus/blur events, which the name editor relies on. // Background tabs otherwise skip focus/blur events, which the name editor relies on.
@@ -117,8 +114,7 @@ async function page(url = origin) {
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId); if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url }, sessionId); await call('Page.navigate', { url }, sessionId);
for (let n = 0; n < 100; n++) { for (let n = 0; n < 100; n++) {
// The app removes invitation fragments from the address bar. try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url)) break; }
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; } catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20)); await new Promise(resolve => setTimeout(resolve, 20));
} }
@@ -143,7 +139,6 @@ const screenshot = async (session: string, name: string) => {
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session); const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64')); 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 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 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 input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value);
@@ -151,30 +146,12 @@ const enableTurn = (session: string) => evaluate(session, () => {
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input'); const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
if (!checkbox.checked) checkbox.click(); if (!checkbox.checked) checkbox.click();
}); });
let checkedCodeLayout = false;
async function connect(sender: string, receiver: string, size: number, changedIdentity = false) { async function connect(sender: string, receiver: string, size: number, changedIdentity = false) {
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size); await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
await input(sender, '#stun-provider', provider); await input(sender, '#stun-provider', provider);
await input(receiver, '#stun-provider', provider); await input(receiver, '#stun-provider', provider);
if (turn) { await enableTurn(sender); await enableTurn(receiver); } if (turn) { await enableTurn(sender); await enableTurn(receiver); }
await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code')); await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code'));
if (!checkedCodeLayout) {
const layout = await evaluate(sender, () => {
const details = window.__hellcon.element<HTMLDetailsElement>('.code-details');
const closedByDefault = !details.open;
details.open = true;
const code = window.__hellcon.element<HTMLTextAreaElement>('#output-code').getBoundingClientRect();
const copy = window.__hellcon.element<HTMLButtonElement>('.code-entry button').getBoundingClientRect();
const answer = window.__hellcon.element<HTMLTextAreaElement>('#answer-input').getBoundingClientRect();
const connect = window.__hellcon.element<HTMLButtonElement>('#answer-input + button').getBoundingClientRect();
details.open = false;
return { closedByDefault, codeGap: copy.top - code.bottom, answerGap: connect.top - answer.bottom, codeWidth: code.width, answerWidth: answer.width };
});
assert.equal(layout.closedByDefault, true, 'Code alternative starts collapsed');
assert.ok(Math.abs(layout.codeGap - layout.answerGap) < 1, 'Code and answer buttons have matching spacing');
assert.ok(Math.abs(layout.codeWidth - layout.answerWidth) < 1, 'Code and answer fields have matching width');
checkedCodeLayout = true;
}
const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.ok(offer.startsWith(CODE_PREFIX)); assert.ok(offer.startsWith(CODE_PREFIX));
await input(receiver, '#offer-input', 'invalid-code!'); await input(receiver, '#offer-input', 'invalid-code!');
@@ -564,62 +541,6 @@ try {
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); 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.'); console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (!turn) { if (!turn) {
// Invitation links: the offer opens a dialog in a fresh page, the answer link
// reaches the sender's tab, and other origins fall back to copy and paste.
const inviter = await page();
await evaluate(inviter, () => window.__hellcon.chooseFile(3000, 'invited.bin'));
await input(inviter, '#stun-provider', provider);
await click(inviter, 'Create code'); await wait(inviter, () => !!document.querySelector('#output-link'));
const offerLink = await evaluate(inviter, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const offerCode = await evaluate(inviter, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(offerLink, `${origin}/#${offerCode}`);
const invited = await page(offerLink);
await wait(invited, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files'));
assert.equal(await evaluate(invited, () => location.href), `${origin}/`);
assert.match(await dialogText(invited), /temporary identity/);
await checkAccessibility(invited, 'Invitation dialog');
if (screenshotDirectory) await evaluate(inviter, () => window.__hellcon.element('#output-link').scrollIntoView({ block: 'center' }));
await screenshot(inviter, 'invitation-share');
await screenshot(invited, 'invitation-offer');
await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, invited);
assert.equal(await evaluate(invited, () => document.documentElement.scrollWidth <= innerWidth), true, 'Invitation dialog must not overflow horizontally');
await screenshot(invited, 'invitation-offer-mobile');
await click(invited, 'Open'); await wait(invited, () => !document.querySelector('dialog[open]'));
await wait(invited, () => document.activeElement?.textContent === 'Accept & create answer');
assert.equal(await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offerCode);
assert.equal(await evaluate(invited, () => window.__hellcon.element('.tabs button[aria-pressed=true]').textContent), 'Receive');
await input(invited, '#stun-provider', provider);
await click(invited, 'Accept & create answer'); await wait(invited, () => !!document.querySelector('#output-link'));
const answerLink = await evaluate(invited, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const answerCode = await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
const elsewhere = await page(answerLink.replace('127.0.0.1', 'localhost'));
await wait(elsewhere, () => document.querySelector('dialog[open]')?.textContent?.includes('Paste this answer in the sender’s tab'));
assert.equal(await evaluate(elsewhere, () => window.__hellcon.element<HTMLTextAreaElement>('#invitation-answer').value), answerCode);
await checkAccessibility(elsewhere, 'Answer fallback dialog');
await screenshot(elsewhere, 'invitation-answer-fallback');
assert.equal(await evaluate(inviter, () => !!document.querySelector('.fingerprint')), false);
const relay = await page(answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer delivered'));
await wait(inviter, () => !!document.querySelector('.fingerprint'));
await evaluate(relay, (link: string) => { location.hash = link.split('#')[1]!; }, answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer already used'));
assert.equal(await evaluate(relay, () => location.hash), '');
await click(relay, 'Close');
await evaluate(relay, () => { location.hash = 'HC1.not-a-code'; });
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Link could not be opened'));
await click(inviter, 'Both fingerprints match — confirm'); await click(invited, 'Both fingerprints match — confirm');
await wait(invited, () => !!document.querySelector('.incoming'));
await click(invited, 'Accept file');
await wait(inviter, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
const invitedBytes = await evaluate(invited, async () => {
const link = window.__hellcon.element<HTMLAnchorElement>('a.download');
const bytes = new Uint8Array(await (await fetch(link.href)).arrayBuffer());
return { name: link.download, length: bytes.length, valid: bytes.every(byte => byte === 123) };
});
assert.deepEqual(invitedBytes, { name: 'invited.bin', length: 3000, valid: true });
for (const session of [inviter, invited, elsewhere, relay]) await closePage(session);
console.log('PASS: offer links open a reviewed import with a clean URL; answer links connect the waiting tab once, fall back to copy and paste elsewhere, and transfer exact bytes.');
const identitySender = await page(); const identitySender = await page();
const receiverOrigin = origin.replace('127.0.0.1', 'localhost'); const receiverOrigin = origin.replace('127.0.0.1', 'localhost');
const identityReceiver = await page(receiverOrigin); const identityReceiver = await page(receiverOrigin);
@@ -665,24 +586,6 @@ try {
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code')); await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.ok((await decodeCode(offer)).identity); assert.ok((await decodeCode(offer)).identity);
// Another receiver tab whose current slot is a new one: the invitation still
// suggests the slot paired with the sender's device, and Open hands it there.
const invitedPaired = await page(receiverOrigin);
await click(invitedPaired, 'Add connection');
await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
await evaluate(invitedPaired, (code: string) => { location.hash = code; }, offer);
await wait(invitedPaired, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files'));
assert.match(await dialogText(invitedPaired), /matches the paired device of Con 1/);
assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element<HTMLSelectElement>('#invitation-target').selectedOptions[0]?.textContent?.trim()), 'Con 1 · paired device');
await click(invitedPaired, 'Open'); await wait(invitedPaired, () => !document.querySelector('dialog[open]'));
assert.equal(await evaluate(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1');
assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offer);
await evaluate(invitedPaired, () => [...document.querySelectorAll<HTMLElement>('.connection-name')].find(item => item.textContent === 'Con 2')?.click());
await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
await click(invitedPaired, 'Remove Con 2'); await click(invitedPaired, 'Remove connection');
await wait(invitedPaired, () => document.querySelectorAll('.connection-link').length === 1);
await closePage(invitedPaired);
console.log('PASS: an invitation from a paired device suggests its slot over the current one and hands the code to it.');
await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer'); await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer');
await wait(identityReceiver, () => !!document.querySelector('#output-code')); await wait(identityReceiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
+4 -29
View File
@@ -2,14 +2,9 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'; import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue'; import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.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 { 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'; 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 logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`;
const giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`; const giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`;
const connections = ref<SavedConnection[]>([]), selected = ref(''); 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 removalTarget = computed(() => connections.value.find(item => item.id === removalId.value));
const error = ref(''), removalError = ref(''); const error = ref(''), removalError = ref('');
const heading = ref<HTMLElement | null>(null); 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 persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
let updates: BroadcastChannel | undefined; let updates: BroadcastChannel | undefined;
function select(id: string) { function select(id: string) {
@@ -81,15 +72,8 @@ onMounted(async () => {
updates.onmessage = () => { void refresh(); }; updates.onmessage = () => { void refresh(); };
} }
window.addEventListener('focus', 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); }); onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
// A link opened in an existing tab only changes the fragment.
function openLink() {
const code = takeFragment();
if (code) invitation.value = { code };
}
async function add() { async function add() {
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return; if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
adding.value = true; adding.value = true;
@@ -97,18 +81,10 @@ async function add() {
await writes; await writes;
if (persistent) connections.value = await addConnection(); if (persistent) connections.value = await addConnection();
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1)); else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
const id = connections.value.at(-1)!.id; select(connections.value.at(-1)!.id); updates?.postMessage('changed');
select(id); updates?.postMessage('changed');
return id;
} catch (err) { error.value = asError(err).message; } } catch (err) { error.value = asError(err).message; }
finally { adding.value = false; } 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) { function update(id: string, change: ConnectionUpdate) {
const index = connections.value.findIndex(item => item.id === id); const index = connections.value.findIndex(item => item.id === id);
if (index < 0) return; if (index < 0) return;
@@ -214,8 +190,8 @@ async function remove() {
<p v-if="error" class="storage-error" role="alert">{{ error }}</p> <p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id"> <template v-for="item in connections" :key="item.id">
<KeepAlive> <KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null" <ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust"
@status="setStatus" @update="update" @invitation-taken="handoff = null" /> @status="setStatus" @update="update" />
</KeepAlive> </KeepAlive>
</template> </template>
<p v-if="!current" class="status">Opening your connections…</p> <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> <button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
</template> </template>
</AppDialog> </AppDialog>
<InvitationDialog v-if="current" v-model="invitation" :connections="connections" :states="states" :current="current.id" :can-add="canAdd" @open="openInvitation" />
</template> </template>
+2 -13
View File
@@ -1,12 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, ref, watch } from 'vue'; import { ref } from 'vue';
import TransferPanel from './TransferPanel.vue'; import TransferPanel from './TransferPanel.vue';
import type { SavedConnection, ConnectionUpdate } from '../lib/connections.ts'; 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<{ const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected']; status: [id: string, state: 'ready' | 'connecting' | 'connected'];
update: [id: string, change: ConnectionUpdate]; update: [id: string, change: ConnectionUpdate];
invitationTaken: [];
}>(); }>();
const mode = ref<'send' | 'receive'>('send'); const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false), connected = ref(false); 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); } if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
else if (!sessionActive.value) mode.value = 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> </script>
<template> <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 { asError } from '../lib/validation.ts';
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts'; import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.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 DeviceSettings from './DeviceSettings.vue';
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts'; import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
import NetworkSettings from './NetworkSettings.vue'; import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts'; 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 { 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 { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts'; import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts'; import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
@@ -29,8 +28,6 @@ interface Session {
expected?: string; expected?: string;
// Shared by this session's offer and answer codes. // Shared by this session's offer and answer codes.
ref?: string; ref?: string;
// Stops accepting answer links from other tabs.
stopAnswers?: () => void;
timer?: ReturnType<typeof setTimeout>; timer?: ReturnType<typeof setTimeout>;
} }
@@ -53,7 +50,7 @@ const inputCode = ref('');
const outputCode = ref(''); const outputCode = ref('');
const step = ref<Step>('idle'); const step = ref<Step>('idle');
const error = ref(''); const error = ref('');
const copied = ref<'' | 'link' | 'code'>(''); const copied = ref(false);
const fps = ref<Fingerprints | null>(null); const fps = ref<Fingerprints | null>(null);
const verified = ref(false); const verified = ref(false);
const progress = ref(0); const progress = ref(0);
@@ -63,22 +60,13 @@ const downloadName = ref('');
const connected = ref(false); const connected = ref(false);
const sendSection = ref<HTMLElement | null>(null); const sendSection = ref<HTMLElement | null>(null);
const receiveSection = ref<HTMLElement | null>(null); const receiveSection = ref<HTMLElement | null>(null);
const acceptButton = ref<HTMLButtonElement | null>(null);
watch(connected, value => emit('connectedChange', value)); watch(connected, value => emit('connectedChange', value));
function focusDirection(direction: 'send' | 'receive') { function focusDirection(direction: 'send' | 'receive') {
const section = direction === 'send' ? sendSection.value : receiveSection.value; const section = direction === 'send' ? sendSection.value : receiveSection.value;
section?.focus({ preventScroll: true }); section?.focus({ preventScroll: true });
section?.scrollIntoView({ block: 'start', behavior: 'auto' }); section?.scrollIntoView({ block: 'start', behavior: 'auto' });
} }
// Fills an invitation's code without creating the answer, which would reveal defineExpose({ focusDirection });
// 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 choosing = ref(false);
const dragover = 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 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 settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
const managedCredentials = ref<IceOptions | null>(null); 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 // 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. // through the native save picker, otherwise buffered in memory (capped) and saved on completion.
const receiveMethod = computed(() => { const receiveMethod = computed(() => {
@@ -107,8 +92,8 @@ const status = computed(() => ({
'session-ready': 'Connected. Add files to send, or wait for your peer.', '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.', idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
gathering: 'Gathering connection info (up to 30 seconds)…', 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.', 'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
'answer-ready': 'Send the answer link back, then compare both full fingerprints.', '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.', 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…', 'waiting-accept': 'Waiting for the receiver to accept the file…',
'choose-storage': 'Accept or decline this file.', 'choose-storage': 'Accept or decline this file.',
@@ -139,7 +124,6 @@ function dispose() {
managedCredentials.value = null; settings.value.allowTurn = false; managedCredentials.value = null; settings.value.allowTurn = false;
if (!old) return; if (!old) return;
clearTimeout(old.timer); clearTimeout(old.timer);
old.stopAnswers?.();
// Start the snapshot before aborting/closing anything; close the peer after // Start the snapshot before aborting/closing anything; close the peer after
// stats resolve (bounded to 300 ms), so failure evidence remains available. // stats resolve (bounded to 300 ms), so failure evidence remains available.
void old.diagnostics.finish(() => old.pc.close()); void old.diagnostics.finish(() => old.pc.close());
@@ -157,7 +141,7 @@ function reset(keepNetwork = false) {
inputCode.value = outputCode.value = error.value = ''; inputCode.value = outputCode.value = error.value = '';
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false; identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
fps.value = incoming.value = null; 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; progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
sendState.value = receiveState.value = null; outgoing.value = null; sendState.value = receiveState.value = null; outgoing.value = null;
} }
@@ -318,12 +302,6 @@ async function createCode() {
void session.diagnostics.capture(); void session.diagnostics.capture();
if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); } if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); }
step.value = props.sending ? 'offer-ready' : 'answer-ready'; 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) { } catch (err) {
if (session) fail(session, err); if (session) fail(session, err);
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; } 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; 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; } } finally { if (active === session) choosing.value = false; }
} }
async function copy(kind: 'link' | 'code') { async function copy() {
const session = active; const session = active;
try { try {
await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value); await navigator.clipboard.writeText(outputCode.value);
if (active !== session) return; if (active !== session) return;
copied.value = kind; clearTimeout(copyTimer); copied.value = true; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = ''; }, 1500); copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = `Clipboard unavailable. Select and copy the ${kind} manually.`; } } catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code 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) { 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'; 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]}`; return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
} }
function selectCode(event: FocusEvent) { 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); }); onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script> </script>
@@ -466,35 +439,21 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<summary>Network settings</summary> <summary>Network settings</summary>
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" /> <NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
</details> </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"> <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" /> <textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template> </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"> <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> <label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<input id="output-link" class="stun-input" :value="outputLink" readonly @focus="selectCode" /> <textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<div class="share-actions"> <button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
<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>
</template> </template>
<template v-if="sending && outputCode"> <template v-if="sending && outputCode">
<div class="code-entry"> <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'" />
<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>
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</div>
</template> </template>
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p> <p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
<div v-if="fps" class="fingerprint"> <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 { asError, isRecord } from './validation.ts';
import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts'; import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts';
// Connection codes: "HC1." + base64url(deflate-raw(JSON)). The same text works // Connection codes: "HC1." + base64url(deflate-raw(JSON)).
// pasted or as a link fragment, which browsers never send to the app host.
// Codes carry connection details, not secrets; fingerprints authenticate peers. // Codes carry connection details, not secrets; fingerprints authenticate peers.
export const CODE_PREFIX = 'HC1.'; export const CODE_PREFIX = 'HC1.';
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH; 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; export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024; 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 { export interface Signal {
type: 'offer' | 'answer'; type: 'offer' | 'answer';
@@ -55,17 +54,6 @@ async function inflate(bytes: Uint8Array<ArrayBuffer>) {
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); } 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) { 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 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))); 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> { 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.'); 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.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
if (!code.startsWith(CODE_PREFIX)) { if (!code.startsWith(CODE_PREFIX)) {
let legacy = false; 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'> = {}) { 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)) { if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
throw new Error('Invalid connection description.'); 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])) { 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.'); 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.'); 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(':', ' '); return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
+1 -3
View File
@@ -1,7 +1,5 @@
import { createApp } from 'vue'; import { createApp } from 'vue';
import App from './App.vue'; import App from './App.vue';
import { takeFragment } from './lib/invitations.ts';
import './style.css'; import './style.css';
// Read and clear an invitation fragment before anything else can see the URL. createApp(App).mount('#app');
createApp(App, { initialCode: takeFragment() }).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; } .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] { 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; } 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); } .session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.share-actions button, .session-actions button { font-size: 0.88rem; } .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; }
.storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; } .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; } .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; } .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; }
+2 -7
View File
@@ -1,7 +1,7 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto'; import { randomBytes } from 'node:crypto';
import { CODE_PREFIX, MAX_CODE_LENGTH, MAX_INPUT_LENGTH, codeFromText, codeLink, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts'; import { CODE_PREFIX, MAX_CODE_LENGTH, MAX_INPUT_LENGTH, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts';
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':'); const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':');
const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`; const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) }; const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
@@ -24,14 +24,9 @@ test('codes round-trip both types, with and without identity', async () => {
} }
}); });
test('links, wrapped text and bare codes decode the same', async () => { test('wrapped text and bare codes decode the same', async () => {
const code = await encodeCode(offer); const code = await encodeCode(offer);
const link = codeLink(code, 'https://example.com/apps/hellcon/?x=1#old');
assert.equal(link, `https://example.com/apps/hellcon/?x=1#${code}`);
assert.equal(codeFromText(link), code);
assert.deepEqual(await decodeCode(link), offer);
assert.deepEqual(await decodeCode(` ${code.slice(0, 20)}\n${code.slice(20)} `), offer); assert.deepEqual(await decodeCode(` ${code.slice(0, 20)}\n${code.slice(20)} `), offer);
assert.deepEqual(await decodeCode('#' + code), offer);
}); });
test('expected type and ref are enforced', async () => { test('expected type and ref are enforced', async () => {
-39
View File
@@ -1,39 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deliverAnswer, listenForAnswers, takeFragment } from '../src/lib/invitations.ts';
test('answers reach the waiting offer once and report later deliveries as used', async () => {
let waiting = true;
const received: string[] = [];
const stop = listenForAnswers('ref-a', code => {
if (!waiting) return false;
waiting = false; received.push(code);
return true;
});
const other = listenForAnswers('ref-b', () => assert.fail('another offer must ignore this answer'));
try {
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'delivered');
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'used');
assert.deepEqual(received, ['HC1.answer']);
} finally { stop(); other(); }
});
test('answers without a waiting tab fall back to manual pasting', async () => {
assert.equal(await deliverAnswer('nobody', 'HC1.answer', 50), null);
const stop = listenForAnswers('ref-a', () => true);
stop();
assert.equal(await deliverAnswer('ref-a', 'HC1.answer', 50), null);
});
test('only code fragments are taken from the URL', () => {
const replaced: string[] = [];
const url = { href: 'https://example.test/app/?x=1#HC1.abc', hash: '#HC1.abc' };
Object.assign(globalThis, { location: url, history: { state: null, replaceState: (_: unknown, __: string, next: string) => replaced.push(next) } });
try {
assert.equal(takeFragment(), 'HC1.abc');
assert.deepEqual(replaced, ['https://example.test/app/?x=1']);
Object.assign(url, { href: 'https://example.test/app/#main-content', hash: '#main-content' });
assert.equal(takeFragment(), '');
assert.equal(replaced.length, 1);
} finally { Reflect.deleteProperty(globalThis, 'location'); Reflect.deleteProperty(globalThis, 'history'); }
});