Compare commits

...
6 Commits
Author SHA1 Message Date
Schluffe 019267cc34 Add shareable invitation links II 2026-10-19 23:09:18 +02:00
SchluffeandClaude Opus 5.5 43ee7f119f Add shareable invitation links
Codes now travel as links with the code in the URL fragment, which the
app reads and clears before mounting (and on hashchange). An offer link
opens a preview that suggests an idle slot, preferring the one paired
with the sender's device, and only fills in the code; the user still
creates the answer. Answer links reach the waiting sender tab over a
same-origin BroadcastChannel, are acknowledged once and reported as
used afterwards, and fall back to copy and paste when no tab answers.

The panel offers Share link where the Web Share API accepts URLs, Copy
link, and the bare code under a disclosure. The browser check covers
the offer dialog, clean URL, answer relay, reuse, fallback on another
origin, an invalid fragment, axe on both dialogs and exact bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:44:15 +02:00
SchluffeandClaude Opus 5.5 8bd37ac8b1 Use compressed connection codes in the transfer panel
Offers and answers now go through the HC1 codec: the sender creates a
ref per session and the answer must echo it, so pasting an offer as the
answer or an answer for another code is rejected with a specific message
while the live offer stays usable. Pasted input may be a full link.

webrtc.ts drops its Base64 JSON signaling and exchanges validated SDP
only; identity hellos travel in the code envelope. Tests, the browser
check, compare-ice and the docs follow the new format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:35:44 +02:00
SchluffeandClaude Opus 5.5 da2999ed5d Add compressed connection code codec
Codes become "HC1." plus base64url of deflate-raw JSON with an
offer/answer type and a ref the answer echoes. Decoding accepts bare
codes or full links, validates identity and description, enforces the
expected type and ref, and bounds both input and decompressed output.
Not wired into the app yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:29:20 +02:00
SchluffeandClaude Opus 5.5 4cf2ff5211 Plan shareable invitation links
Codes move into the URL fragment, which browsers never send to the host.
A compressed, versioned encoding with offer/answer type and an echoed ref
serves both links and pasted codes. Offers open an import dialog with slot
selection; answer links reach the waiting tab over BroadcastChannel, with
copy/paste as fallback. Includes measured code sizes and acceptance checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:26:22 +02:00
SchluffeandClaude Opus 5.5 1b76c7ce01 Add exploratory peer mesh idea to the roadmap
Describe peer-relayed signaling between paired devices and multi-source
transfers from signed piece manifests as an unscheduled idea, with its
limits (open tabs only, no NAT benefit, relay sees who connects). Note in
the reconnect plan that encrypted signaling should stay independent of
the tracker transport so a data channel can carry it later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 21:16:39 +02:00
21 changed files with 906 additions and 167 deletions

No files matched your search

+13
View File
@@ -22,6 +22,13 @@
can use Send to add files without reconnecting. Disconnect can use Send to add files without reconnecting. Disconnect
aborts unfinished writes while preserving the last completed memory download. aborts unfinished writes while preserving the last completed memory download.
- Document the hosted-first, serverless UX roadmap. - 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 ### Changed
@@ -32,6 +39,12 @@
longer read. longer read.
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers - Upgrade connection/session framing to v3 with per-file identifiers. Both peers
must update; v2 codes are rejected before connection setup. must update; v2 codes are rejected before connection setup.
- Connection codes are compressed to roughly half their length (`HC1.` plus
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 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
link. Earlier 0.0.5 drafts' codes are rejected.
- New device identity private keys are non-extractable. - New device identity private keys are non-extractable.
- 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
+32 -15
View File
@@ -4,7 +4,8 @@ Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for releas
and compatibility changes. and compatibility changes.
Browser-to-browser file sharing with Vue 3 and WebRTC. No accounts, signaling 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 Direct connections are the default. TURN relaying is optional and requires
explicit opt-in by both people; no relay is configured automatically. 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 ## How it works
1. The person starting the connection selects one or more files and configures STUN (PageQuit by default, Google, 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 Cloudflare, a custom provider, or None). They create a code and send it as a
privately to the intended receiver through an authenticated channel. Normal link (**Share link** where the browser supports it, or **Copy link**)
messenger copy/paste is supported; there is no need to transcribe codes. privately to the intended receiver through an authenticated channel. The bare
2. The receiver pastes the code, creates an answer, and sends it back. The sender code remains available under **Show code instead**; there is no need to
pastes the answer. Gathering waits for completion, up to 30 seconds; a timeout transcribe either.
fails rather than quietly exporting incomplete connection information. 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 3. **Both people compare both full SHA-256 certificate fingerprints** over a
channel whose authenticity and integrity they trust, such as in person. channel whose authenticity and integrity they trust, such as in person.
Your fingerprint must equal their “Their fingerprint”, and vice versa. Your fingerprint must equal their “Their fingerprint”, and vice versa.
@@ -92,8 +99,9 @@ Keep both tabs open. Switching browser tabs or apps does not explicitly cancel
the session, although browsers and mobile operating systems can suspend pages. the session, although browsers and mobile operating systems can suspend pages.
Pending verification/acceptance expires after five minutes; stalled transfers Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. Idle verified sessions stay open. Lost connections need expire after one minute. Idle verified sessions stay open. Lost connections need
fresh codes. File transfers use protocol **v3**; pre-v3 connection codes are fresh codes. File transfers use protocol **v3**; codes from older builds are
rejected before connecting. rejected before connecting. Pasting the wrong kind of code (an offer as answer,
or an answer for a different code) is reported without discarding a live offer.
If an answer is rejected as invalid, correct the pasted answer and click Connect If an answer is rejected as invalid, correct the pasted answer and click Connect
again; the sender keeps its existing offer while it is still awaiting an answer. again; the sender keeps its existing offer while it is still awaiting an answer.
@@ -160,12 +168,21 @@ avoids contacting a configured STUN provider; direct connectivity depends on
addresses, routing, browser policy and firewalls, not simply whether peers share addresses, routing, browser policy and firewalls, not simply whether peers share
one network. A VPN is not automatically a guarantee against address disclosure. one network. A VPN is not automatically a guarantee against address disclosure.
Connection codes are **Base64-encoded, not encrypted**. They contain SDP, Connection codes are **compressed and Base64url-encoded, not encrypted**
including candidate addresses, temporary ICE credentials and certificate (`HC1.` followed by deflated JSON). They contain SDP, including candidate
fingerprints. Peers and anyone who sees these codes (including the messaging addresses, temporary ICE credentials and certificate fingerprints. Peers and
service used to exchange them) may learn connection details. Local addresses may anyone who sees these codes (including the messaging service used to exchange
be obscured by the browser, but this app does not provide anonymity. Treat codes them) may learn connection details. Local addresses may be obscured by the
as private session information; do not publish them. 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 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 TURN retry. To permit a relay, both people must explicitly check **Allow a TURN
+4 -3
View File
@@ -7,9 +7,10 @@ independent cryptographic audit.
## Authentication transcript ## Authentication transcript
A device has an ECDSA P-256 key pair. An identity-enabled connection code uses A device has an ECDSA P-256 key pair. An identity-enabled connection code
signaling envelope version 4 with a public key (65-byte uncompressed point, (see `src/lib/codes.ts` for the `HC1.` encoding) uses signaling envelope
lowercase hex) and a fresh 32-byte cryptographically random nonce. Both local version 4 with a public key (65-byte uncompressed point, lowercase hex) and a
fresh 32-byte cryptographically random nonce. Both local
and remote SDP fingerprints continue to be validated as full SHA-256 values. and remote SDP fingerprints continue to be validated as full SHA-256 values.
Temporary codes use version 3. Old builds reject version 4 before connecting. Temporary codes use version 3. Old builds reject version 4 before connecting.
Current builds accept both; if either participant uses a temporary identity, Current builds accept both; if either participant uses a temporary identity,
+128
View File
@@ -0,0 +1,128 @@
# 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.
+41 -11
View File
@@ -88,19 +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 are in [the device identity protocol](device-identities.md); this is not an
independent cryptographic audit. independent cryptographic audit.
## 4. Shareable invitations ## 4. Shareable invitations — implemented
For HTTPS, encode fresh offers in URL fragments with an explicit Share/Copy link Detailed in [the invitation design](invitations.md).
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.
Bound and validate payloads, handle stale/incompatible links, and test practical Offers and answers are shared as links with the compressed code in the URL
URL limits across messengers and mobile browsers. Do not promise a short link fragment, through **Share link** where supported or **Copy link**; the bare code
without a storage service. Consider compressed payloads and QR only after checking stays available. Opening a link clears the fragment. An offer opens an import
real payload sizes and decoding limits. 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
@@ -123,3 +123,33 @@ phase. Small contextual UI improvements can accompany each phase. Treat identity
authentication and bidirectional framing as explicit design/review milestones. authentication and bidirectional framing as explicit design/review milestones.
No new persistent data or backend is needed for phase 1. Deployments are separate No new persistent data or backend is needed for phase 1. Deployments are separate
from implementation; this document is the plan for the remaining phases. from implementation; this document is the plan for the remaining phases.
## Later: peer mesh (exploratory, unscheduled)
Open HellCon tabs could assist each other so the tracker becomes a bootstrap
fallback rather than a requirement. This is an idea, not a commitment.
**Peer-relayed signaling.** WebRTC only needs a channel for offer, answer and ICE
candidates. If A has verified sessions with B and C, and B and C are paired with
each other, A can forward their reconnect exchange over its data channels. Seal
and authenticate the payloads with the B–C pairing key and bind them to the DTLS
fingerprints, so A acts only as a mailbox and cannot interpose. A relay does not
create trust: introducing unpaired devices still requires manual verification.
Fall back to the pairing's tracker or manual codes when no shared peer is open.
**Multi-source transfers.** Split a file into pieces hashed under a manifest
signed by the original sender. Any verified peer that holds pieces can serve
them; receivers check every piece against the manifest. Once one complete copy
exists, the sender may leave. Requesting only missing pieces also allows resuming
an interrupted transfer. This stays inside verified HellCon sessions: no public
swarms, no BitTorrent interoperability, and acceptance is still required per file.
**Limits.** "Online" means an open tab; browsers cannot listen in the background
and service workers cannot hold WebRTC connections, so there is still no presence
or offline wake-up. Relayed signaling does not help NAT traversal; STUN and
explicit TURN consent remain unchanged. The relay sees which of its peers connect
to each other.
**Preparation.** Keep the tracker reconnect adapter's announce/offer/answer layer
independent of the pairing logic and of its transport, so a data channel can carry
the same sealed exchange later.
+6
View File
@@ -95,6 +95,12 @@ tracker signaling requires no Nostr-style Schnorr signature library. Preserve
HellCon's P-256 identity proofs; tracker peer IDs are routing identifiers only. HellCon's P-256 identity proofs; tracker peer IDs are routing identifiers only.
Server-side dependencies are maintained separately from the browser bundle. Server-side dependencies are maintained separately from the browser bundle.
Keep the encrypted signaling exchange independent of the WebSocket transport.
The [peer mesh idea](ux-roadmap.md#later-peer-mesh-exploratory-unscheduled) may
later let an open, verified peer forward the same sealed exchange over a data
channel, leaving the tracker as a fallback. That idea is unscheduled and not part
of this plan.
## Discovery and encrypted signaling ## Discovery and encrypted signaling
Derive a 20-byte discovery identifier from the pairing secret with a dedicated Derive a 20-byte discovery identifier from the pairing secret with a dedicated
+115 -12
View File
@@ -1,6 +1,7 @@
// Dependency-free Chromium integration check. Run after `bun run build`. // Dependency-free Chromium integration check. Run after `bun run build`.
import { Readable, Writable } from 'node:stream'; import { Readable, Writable } from 'node:stream';
import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts'; import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts';
import { CODE_PREFIX, decodeCode } from '../src/lib/codes.ts';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import { createServer } from 'node:http'; import { createServer } from 'node:http';
@@ -48,6 +49,7 @@ 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;
@@ -98,9 +100,11 @@ 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.
@@ -113,7 +117,8 @@ 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++) {
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; } 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));
} }
@@ -131,19 +136,47 @@ async function checkAccessibility(session: string, mode: string) {
}); });
assert.deepEqual(violations, [], `${mode} mode accessibility violations`); 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 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);
const enableTurn = (session: string) => evaluate(session, () => { 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));
await input(receiver, '#offer-input', 'invalid-code!'); await input(receiver, '#offer-input', 'invalid-code!');
await click(receiver, 'Accept & create answer'); await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('[role=alert]')); await wait(receiver, () => !!document.querySelector('[role=alert]'));
@@ -152,8 +185,8 @@ async function connect(sender: string, receiver: string, size: number, changedId
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer'); await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('#output-code')); await wait(receiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect'); await input(sender, '#answer-input', offer); await click(sender, 'Connect');
await wait(sender, () => !!document.querySelector('[role=alert]')); await wait(sender, () => document.querySelector('[role=alert]')?.textContent?.includes('not an answer'));
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer); assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer);
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false); assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false);
await input(sender, '#answer-input', answer); await click(sender, 'Connect'); await input(sender, '#answer-input', answer); await click(sender, 'Connect');
@@ -210,15 +243,11 @@ try {
if (!button) throw new Error('Missing connection: ' + name); if (!button) throw new Error('Missing connection: ' + name);
button.click(); button.click();
}, name); }, 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); 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'); assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll<HTMLDetailsElement>('.config-details')].map(details => [details.querySelector('summary')?.textContent?.trim(), details.open])), [
['Remembered device', false], ['Network settings', false],
], 'Configuration panels start closed');
await checkAccessibility(sender, 'Connections desktop'); await checkAccessibility(sender, 'Connections desktop');
await screenshot(sender, 'connections-desktop'); await screenshot(sender, 'connections-desktop');
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus()); await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
@@ -473,6 +502,62 @@ 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);
@@ -517,7 +602,25 @@ try {
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin')); await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
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.equal(JSON.parse(atob(offer)).version, 4); 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('.title-line 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('.title-line h1')?.textContent), 'Con 1');
assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offer);
await evaluate(invitedPaired, () => [...document.querySelectorAll<HTMLButtonElement>('.connection-link')].find(item => item.querySelector('.connection-name')?.textContent === 'Con 2')?.click());
await wait(invitedPaired, () => document.querySelector('.title-line h1')?.textContent === 'Con 2');
await click(invitedPaired, 'Remove'); 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);
@@ -621,7 +724,7 @@ try {
await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code'); await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code');
await wait(denied, () => !!document.querySelector('#output-code')); await wait(denied, () => !!document.querySelector('#output-code'));
const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(JSON.parse(atob(temporary)).version, 3); assert.equal((await decodeCode(temporary)).identity, undefined);
await click(denied, 'Cancel connection'); await click(denied, 'Cancel connection');
console.log('PASS: denied identity storage still allows temporary v3 connection setup.'); console.log('PASS: denied identity storage still allows temporary v3 connection setup.');
+4 -4
View File
@@ -40,8 +40,8 @@ async function run(mode) {
dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); }; dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); };
b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; }; b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; };
try { try {
const offer = await api.createOfferCode(a); // The original helpers exchange encoded codes; current helpers exchange SDP.
let sdp = api.decodeSignal(offer); let sdp = mode === 'original' ? api.decodeSignal(await api.createOfferCode(a)) : await api.createOffer(a);
// Deliberately unusable advertised ports: only sender-initiated checks // Deliberately unusable advertised ports: only sender-initiated checks
// after the answer can discover the real sender. No host firewall changes. // after the answer can discover the real sender. No host firewall changes.
if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{ if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{
@@ -49,11 +49,11 @@ async function run(mode) {
const fields=l.split(' '); fields[5]='9'; return fields.join(' '); const fields=l.split(' '); fields[5]='9'; return fields.join(' ');
}).join('\r\n'); }).join('\r\n');
log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates')); log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates'));
const answer = await api.createAnswerCode(b, api.encodeSignal(sdp)); const answer = mode === 'original' ? await api.createAnswerCode(b, api.encodeSignal(sdp)) : await api.createAnswer(b, sdp);
log('answer ready'); log('answer ready');
await new Promise(r=>setTimeout(r,20000)); await new Promise(r=>setTimeout(r,20000));
log('apply answer'); log('apply answer');
await api.acceptAnswerCode(a,answer); await (mode === 'original' ? api.acceptAnswerCode(a,answer) : api.acceptAnswer(a,answer));
await new Promise(r=>setTimeout(r,12000)); await new Promise(r=>setTimeout(r,12000));
return {mode,received,events}; return {mode,received,events};
} catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; } } catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; }
+29 -3
View File
@@ -3,9 +3,14 @@ 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 EditableName from './components/EditableName.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 { 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'; 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 connections = ref<SavedConnection[]>([]), selected = ref(''); const connections = ref<SavedConnection[]>([]), selected = ref('');
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({}); const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
@@ -14,6 +19,10 @@ const sidebarOpen = ref(false), adding = ref(false);
const confirmingRemoval = ref(false), removing = ref(false); const confirmingRemoval = ref(false), removing = ref(false);
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) {
@@ -48,8 +57,15 @@ 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); }); 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() { 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;
@@ -57,10 +73,18 @@ 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));
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; } } 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;
@@ -154,7 +178,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" @status="setStatus" @activity="record" @update="update" /> <ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null"
@status="setStatus" @activity="record" @update="update" @invitation-taken="handoff = null" />
</KeepAlive> </KeepAlive>
</template> </template>
<p v-if="!current" class="status">Opening your connections…</p> <p v-if="!current" class="status">Opening your connections…</p>
@@ -170,4 +195,5 @@ async function remove() {
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button> <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>
+13 -2
View File
@@ -1,12 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { nextTick, ref, watch } from 'vue';
import TransferPanel from './TransferPanel.vue'; import TransferPanel from './TransferPanel.vue';
import type { SavedConnection, ConnectionActivity, ConnectionUpdate } from '../lib/connections.ts'; import type { SavedConnection, ConnectionActivity, ConnectionUpdate } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection> }>(); const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; invitation?: { code: string } | null }>();
const emit = defineEmits<{ const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected']; status: [id: string, state: 'ready' | 'connecting' | 'connected'];
activity: [id: string, item: ConnectionActivity]; activity: [id: string, item: ConnectionActivity];
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,6 +18,16 @@ 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 });
function sizeLabel(size: number) { function sizeLabel(size: number) {
if (size < 1024) return `${size} B`; if (size < 1024) return `${size} B`;
const index = Math.min(5, Math.floor(Math.log(size) / Math.log(1024))); const index = Math.min(5, Math.floor(Math.log(size) / Math.log(1024)));
+1 -1
View File
@@ -54,7 +54,7 @@ defineExpose({ refreshIdentity });
</script> </script>
<template> <template>
<details v-if="supported"> <details v-if="supported" class="config-details">
<summary>Remembered device</summary> <summary>Remembered device</summary>
<p class="status">Optionally remember the device on this connection, so later sessions verify it automatically. This uses a device identity stored in this browser and shared by all connections. Clearing site data loses it. Trusted app code is required: it can use this identity.</p> <p class="status">Optionally remember the device on this connection, so later sessions verify it automatically. This uses a device identity stored in this browser and shared by all connections. Clearing site data loses it. Trusted app code is required: it can use this identity.</p>
<fieldset class="device-settings" :disabled="disabled || working || !loaded"> <fieldset class="device-settings" :disabled="disabled || working || !loaded">
+110
View File
@@ -0,0 +1,110 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import AppDialog from './AppDialog.vue';
import { decodeCode, type Signal } from '../lib/codes.ts';
import { deliverAnswer, type Delivery } from '../lib/invitations.ts';
import { hasRelay } from '../lib/webrtc.ts';
import { asError } from '../lib/validation.ts';
import type { SavedConnection } from '../lib/connections.ts';
// A link opened in this tab. Offers are previewed and handed to a chosen slot;
// they never create an answer here, because answering reveals this device's
// addresses to whoever made the link.
const invitation = defineModel<{ code: string } | null>({ required: true });
const props = defineProps<{ connections: SavedConnection[]; states: Record<string, 'ready' | 'connecting' | 'connected'>; current: string; canAdd: boolean }>();
const emit = defineEmits<{ open: [target: string, code: string] }>();
const signal = ref<Signal | null>(null), failure = ref('');
const delivery = ref<Delivery | 'pending' | 'manual'>('pending');
const target = ref(''), copied = ref(false), copyError = ref('');
const open = computed({ get: () => !!invitation.value, set: value => { if (!value) invitation.value = null; } });
const idle = (id: string) => (props.states[id] ?? 'ready') === 'ready';
const paired = computed(() => signal.value?.identity && props.connections.find(item => item.peerKey === signal.value!.identity!.key));
const relay = computed(() => !!signal.value && hasRelay(signal.value.sdp));
const available = computed(() => target.value === 'new' ? props.canAdd : !!target.value && idle(target.value));
const title = computed(() => failure.value ? 'Link could not be opened'
: !signal.value ? 'Opening link'
: signal.value.type === 'offer' ? 'Invitation to receive files'
: { pending: 'Delivering answer', delivered: 'Answer delivered', used: 'Answer already used', manual: 'Paste this answer in the sender’s tab' }[delivery.value]);
let token = 0;
// Prefer the slot paired with the sender's device, then the open slot, then a new one.
function suggest() {
const match = paired.value;
if (match && idle(match.id)) return match.id;
if (idle(props.current)) return props.current;
return props.canAdd ? 'new' : props.connections.find(item => idle(item.id))?.id ?? '';
}
watch(invitation, async value => {
const run = ++token;
signal.value = null; failure.value = ''; delivery.value = 'pending'; copied.value = false; copyError.value = '';
if (!value) return;
try {
// TURN consent is checked again when the slot uses the code.
const decoded = await decodeCode(value.code, { allowTurn: true });
if (run !== token) return;
signal.value = decoded;
if (decoded.type === 'offer') { target.value = suggest(); return; }
const result = await deliverAnswer(decoded.ref, value.code);
if (run === token) delivery.value = result ?? 'manual';
} catch (err) { if (run === token) failure.value = asError(err).message; }
}, { immediate: true });
function accept() {
if (!invitation.value || !available.value) return;
emit('open', target.value, invitation.value.code);
invitation.value = null;
}
async function copy() {
try { await navigator.clipboard.writeText(invitation.value?.code ?? ''); copied.value = true; copyError.value = ''; }
catch { copyError.value = 'Clipboard unavailable. Select and copy the answer manually.'; }
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
</script>
<template>
<AppDialog v-model="open" :title="title">
<template v-if="failure">
<p class="error" role="alert">{{ failure }}</p>
<p>Ask your peer for a new link or code.</p>
</template>
<p v-else-if="!signal">Reading the link…</p>
<template v-else-if="signal.type === 'offer'">
<p>Someone invited you to receive files. The invitation only works while the sender’s HellCon page stays open, for up to 5 minutes after they created it.</p>
<p v-if="!signal.identity">The sender uses a temporary identity. Compare fingerprints after connecting.</p>
<p v-else-if="paired">The sender’s device matches the paired device of {{ paired.name }}. Its fresh device proof is still checked when connecting.</p>
<p v-else>The sender’s device is not paired with any of your connections. Compare fingerprints after connecting.</p>
<p v-if="relay">This invitation uses a TURN relay. Enable TURN in Network settings before accepting it.</p>
<label class="step" for="invitation-target">Receive on</label>
<select id="invitation-target" v-model="target" class="stun-select">
<option v-for="item in connections" :key="item.id" :value="item.id" :disabled="!idle(item.id)">
{{ item.name }}{{ item.id === paired?.id ? ' · paired device' : '' }}{{ idle(item.id) ? '' : ' · in use' }}
</option>
<option value="new" :disabled="!canAdd">New connection</option>
</select>
<p v-if="!available" class="error">Choose a connection that is not in use.</p>
<p>Nothing is sent until you press <strong>Accept &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>
+80 -29
View File
@@ -2,11 +2,13 @@
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, onBeforeUnmount, ref, watch } from 'vue'; import { computed, nextTick, 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 { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, decodeSignal, signalIdentity, MAX_SIGNAL_LENGTH, 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 { 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';
@@ -25,6 +27,10 @@ interface Session {
identityContext?: IdentityContext; identityContext?: IdentityContext;
identity?: IdentityState['identity']; identity?: IdentityState['identity'];
expected?: string; expected?: string;
// Shared by this session's offer and answer codes.
ref?: string;
// Stops accepting answer links from other tabs.
stopAnswers?: () => void;
timer?: ReturnType<typeof setTimeout>; timer?: ReturnType<typeof setTimeout>;
} }
@@ -47,7 +53,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(false); const copied = ref<'' | 'link' | 'code'>('');
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);
@@ -57,13 +63,22 @@ 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' });
} }
defineExpose({ focusDirection }); // Fills an invitation's code without creating the answer, which would reveal
// this device's addresses before the user chose to.
function importCode(code: string) {
if (busy.value || connected.value || props.sending) return;
if (step.value !== 'idle') reset();
inputCode.value = code;
void nextTick(() => acceptButton.value?.focus());
}
defineExpose({ focusDirection, importCode });
const choosing = ref(false); const choosing = ref(false);
const dragover = ref(false); const dragover = ref(false);
@@ -73,6 +88,9 @@ 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(() => {
@@ -89,8 +107,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 your code through an authenticated channel, then paste the answer.', 'offer-ready': 'Send the link privately, then paste the answer or open the answer link in this browser.',
'answer-ready': 'Send your answer back, then compare both full fingerprints.', 'answer-ready': 'Send the answer link back, then compare both full fingerprints.',
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.', 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.',
@@ -121,6 +139,7 @@ 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());
@@ -138,7 +157,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 = copied.value = choosing.value = false; verified.value = choosing.value = false; copied.value = '';
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;
} }
@@ -289,10 +308,14 @@ async function createCode() {
if (active !== session) return; if (active !== session) return;
session.pc.setConfiguration(iceConfiguration(configured)); session.pc.setConfiguration(iceConfiguration(configured));
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null; managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
if (!props.sending) { decodeSignal(pasted, session.options); session.remoteHello = signalIdentity(pasted); } const offer = props.sending ? null : await decodeCode(pasted, { type: 'offer', allowTurn: session.options.allowTurn });
const options = { ...session.options, signal: session.controller.signal, identity: session.localHello }; if (active !== session) return;
session.ref = offer ? offer.ref : createRef(); session.remoteHello = offer?.identity;
const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3')); if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options); const sdp = offer ? await createAnswer(session.pc, offer.sdp, options) : await createOffer(session.pc, options);
if (active !== session) return;
const code = await encodeCode({ type: props.sending ? 'offer' : 'answer', ref: session.ref, sdp, identity: session.localHello });
if (active !== session) return; if (active !== session) return;
outputCode.value = code; outputCode.value = code;
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready'); session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
@@ -300,6 +323,12 @@ 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'; }
@@ -311,9 +340,10 @@ async function useAnswer() {
error.value = ''; error.value = '';
step.value = 'verification'; step.value = 'verification';
try { try {
decodeSignal(inputCode.value, session.options); const answer = await decodeCode(inputCode.value, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
session.remoteHello = signalIdentity(inputCode.value); if (active !== session) return;
await acceptAnswerCode(session.pc, inputCode.value, session.options); session.remoteHello = answer.identity;
await acceptAnswer(session.pc, answer.sdp, session.options);
if (active !== session) return; if (active !== session) return;
session.diagnostics.record('answer applied'); session.diagnostics.record('answer applied');
session.diagnostics.descriptions(); session.diagnostics.descriptions();
@@ -393,14 +423,19 @@ 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() { async function copy(kind: 'link' | 'code') {
const session = active; const session = active;
try { try {
await navigator.clipboard.writeText(outputCode.value); await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value);
if (active !== session) return; if (active !== session) return;
copied.value = true; clearTimeout(copyTimer); copied.value = kind; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = false; }, 1500); copyTimer = setTimeout(() => { copied.value = ''; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; } } catch { if (active === session) error.value = `Clipboard unavailable. Select and copy the ${kind} manually.`; }
}
async function share() {
const session = active;
try { await navigator.share({ url: outputLink.value }); }
catch (err) { if (active === session && asError(err).name !== 'AbortError') error.value = 'Sharing failed. Copy the link instead.'; }
} }
function stateLabel(state: TransferState | null) { 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';
@@ -411,7 +446,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.select(); if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) event.target.select();
} }
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); }); onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script> </script>
@@ -432,25 +467,39 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<div v-if="outgoing" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Sending progress"><div :style="{ width: progress + '%' }"></div></div> <div v-if="outgoing" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Sending progress"><div :style="{ width: progress + '%' }"></div></div>
</section> </section>
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :disabled="busy || connected" @update="emit('update', $event)" /> <DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :disabled="busy || connected" @update="emit('update', $event)" />
<details class="network-details"> <details class="config-details">
<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 codes privately. They contain your IP address and connection details.</p> <p v-if="!connected" class="status">Exchange links or codes privately. They contain your IP address and connection details.</p>
<template v-if="!sending"> <template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s connection code</label> <label class="step" for="offer-input">Paste the sender’s link or code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" /> <textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template> </template>
<button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button> <button ref="acceptButton" class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode"> <template v-if="outputCode">
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label> <label class="step" for="output-link">{{ sending ? 'Send this link to the receiver' : 'Send this answer link back to the sender' }}</label>
<input id="output-link" class="stun-input" :value="outputLink" readonly @focus="selectCode" />
<div class="share-actions">
<button v-if="canShare" class="primary" @click="share">Share link</button>
<button @click="copy('link')">{{ copied === 'link' ? 'Copied!' : 'Copy link' }}</button>
</div>
<p class="status">A link is as sensitive as a code: send it privately. It may stay in browser history and only works while this page stays open, for up to 5 minutes.</p>
<details class="code-details">
<summary>Show code instead</summary>
<div class="code-entry">
<label class="step" for="output-code">{{ sending ? 'Connection code' : 'Answer code' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" /> <textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button> <button @click="copy('code')">{{ copied === 'code' ? 'Copied!' : 'Copy code' }}</button>
</div>
</details>
</template> </template>
<template v-if="sending && outputCode"> <template v-if="sending && outputCode">
<label class="step" for="answer-input">Paste the receiver’s answer</label> <div class="code-entry">
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="step !== 'offer-ready'" /> <label class="step" for="answer-input">Paste the receiver’s answer or answer link</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button> <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">
@@ -487,8 +536,10 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
</details> </details>
<p v-if="!connected && step === 'done'" class="status">Connection ended. Exchange fresh codes to send more files.</p> <p v-if="!connected && step === 'done'" class="status">Connection ended. Exchange fresh codes to send more files.</p>
<p v-if="connected" class="status">Connection verified. Either person can add files. Keep both tabs open.</p> <p v-if="connected" class="status">Connection verified. Either person can add files. Keep both tabs open.</p>
<div v-if="step !== 'idle'" class="session-actions">
<button v-if="connected || busy" @click="disconnect">Disconnect</button> <button v-if="connected || busy" @click="disconnect">Disconnect</button>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button> <button @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
</div>
<p class="status">Before connecting, Send/Receive chooses who starts. Once connected, use either button to jump between sending and receiving without disconnecting. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p> <p class="status">Before connecting, Send/Receive chooses who starts. Once connected, use either button to jump between sending and receiving without disconnecting. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div> </div>
</template> </template>
+104
View File
@@ -0,0 +1,104 @@
import { parseHello, type IdentityHello } from './identity.ts';
import { asError, isRecord } from './validation.ts';
import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts';
// Connection codes: "HC1." + base64url(deflate-raw(JSON)). The same text works
// pasted or as a link fragment, which browsers never send to the app host.
// Codes carry connection details, not secrets; fingerprints authenticate peers.
export const CODE_PREFIX = 'HC1.';
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH;
// Pasted text may be a full link around the code.
export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024;
const INVALID = 'Invalid connection code. Paste the complete code or link.';
export interface Signal {
type: 'offer' | 'answer';
// Chosen by the offerer and echoed by the answer, which addresses that offer.
ref: string;
sdp: string;
identity?: IdentityHello;
}
export interface DecodeOptions extends Pick<IceOptions, 'allowTurn'> { type?: Signal['type']; ref?: string }
function toBase64Url(bytes: Uint8Array) {
let binary = '';
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
}
function fromBase64Url(text: string) {
if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new Error(INVALID);
return Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), char => char.charCodeAt(0));
}
async function deflate(text: string) {
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
// Stops reading once the output exceeds the limit, so a small hostile code
// cannot expand without bound.
async function inflate(bytes: Uint8Array<ArrayBuffer>) {
const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw')).getReader();
const chunks: Uint8Array[] = [];
let length = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
length += value.byteLength;
if (length > MAX_PAYLOAD) { void reader.cancel().catch(() => {}); throw new Error('Connection code is too large.'); }
chunks.push(value);
}
const output = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.byteLength; }
return output;
}
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); }
// Accepts a bare code or a full link and returns the code text.
export function codeFromText(text: string) {
return text.slice(text.lastIndexOf('#') + 1).replace(/\s+/g, '');
}
export function codeLink(code: string, base: string) {
const url = new URL(base);
url.hash = code;
return url.href;
}
export async function encodeCode({ type, ref, sdp, identity }: Signal) {
const payload = identity ? { version: 4, type, ref, sdp, identity: parseHello(identity) } : { version: 3, type, ref, sdp };
const code = CODE_PREFIX + toBase64Url(await deflate(JSON.stringify(payload)));
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
return code;
}
export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise<Signal> {
if (typeof text !== 'string' || text.length > MAX_INPUT_LENGTH) throw new Error('Connection code is too large.');
const code = codeFromText(text);
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
if (!code.startsWith(CODE_PREFIX)) {
let legacy = false;
try { legacy = isRecord(JSON.parse(atob(code))); } catch { /* not an old code either */ }
throw new Error(legacy ? 'Both people need the current HellCon version.' : INVALID);
}
let data: unknown;
try {
data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await inflate(fromBase64Url(code.slice(CODE_PREFIX.length)))));
} catch (err) {
if (asError(err).message === 'Connection code is too large.') throw err;
throw new Error(INVALID);
}
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
if ((data.type !== 'offer' && data.type !== 'answer') || typeof data.ref !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(data.ref) || typeof data.sdp !== 'string') {
throw new Error(INVALID);
}
if (data.version === 3 && data.identity !== undefined) throw new Error(INVALID);
const identity = data.version === 4 ? parseHello(data.identity) : undefined;
validateDescription(data.sdp, options);
if (type && data.type !== type) {
throw new Error(type === 'answer' ? 'This is a connection code, not an answer. Paste the answer your peer created.' : 'This is an answer, not a connection code. Paste the code the sender created.');
}
if (ref !== undefined && data.ref !== ref) throw new Error('This answer belongs to a different connection code. Ask your peer to answer your current code.');
return { type: data.type, ref: data.ref, sdp: data.sdp, ...(identity ? { identity } : {}) };
}
+43
View File
@@ -0,0 +1,43 @@
import { CODE_PREFIX } from './codes.ts';
import { isRecord } from './validation.ts';
// Invitation links carry a code in the fragment, which browsers never send to
// the host. Answers opened in another tab reach the waiting sender over a
// same-origin BroadcastChannel; pasting stays the fallback.
const CHANNEL = 'hellcon-answers';
export type Delivery = 'delivered' | 'used';
// Returns a code from the URL fragment and removes it from the address bar.
// Other fragments, such as the skip link's, are left alone.
export function takeFragment() {
const code = location.hash.slice(1);
if (!code.startsWith(CODE_PREFIX)) return '';
history.replaceState(history.state, '', location.href.split('#')[0]);
return code;
}
// Resolves null when no waiting tab answers in time, for example in a
// messenger's in-app browser or another browser.
export function deliverAnswer(ref: string, code: string, timeout = 1000): Promise<Delivery | null> {
if (typeof BroadcastChannel === 'undefined') return Promise.resolve(null);
const channel = new BroadcastChannel(CHANNEL), id = crypto.randomUUID();
return new Promise(resolve => {
const done = (result: Delivery | null) => { clearTimeout(timer); channel.close(); resolve(result); };
const timer = setTimeout(() => done(null), timeout);
channel.onmessage = ({ data }: MessageEvent) => {
if (isRecord(data) && data.kind === 'ack' && data.id === id && (data.status === 'delivered' || data.status === 'used')) done(data.status);
};
channel.postMessage({ kind: 'answer', id, ref, code });
});
}
// `receive` returns false when the offer no longer waits for an answer.
export function listenForAnswers(ref: string, receive: (code: string) => boolean) {
if (typeof BroadcastChannel === 'undefined') return () => {};
const channel = new BroadcastChannel(CHANNEL);
channel.onmessage = ({ data }: MessageEvent) => {
if (!isRecord(data) || data.kind !== 'answer' || data.ref !== ref || typeof data.id !== 'string' || typeof data.code !== 'string') return;
channel.postMessage({ kind: 'ack', id: data.id, status: receive(data.code) ? 'delivered' : 'used' });
};
return () => channel.close();
}
+18 -39
View File
@@ -1,5 +1,4 @@
import { parseHello, type IdentityHello } from './identity.ts'; import { isRecord, isStringArray } from './validation.ts';
import { asError, isRecord, isStringArray } from './validation.ts';
export interface IceOptions { export interface IceOptions {
stunUrl?: string | null; stunUrl?: string | null;
@@ -21,13 +20,13 @@ export interface NetworkSettings {
} }
export interface WaitOptions { signal?: AbortSignal; timeout?: number } export interface WaitOptions { signal?: AbortSignal; timeout?: number }
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'> & { identity?: IdentityHello }; type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
export interface Fingerprints { local: string; remote: string } export interface Fingerprints { local: string; remote: string }
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>; export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>; export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>; type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
// Manual signaling. Codes are encoded connection details, not encrypted secrets. // Manual signaling; codes.ts encodes the validated descriptions for exchange.
export const CHUNK_SIZE = 16 * 1024; export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024; export const MAX_BUFFERED = 1024 * 1024;
export const MAX_SIGNAL_LENGTH = 64 * 1024; export const MAX_SIGNAL_LENGTH = 64 * 1024;
@@ -105,6 +104,10 @@ export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: Wai
}); });
} }
export function hasRelay(sdp: string) {
return sdp.split(/\r?\n/).some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line));
}
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) { 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.');
@@ -119,7 +122,7 @@ export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<Ic
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) { 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 && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) { if (!allowTurn && hasRelay(sdp)) {
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.'); 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(':', ' ');
@@ -132,47 +135,28 @@ export function getFingerprints(pc: { localDescription: { sdp: string } | null;
}; };
} }
export function encodeSignal(sdp: string, identity?: IdentityHello) { // Each step validates the description it produces or applies.
const code = btoa(JSON.stringify(identity ? { version: 4, sdp, identity: parseHello(identity) } : { version: 3, sdp })).replace(/=+$/, ''); export async function createOffer(pc: RTCPeerConnection, options: SignalOptions = {}) {
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
return code;
}
export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTurn'>): string {
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
try {
const clean = text.trim().replace(/\s+/g, '');
const data: unknown = JSON.parse(atob(clean));
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
if (data.version === 4) parseHello(data.identity);
validateDescription(data.sdp, options);
return data.sdp;
} catch (err) {
if (err instanceof SyntaxError || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
throw err;
}
}
export async function createOfferCode(pc: RTCPeerConnection, options: SignalOptions = {}) {
await pc.setLocalDescription(await pc.createOffer()); await pc.setLocalDescription(await pc.createOffer());
await waitForIceComplete(pc, options); await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.'); if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options); validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp, options.identity); return pc.localDescription.sdp;
} }
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) { export async function createAnswer(pc: RTCPeerConnection, offer: string, options: SignalOptions = {}) {
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) }); validateDescription(offer, options);
await pc.setRemoteDescription({ type: 'offer', sdp: offer });
await pc.setLocalDescription(await pc.createAnswer()); await pc.setLocalDescription(await pc.createAnswer());
await waitForIceComplete(pc, options); await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.'); if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options); validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp, options.identity); return pc.localDescription.sdp;
} }
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) { export function acceptAnswer(pc: RTCPeerConnection, answer: string, options?: SignalOptions) {
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) }); validateDescription(answer, options);
return pc.setRemoteDescription({ type: 'answer', sdp: answer });
} }
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) { export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
@@ -200,8 +184,3 @@ export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 6000
check(); check();
}); });
} }
export function signalIdentity(text: string): IdentityHello | undefined {
const data = JSON.parse(atob(text.trim().replace(/\s+/g, '')));
return data.version === 4 ? parseHello(data.identity) : undefined;
}
+3 -1
View File
@@ -1,5 +1,7 @@
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';
createApp(App).mount('#app'); // Read and clear an invitation fragment before anything else can see the URL.
createApp(App, { initialCode: takeFragment() }).mount('#app');
+37 -24
View File
@@ -7,6 +7,11 @@
--accent-soft: rgba(255, 155, 61, 0.15); --accent-soft: rgba(255, 155, 61, 0.15);
--text: #e8eaf0; --text: #e8eaf0;
--muted: #a0a7b8; --muted: #a0a7b8;
--space-sm: 0.6rem;
--space-md: 0.9rem;
--space-lg: 1.25rem;
--space-xl: 1.5rem;
--space-2xl: 2rem;
} }
* { * {
@@ -44,10 +49,10 @@ body {
background: var(--panel); background: var(--panel);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 12px; border-radius: 12px;
padding: 1.25rem; padding: var(--space-lg);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.9rem; gap: var(--space-md);
} }
h1 { h1 {
@@ -245,28 +250,31 @@ p.stun-hint {
.network-settings { .network-settings {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.7rem; gap: var(--space-sm);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 8px; border-radius: 8px;
min-width: 0; min-width: 0;
padding: var(--space-sm) var(--space-md) var(--space-md);
} }
.network-settings legend { color: var(--muted); } .network-settings legend { color: var(--muted); }
.checkbox { display: flex; align-items: start; gap: 0.6rem; } .checkbox { display: flex; align-items: start; gap: var(--space-sm); }
.fp-row { flex-direction: column; align-items: start; } .fp-row { flex-direction: column; align-items: start; }
.fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; } .fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; }
.file-chip span { overflow-wrap: anywhere; min-width: 0; } .file-chip span { overflow-wrap: anywhere; min-width: 0; }
.incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; } .incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; }
.transfer-section { display: flex; flex-direction: column; gap: 0.9rem; scroll-margin-top: 1rem; min-width: 0; } .transfer-section { display: flex; flex-direction: column; gap: var(--space-md); scroll-margin-top: 1rem; min-width: 0; }
.transfer-section:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; } .transfer-section:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; }
.device-settings { display: flex; flex-direction: column; gap: 0.75rem; min-width: 0; border: 1px solid var(--border); border-radius: 8px; } .device-settings { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; border: 1px solid var(--border); border-radius: 8px; padding: var(--space-sm) var(--space-md) var(--space-md); }
.config-details > :not(summary) { margin-block: var(--space-sm) 0; }
.config-details fieldset .status { margin-block: 0; line-height: 1.5; }
.device-settings input:not([type=checkbox]) { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; } .device-settings input:not([type=checkbox]) { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
/* The connection shell stays in place while each workspace scrolls. */ /* The connection shell stays in place while each workspace scrolls. */
.app-shell { display: grid; grid-template-columns: 264px minmax(0, 1fr); height: 100%; } .app-shell { display: grid; grid-template-columns: 264px minmax(0, 1fr); height: 100%; }
.sidebar { display: flex; flex-direction: column; gap: 1.25rem; background: #13161e; border-right: 1px solid var(--border); padding: 1.6rem 1rem 1rem; min-height: 0; overflow-y: auto; } .sidebar { display: flex; flex-direction: column; gap: var(--space-lg); background: #13161e; border-right: 1px solid var(--border); padding: 1.6rem 1rem 1rem; min-height: 0; overflow-y: auto; }
.brand { display: flex; align-items: center; gap: 0.8rem; padding: 0 0.5rem 1.25rem; } .brand { display: flex; align-items: center; gap: 0.8rem; padding: 0 0.5rem var(--space-lg); }
.brand img { object-fit: contain; } .brand img { object-fit: contain; }
.brand-name { display: block; font-family: ui-monospace, monospace; font-weight: 700; font-size: 1.45rem; letter-spacing: -0.05em; } .brand-name { display: block; font-family: ui-monospace, monospace; font-weight: 700; font-size: 1.45rem; letter-spacing: -0.05em; }
.brand p { font-size: 0.75rem; color: var(--muted); margin: 0.25rem 0 0; } .brand p { font-size: 0.75rem; color: var(--muted); margin: 0.25rem 0 0; }
@@ -286,7 +294,7 @@ p.stun-hint {
.connection-dot.connecting { background: var(--accent); } .connection-dot.connecting { background: var(--accent); }
.add-connection { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.82rem; background: transparent; border-style: dashed; } .add-connection { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.82rem; background: transparent; border-style: dashed; }
.add-connection > span { font-size: 1.1rem; } .add-connection > span { font-size: 1.1rem; }
.sidebar-footer { margin-top: auto; padding: 1.5rem 0.65rem 0.25rem; color: var(--muted); font-size: 0.72rem; line-height: 1.65; } .sidebar-footer { margin-top: auto; padding: var(--space-xl) 0.65rem 0.25rem; color: var(--muted); font-size: 0.72rem; line-height: 1.65; }
.sidebar-tag { font-weight: 600; color: var(--text); } .sidebar-tag { font-weight: 600; color: var(--text); }
.sidebar-footer p { margin: 0.5rem 0 1rem; } .sidebar-footer p { margin: 0.5rem 0 1rem; }
summary { cursor: pointer; color: var(--muted); font-size: 0.83rem; padding: 0.4rem 0; } summary { cursor: pointer; color: var(--muted); font-size: 0.83rem; padding: 0.4rem 0; }
@@ -294,7 +302,7 @@ summary:hover { color: var(--text); }
summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.privacy-details summary { font-size: 0.72rem; } .privacy-details summary { font-size: 0.72rem; }
.main-pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; } .main-pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; }
.connection-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; min-height: 80px; padding: 1rem 1.5rem; border-bottom: 1px solid var(--border); background: #141720; } .connection-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; min-height: 80px; padding: 1rem var(--space-xl); border-bottom: 1px solid var(--border); background: #141720; }
.connection-title { min-width: 0; flex: 1; } .connection-title { min-width: 0; flex: 1; }
.title-line { display: flex; align-items: center; gap: 1rem; margin-top: 0.4rem; } .title-line { display: flex; align-items: center; gap: 1rem; margin-top: 0.4rem; }
.title-line h1 { margin: 0; font-size: 1.35rem; font-weight: 600; font-family: inherit; overflow-wrap: anywhere; } .title-line h1 { margin: 0; font-size: 1.35rem; font-weight: 600; font-family: inherit; overflow-wrap: anywhere; }
@@ -304,14 +312,14 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.header-action:hover:not(:disabled) .header-action-icon, .header-action:focus-visible .header-action-icon { opacity: 1; } .header-action:hover:not(:disabled) .header-action-icon, .header-action:focus-visible .header-action-icon { opacity: 1; }
.session-badge { display: inline-flex; align-items: center; gap: 0.45rem; color: var(--muted); font-size: 0.74rem; white-space: nowrap; border: 1px solid var(--border); border-radius: 20px; padding: 0.45rem 0.7rem; } .session-badge { display: inline-flex; align-items: center; gap: 0.45rem; color: var(--muted); font-size: 0.74rem; white-space: nowrap; border: 1px solid var(--border); border-radius: 20px; padding: 0.45rem 0.7rem; }
.session-badge.connected { color: #8ddbb6; border-color: #315344; } .session-badge.connected { color: #8ddbb6; border-color: #315344; }
.workspace-scroll { flex: 1; overflow-y: auto; padding: 2rem 2.25rem; } .workspace-scroll { flex: 1; overflow-y: auto; padding: var(--space-2xl) 2.25rem; }
.connection-workspace { display: grid; grid-template-columns: minmax(0, 720px) minmax(240px, 320px); gap: 2rem; max-width: 1200px; margin-inline: auto; align-items: start; } .connection-workspace { display: grid; grid-template-columns: minmax(0, 720px) minmax(240px, 320px); gap: var(--space-2xl); max-width: 1200px; margin-inline: auto; align-items: start; }
.session-column { min-width: 0; } .session-column { min-width: 0; }
.workspace-intro { margin-bottom: 1.4rem; } .workspace-intro { margin-bottom: 1.4rem; }
.workspace-intro h2 { font-size: 1.05rem; font-weight: 600; margin: 0 0 0.4rem; } .workspace-intro h2 { font-size: 1.05rem; font-weight: 600; margin: 0 0 0.4rem; }
.workspace-intro p { font-size: 0.85rem; color: var(--muted); line-height: 1.6; margin: 0; } .workspace-intro p { font-size: 0.85rem; color: var(--muted); line-height: 1.6; margin: 0; }
.tabs { width: fit-content; padding: 4px; gap: 4px; background: #1b1f2a; border: 1px solid var(--border); border-radius: 10px; } .tabs { width: fit-content; padding: 4px; gap: 4px; background: #1b1f2a; border: 1px solid var(--border); border-radius: 10px; }
.tabs button { padding: 0.45rem 1.5rem; font-size: 0.85rem; border: none; background: transparent; } .tabs button { padding: 0.45rem var(--space-xl); font-size: 0.85rem; border: none; background: transparent; }
.tabs button.active { background: #3e3025; color: #ffb575; } .tabs button.active { background: #3e3025; color: #ffb575; }
.panel { box-shadow: 0 6px 28px #00000012; } .panel { box-shadow: 0 6px 28px #00000012; }
.panel > .status { line-height: 1.6; margin: 0.1rem 0; } .panel > .status { line-height: 1.6; margin: 0.1rem 0; }
@@ -320,9 +328,14 @@ 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; }
.network-details > fieldset { margin-top: 0.65rem; } .share-actions, .session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.activity-panel { min-width: 0; border-left: 1px solid var(--border); padding-left: 1.5rem; } .share-actions button, .session-actions button { font-size: 0.88rem; }
.activity-heading { display: flex; align-items: center; gap: 0.6rem; } .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; }
.activity-panel { min-width: 0; border-left: 1px solid var(--border); padding-left: var(--space-xl); }
.activity-heading { display: flex; align-items: center; gap: var(--space-sm); }
.activity-heading h2 { font-size: 0.9rem; font-weight: 600; margin: 0; } .activity-heading h2 { font-size: 0.9rem; font-weight: 600; margin: 0; }
.activity-heading > span { font-size: 0.68rem; color: var(--muted); border-radius: 5px; padding: 0.15rem 0.35rem; background: #242936; } .activity-heading > span { font-size: 0.68rem; color: var(--muted); border-radius: 5px; padding: 0.15rem 0.35rem; background: #242936; }
.empty-activity { padding: 3.5rem 0.25rem; text-align: center; } .empty-activity { padding: 3.5rem 0.25rem; text-align: center; }
@@ -330,8 +343,8 @@ input[type=file]::file-selector-button { border: 1px solid #505667; border-radiu
.empty-activity h3 { font-size: 0.88rem; font-weight: 500; margin: 0 0 0.6rem; } .empty-activity h3 { font-size: 0.88rem; font-weight: 500; margin: 0 0 0.6rem; }
.empty-activity p { font-size: 0.8rem; line-height: 1.7; color: var(--muted); } .empty-activity p { font-size: 0.8rem; line-height: 1.7; color: var(--muted); }
p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; } p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.empty-activity .activity-note { margin-top: 1.5rem; } .empty-activity .activity-note { margin-top: var(--space-xl); }
.activity-list { list-style: none; padding: 0; margin: 1.25rem 0; } .activity-list { list-style: none; padding: 0; margin: var(--space-lg) 0; }
.activity-item { display: flex; gap: 0.7rem; padding: 1rem 0; border-bottom: 1px solid var(--border); font-size: 0.78rem; } .activity-item { display: flex; gap: 0.7rem; padding: 1rem 0; border-bottom: 1px solid var(--border); font-size: 0.78rem; }
.activity-item > div { min-width: 0; } .activity-item > div { min-width: 0; }
.activity-icon { color: var(--accent); padding-top: 0.1rem; font-size: 1rem; } .activity-icon { color: var(--accent); padding-top: 0.1rem; font-size: 1rem; }
@@ -343,11 +356,11 @@ p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.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; }
@media (max-width: 1150px) { @media (max-width: 1150px) {
.app-shell { grid-template-columns: 230px minmax(0, 1fr); } .app-shell { grid-template-columns: 230px minmax(0, 1fr); }
.connection-workspace { grid-template-columns: minmax(0, 1fr); gap: 2rem; } .connection-workspace { grid-template-columns: minmax(0, 1fr); gap: var(--space-2xl); }
.activity-panel { border-left: 0; border-top: 1px solid var(--border); padding: 1.5rem 0 0; } .activity-panel { border-left: 0; border-top: 1px solid var(--border); padding: var(--space-xl) 0 0; }
.empty-activity { padding: 1.5rem 0; } .empty-activity { padding: var(--space-xl) 0; }
.connection-header { padding-inline: 1.5rem; } .connection-header { padding-inline: var(--space-xl); }
.workspace-scroll { padding: 1.5rem; } .workspace-scroll { padding: var(--space-xl); }
} }
@media (max-width: 700px) { @media (max-width: 700px) {
#app { height: auto; min-height: 100dvh; } #app { height: auto; min-height: 100dvh; }
@@ -358,7 +371,7 @@ p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.sidebar-footer { padding-top: 0; } .sidebar-footer { padding-top: 0; }
.connection-header { flex-wrap: wrap; padding: 1rem; min-height: 0; gap: 0.75rem; } .connection-header { flex-wrap: wrap; padding: 1rem; min-height: 0; gap: 0.75rem; }
.sidebar-toggle { display: block; flex-basis: 100%; font-size: 0.8rem; text-align: left; background: transparent; padding: 0.5rem; } .sidebar-toggle { display: block; flex-basis: 100%; font-size: 0.8rem; text-align: left; background: transparent; padding: 0.5rem; }
.workspace-scroll { padding: 1.25rem 1rem; overflow: visible; } .workspace-scroll { padding: var(--space-lg) 1rem; overflow: visible; }
.title-line { gap: 0.4rem; } .title-line { gap: 0.4rem; }
.title-line h1 { font-size: 1.15rem; } .title-line h1 { font-size: 1.15rem; }
.panel { padding: 1rem; } .panel { padding: 1rem; }
+79
View File
@@ -0,0 +1,79 @@
import test from 'node:test';
import assert from 'node:assert/strict';
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';
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 identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
const ref = createRef();
const offer: Signal = { type: 'offer', ref, sdp };
const base64url = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url');
async function deflate(data: Uint8Array<ArrayBuffer> | string) {
return new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer());
}
const raw = async (payload: unknown) => CODE_PREFIX + base64url(await deflate(JSON.stringify(payload)));
test('codes round-trip both types, with and without identity', async () => {
assert.match(ref, /^[A-Za-z0-9_-]{22}$/);
assert.notEqual(createRef(), ref);
for (const signal of [offer, { ...offer, type: 'answer' as const }, { ...offer, identity }]) {
const code = await encodeCode(signal);
assert.ok(code.startsWith(CODE_PREFIX));
assert.match(code.slice(CODE_PREFIX.length), /^[A-Za-z0-9_-]+$/);
assert.deepEqual(await decodeCode(code), signal);
}
});
test('links, wrapped text and bare codes decode the same', async () => {
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), offer);
});
test('expected type and ref are enforced', async () => {
const answer = await encodeCode({ ...offer, type: 'answer' });
await assert.rejects(decodeCode(await encodeCode(offer), { type: 'answer' }), /not an answer/);
await assert.rejects(decodeCode(answer, { type: 'offer' }), /not a connection code/);
await assert.rejects(decodeCode(answer, { type: 'answer', ref: createRef() }), /different connection code/);
assert.equal((await decodeCode(answer, { type: 'answer', ref })).type, 'answer');
});
test('descriptions are validated, including relay opt-in', async () => {
const relayed = await encodeCode({ ...offer, sdp: sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n' });
await assert.rejects(decodeCode(relayed), /explicitly enable TURN/);
assert.equal((await decodeCode(relayed, { allowTurn: true })).type, 'offer');
await assert.rejects(encodeCode({ ...offer, identity: { key: '04', nonce: '' } }), /device identity/);
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp: 'v=0' })), /data channel/);
});
test('malformed, old and unexpected payloads are rejected', async () => {
for (const text of ['', 'bad!', CODE_PREFIX, `${CODE_PREFIX}a`, `${CODE_PREFIX}not+base64`, `${CODE_PREFIX}AAAA`, CODE_PREFIX + base64url(new Uint8Array([0xff, 0xfe]))]) {
await assert.rejects(decodeCode(text), /Invalid connection code/, text);
}
await assert.rejects(decodeCode(btoa(JSON.stringify({ version: 4, sdp }))), /current HellCon version/);
await assert.rejects(decodeCode(await raw({ version: 2, type: 'offer', ref, sdp })), /current HellCon version/);
await assert.rejects(decodeCode(await raw([1])), /current HellCon version/);
await assert.rejects(decodeCode(await raw({ version: 3, type: 'pranswer', ref, sdp })), /Invalid connection code/);
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref: 'short', sdp })), /Invalid connection code/);
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp, identity })), /Invalid connection code/);
await assert.rejects(decodeCode(await raw({ version: 4, type: 'offer', ref, sdp })), /device identity/);
await assert.rejects(decodeCode(CODE_PREFIX + base64url(await deflate(new Uint8Array([0x7b, 0xff, 0x7d])))), /Invalid connection code/);
await assert.rejects(decodeCode(42), /too large/);
});
test('oversized codes and decompression bombs are rejected', async () => {
await assert.rejects(decodeCode(CODE_PREFIX + 'A'.repeat(MAX_CODE_LENGTH)), /too large/);
await assert.rejects(decodeCode('x'.repeat(MAX_INPUT_LENGTH + 1)), /too large/);
// 32 MiB of zeros deflate to about 32 KiB, which fits the code length limit.
const bomb = CODE_PREFIX + base64url(await deflate(new Uint8Array(32 * 1024 * 1024)));
assert.ok(bomb.length < MAX_CODE_LENGTH);
const started = Date.now();
await assert.rejects(decodeCode(bomb), /too large/);
assert.ok(Date.now() - started < 2000);
// Base64 text of random bytes stays incompressible enough to exceed the limit.
await assert.rejects(encodeCode({ ...offer, sdp: sdp + 'a=x:' + randomBytes(60000).toString('base64') }), /too large/);
});
+39
View File
@@ -0,0 +1,39 @@
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'); }
});
+7 -23
View File
@@ -1,6 +1,6 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { iceConfiguration, validateDescription, getFingerprints, signalIdentity, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts'; import { iceConfiguration, validateDescription, getFingerprints, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.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`;
@@ -15,8 +15,8 @@ test('TURN is absent by default and dormant credentials cannot enable it', () =>
test('remote relay candidates require local explicit opt-in', () => { test('remote relay candidates require local explicit opt-in', () => {
const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n'; const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n';
assert.throws(() => decodeSignal(encodeSignal(relayed)), /explicitly enable TURN/); assert.throws(() => validateDescription(relayed), /explicitly enable TURN/);
assert.equal(decodeSignal(encodeSignal(relayed), { allowTurn: true }), relayed); assert.equal(validateDescription(relayed, { allowTurn: true }), validateDescription(sdp));
}); });
test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => { test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
@@ -28,12 +28,10 @@ test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n')); assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n'));
}); });
test('signals round-trip but reject legacy, malformed and oversized codes', () => { test('descriptions are bounded and printable', () => {
assert.equal(decodeSignal(encodeSignal(sdp)), sdp); assert.throws(() => validateDescription(sdp + 'a'.repeat(MAX_SIGNAL_LENGTH)), /Invalid connection description/);
assert.throws(() => decodeSignal(btoa(sdp))); assert.throws(() => validateDescription(sdp + 'a=x:\u00e9\r\n'), /Invalid connection description/);
assert.throws(() => decodeSignal('bad!')); assert.throws(() => validateDescription(42), /Invalid connection description/);
assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1)));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 2, sdp }))));
}); });
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; } class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }
@@ -62,17 +60,3 @@ test('buffer wait resolves when already drained and rejects close or cancellatio
const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort(); const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort();
await assert.rejects(cancelled, /interrupted/); await assert.rejects(cancelled, /interrupted/);
}); });
test('identity signaling is versioned, bounded, and optional for temporary sessions', () => {
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
const code = encodeSignal(sdp, identity);
assert.equal(JSON.parse(atob(code)).version, 4);
assert.equal(decodeSignal(code), sdp);
assert.deepEqual(signalIdentity(code), identity);
assert.equal(signalIdentity(encodeSignal(sdp)), undefined);
assert.equal(JSON.parse(atob(encodeSignal(sdp))).version, 3);
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp, identity: { ...identity, nonce: 'bad' } }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 5, sdp, identity }))));
});