diff --git a/CHANGELOG.md b/CHANGELOG.md index a4c5b0f..6199f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,39 +4,34 @@ ### Added -- Add a messenger-style workspace with a connections sidebar, editable slot - names, session status, and a persistent activity timeline per connection. -- Preserve live sessions and file selections while switching slots. Save names, - paired-device associations, and the last 50 transfer results locally; keep - manual reconnection with fresh codes. Add collapsible mobile navigation. -- Add opt-in hosted device identities and saved contacts, with fresh mutual - signatures bound to both connection fingerprints before remembered verification. -- Add contact removal and identity reset. +- A connections sidebar with up to 100 named slots. Each row shows its session + status and lets you rename or remove that connection. Switching slots keeps + live sessions and selected files; names and paired devices are saved locally. + On mobile the sidebar collapses and a bar shows the open connection and its + status. +- Remembered devices. Each browser can create an opt-in device identity with a + non-extractable private key. After one manual fingerprint comparison, a + connection pairs with the verified peer; later sessions check fresh mutual + signatures bound to both connection fingerprints. A changed key is replaced + only on explicit choice. Forget a device or delete the identity at any time. Identity-enabled signaling uses v4; temporary v3 sessions remain available. -- Keep verified sessions open for “Send another file”, with separate acceptance - and storage for each file. -- Preserve the previous memory download until the next file is accepted. -- Add bounded queues (32 files per side), sending in both directions, per-file - progress and results, queue removal, and incoming-file decline. -- Add explicit Disconnect and live Send/Receive navigation. The initial receiver - can use Send to add files without reconnecting. Disconnect - aborts unfinished writes while preserving the last completed memory download. -- Document the hosted-first, serverless UX roadmap. -- Add shareable invitation links. Codes travel in the URL fragment, which is - never sent to the host and is removed from the address bar on opening. An - offer link opens a preview that suggests an idle connection (the one paired - with the sender's device first) and fills in the code without answering. An - answer link opened in the same browser connects the waiting sender tab; - elsewhere it shows the answer to copy. **Share link** uses the Web Share API - where available; **Copy link** and the bare code always remain. +- Verified sessions stay open for more files: bounded queues (32 files per + side), sending in both directions, per-file acceptance, progress, and + receipts, queue removal, and incoming-file decline. +- **Disconnect**, which aborts unfinished writes, and Send/Receive navigation + within a live session. The initial receiver can send files without + reconnecting. +- Shareable invitation links. Codes travel in the URL fragment, which is never + sent to the host and is removed from the address bar on opening. An offer + link opens a preview that suggests an idle connection (the one paired with + the sender's device first) and fills in the code without answering. An answer + link opened in the same browser connects the waiting sender tab; elsewhere it + shows the answer to copy. **Share link** uses the Web Share API where + available; **Copy link** and the bare code always remain. +- The hosted-first, serverless [UX roadmap](docs/ux-roadmap.md). ### Changed -- Each connection now remembers its own device instead of picking from a global - contact list. Opt in per connection; after manual fingerprint comparison, - “Remember this device for …” (ticked by default) pairs the verified peer. - A changed key is only replaced on explicit choice. Saved contacts are no - longer read. - Upgrade connection/session framing to v3 with per-file identifiers. Both peers must update; v2 codes are rejected before connection setup. - Connection codes are compressed to roughly half their length (`HC1.` plus @@ -44,12 +39,13 @@ 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. + link. Codes from earlier 0.0.5 drafts are rejected. - Replace the receive-storage choice with a single **Accept file** button that treats every file size the same: stream to Downloads where supported, else use the native save picker, else buffer up to 64 MiB in memory and hand it to Downloads automatically on completion. +- A completed memory download stays available via **Save again** until the next + file is accepted, including after Disconnect. ### Removed diff --git a/README.md b/README.md index bec1507..32af641 100644 --- a/README.md +++ b/README.md @@ -1,407 +1,348 @@ # HellCon -Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release notes -and compatibility changes. +Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release +notes and compatibility changes. -Browser-to-browser file sharing with Vue 3 and WebRTC. No accounts, signaling -backend, or server-side file storage. You exchange invitation links or -connection codes yourself, through any messenger. -Direct connections are the default. TURN relaying is optional and requires -explicit opt-in by both people; no relay is configured automatically. +Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts, no +signaling backend, and no server-side file storage: you exchange invitation links +or connection codes yourself, through any messenger. Connections are direct by +default. A TURN relay is used only when both people opt in. -## Connections workspace +This is experimental software, not independently audited or battle-tested. +Browser compatibility, network connectivity, and storage availability vary. -The sidebar holds your connections, starting with **Con 1**. Use **Add connection** -for another empty slot. Edit the name directly in the header; it saves when you -leave the field or press Enter. Empty names revert to the previous name. -Use **Remove** beside the name to open a confirmation dialog. Confirming removal -ends that slot's sessions in open tabs and forgets its remembered device; -downloaded files and your device identity remain. Removing the last slot leaves a fresh **Con 1**. -Each slot has its own setup, live session, and activity timeline. Switching slots -keeps active transfers and selected files alive while this tab stays open. -On small screens, **Show connections** opens the sidebar. +## Connections -Connection names, remembered devices, and the last 50 transfer results -per slot are saved in this browser. History includes filenames, sizes, directions, -times, and completion/decline/interruption results. It does not save file contents, -connection codes, or relay credentials. **Reset** clears the current session but -keeps the slot and history. Closing or reloading the page ends live sessions and -discards selected files; reconnect by exchanging fresh codes. The sidebar reports -this tab's session status, not remote device presence. +The sidebar lists your connections, starting with **Con 1**, up to 100. Each one +has its own setup and live session. -Each slot can remember one device. Under **Remembered device**, create the -browser's device identity once, then opt each slot in. After the first manual -fingerprint comparison, **Remember this device for …** (ticked by default) pairs -the verified peer with that slot; later sessions on it authenticate the peer -automatically. The slot name is the device's name. **Forget device** unpairs it. -The same device may be paired with several slots. Clearing site data removes saved -connections and trust. Storage failures are shown explicitly; temporary sessions -remain available. Up to 100 connection slots are supported. +- **Open** a connection by clicking its row. The row shows its name and this + tab's session status (not whether the remote device is online). +- **Rename** with the pen. Enter or leaving the field saves; Escape cancels. + An empty name keeps the previous one. +- **Remove** with ✕, then confirm. This ends the connection's sessions in all + open tabs and forgets its remembered device. Downloaded files and your device + identity remain. Removing the last connection leaves a fresh **Con 1**. +- **Add connection** creates another empty slot. -## How it works +Switching connections keeps active transfers and selected files alive while the +tab stays open. Closing or reloading the page ends live sessions and discards +selected files; reconnect with fresh codes. On small screens, **Show +connections** opens the sidebar, and the bar beside it shows the open connection +and its status. -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 as a - link (**Share link** where the browser supports it, or **Copy link**) - privately to the intended receiver through an authenticated channel. The bare - code remains available under **Show code instead**; there is no need to - transcribe either. -2. The receiver opens the link or pastes the link or code. An opened link shows a - preview and lets them choose which connection receives it; nothing is sent - until they click **Accept & create answer**. They send the answer link back. - Opened in the browser that holds the sender's tab, it connects that tab - directly; otherwise it shows the answer to copy, and the sender pastes it. - Gathering waits for completion, up to 30 seconds; a timeout fails rather than - quietly exporting incomplete connection information. -3. **Both people compare both full SHA-256 certificate fingerprints** over a - channel whose authenticity and integrity they trust, such as in person. - Your fingerprint must equal their “Their fingerprint”, and vice versa. - Compare every byte. Cancel on any mismatch. Both people must explicitly - confirm before the app sends the filename, size, MIME metadata, or contents. - On later connections, a remembered device’s fresh proof can replace manual - comparison (see Remembered devices below). -4. The receiver sees the filename and size and clicks **Accept file**. Files of - every size stream into the browser's download manager using a same-origin - service worker (HTTPS or localhost). This requires transferable streams and - service-worker support; Chromium and Brave have been tested with 120 MiB - files. Allow the download and keep the receiving tab open. File contents are - not uploaded to the web host. Without streaming support, the browser's native - save picker asks where to write the file. Without either, files up to 64 MiB - are buffered in memory and handed to Downloads on completion (**Save again** - repeats this); larger files cannot be received. Even capped memory transfers - may be too large on a memory-constrained device. -5. The sender waits for a receipt acknowledgment. For disk transfers, the receiver - sends this only after its writable stream closes successfully; for streaming - downloads, after handing all bytes to the browser; for memory transfers, - after constructing the complete download. A streaming receipt does not prove - the download manager successfully saved the file: check its final status in - Downloads. This also does not prove a human saved a memory download, nor that - a malicious receiver told the truth. Streamed transfers have no app-defined size cap; browser, filesystem, and - available storage limits apply. Byte counts must remain safe JavaScript integers - (at most 2^53 − 1 bytes). Files above 120 MiB have not been tested end to end. +Names and remembered devices are saved in this browser. Transfer history, file +contents, connection codes, and relay credentials are not. Clearing site data +removes saved connections, identities, and trust. If storage fails, the app says +so and temporary sessions still work. -Once both people verify, either person can add files without new codes or another -fingerprint comparison. Each side can queue up to 32 files (including its active -outgoing file). Each direction transfers one file at a time; sending and receiving -can happen simultaneously. Each file has its own progress, receipt and explicit -receiver acceptance. **Remove** drops a waiting local queue item; **Decline file** -rejects an incoming offer and lets the sender's queue continue. +## Sharing files -**Disconnect** ends the entire session, drops waiting files and aborts unfinished -disk writes. To cancel an already active transfer, disconnect; cancelling only an -active file is not supported. A completed memory transfer stays available via **Save again** after -disconnect, until the next acceptance replaces it. **Reset** discards it and -returns to setup. Before connecting, Send/Receive chooses who starts the connection. Once -verified, these controls navigate to the sending and receiving sections without -reconnecting. The initial receiver can click **Send**, then **Add files to send**. +1. **Create a code.** The person starting picks one or more files, chooses a + STUN provider (PageQuit by default, Google, Cloudflare, custom, or None), and + clicks **Create code**. They send the link privately to the receiver through + an authenticated channel, with **Share link** where supported or **Copy + link**. The bare code is under **Show code instead**. +2. **Answer it.** The receiver opens the link or pastes the link or code. An + opened link shows a preview and lets them pick 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; elsewhere it shows the answer for the sender to + paste. Gathering waits up to 30 seconds and fails rather than exporting + incomplete connection information. +3. **Compare fingerprints.** Both people compare **both full SHA-256 certificate + fingerprints** over a channel they trust for authenticity, such as in person. + Your fingerprint must equal their “Their fingerprint”, and vice versa. Compare + every byte and cancel on any mismatch. Nothing about the files is sent until + both people confirm. A [remembered device](#remembered-devices) can replace + this step on later connections. +4. **Accept the file.** The receiver sees the filename and size and clicks + **Accept file**. Files stream into the browser's download manager through a + same-origin service worker (HTTPS or localhost; Chromium and Brave are tested + with 120 MiB files). Without streaming support, the native save picker is + used. Without either, files up to 64 MiB are buffered in memory and handed to + Downloads on completion (**Save again** repeats this); larger files cannot be + received. Keep the receiving tab open. +5. **Receipt.** The sender waits for the receiver's acknowledgment, sent after + the disk write closes, after all bytes reach the browser's download manager, + or after the memory download is built. A receipt does not prove the download + manager saved the file (check Downloads), nor that a malicious receiver told + the truth. -Keep both tabs open. Switching browser tabs or apps does not explicitly cancel -the session, although browsers and mobile operating systems can suspend pages. -Pending verification/acceptance expires after five minutes; stalled transfers -expire after one minute. Idle verified sessions stay open. Lost connections need -fresh codes. File transfers use protocol **v3**; codes from older builds are -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. +Streamed transfers have no app-defined size cap; browser, filesystem, and storage +limits apply, and byte counts must stay below 2^53. Files above 120 MiB have not +been tested end to end. -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. -After a connection actually closes or fails, use Reset and exchange a **new offer -and new answer**. Old codes refer to the closed connection and cannot reopen it. -Reset returns the page to its initial ready state. For a local test, open two -separate browser tabs or windows; use Disconnect before changing the setup role. Use the specific error shown in red to diagnose -failures; if a configured STUN server is unreachable, try None for a local test. +### During a session -### Connection diagnostics and first-version comparison +Once verified, either person can add files without new codes. Each side queues +up to 32 files, including its active one. Each direction sends one file at a +time, and both directions can run at once. Every file has its own acceptance, +progress, and receipt. **Remove** drops a waiting file from your queue; +**Decline file** rejects an incoming one and lets the sender's queue continue. +Send/Receive chooses who starts before connecting; afterwards it switches between +the sending and receiving sections without reconnecting. -Expand **Connection diagnostics** to copy the last 80 timed events. The log -retains local/remote candidate type counts, candidate-pair states, selected -route types, DTLS transport states, and ICE check request/response counters after failure. -Four snapshots during ICE checking preserve evidence before failed pairs disappear. Final stats -are requested before closing the peer, with a 300 ms cleanup bound. A `?` means -the browser did not supply a counter; it does not mean zero. Addresses, raw SDP, -candidate IDs, credentials, server URLs and filenames are excluded. +**Disconnect** ends the session, drops waiting files, and aborts unfinished disk +writes; cancelling a single active file is not supported. A completed memory +download stays available via **Save again** until the next accepted file +replaces it. **Reset** discards it and returns to setup; the connection stays. -Same-machine success does not establish cross-device connectivity. Error 701 -alone does not establish the cause of a failed connection. A receiver shutdown -after both sides report completion can be normal sender cleanup. +Switching tabs or apps does not end the session, but browsers and mobile systems +may suspend pages. Pending verification or acceptance expires after five +minutes, stalled transfers after one minute; idle verified sessions stay open. -The comparison with the first commit and controlled test results are recorded in -[the investigation notes](docs/connection-investigation.md). Run the isolated -ICE experiment with `node scripts/compare-ice.mjs firefox` or replace `firefox` -with `chromium`. This uses local browser peers and deliberately unusable offer -ports plus a 20-second answer delay; it is **not a cross-device test**. Add -`--normal-candidates` to preserve the real candidate ports. No firewall changes, -TURN credentials or public STUN service are required. +### Troubleshooting + +- A pasted answer that is invalid, an offer in the answer field, or an answer for + a different code is reported without discarding the live offer. Fix it and + click **Connect** again. +- After a connection closes or fails, use **Reset** and exchange a new offer and + answer. Old codes cannot reopen it. +- If a configured STUN server is unreachable, try None for a local test. For a + local test, use two tabs or windows, and Disconnect before changing roles. +- Expand **Connection diagnostics** to copy the last 80 timed events: candidate + type counts, candidate-pair and DTLS states, selected route types, and ICE + check counters, with snapshots taken before failed pairs disappear. A `?` means + the browser supplied no value, not zero. Addresses, SDP, candidate IDs, + credentials, server URLs, and filenames are excluded. + +Same-machine success does not show cross-device connectivity, and error 701 +alone does not identify a cause. See [the investigation +notes](docs/connection-investigation.md) for the comparison with the first +version. `node scripts/compare-ice.mjs firefox` (or `chromium`) runs a local ICE +experiment with deliberately unusable offer ports and a 20-second answer delay; +add `--normal-candidates` to keep real ports. It is **not a cross-device test**. ## Remembered devices -On the hosted app, expand **Remembered device** and choose **Create device -identity** on both browsers; this also enables **Use my device identity on this -connection** for the current slot. Exchange codes and compare both full -fingerprints for the first pairing. Leave **Remember this device for …** ticked -before confirming, and the verified peer is paired with this connection. +Each connection can remember one device, so later sessions skip the manual +fingerprint comparison. -Later sessions on that connection need no extra steps: HellCon checks fresh -signed proofs bound to both device keys and both connection fingerprints. A -matching paired key replaces manual fingerprint comparison; file acceptance is -still required. A changed or missing identity requires manual comparison and -only replaces the paired device if you tick **Replace the paired device**. -Connection names stay local. Public identities in codes can link sessions. +1. On both browsers, expand **Remembered device** and choose **Create device + identity**. This also turns on **Use my device identity on this connection**; + each connection has its own opt-in, and new connections start without it. +2. Connect and compare full fingerprints once. Leave **Remember this device for + …** ticked when confirming, and the verified peer is paired with this + connection. The connection's name is the device's name and never leaves + this browser. -Use **Forget device** to unpair a connection, or explicitly delete your identity. -Clearing site data loses saved trust and requires pairing again. Browser-stored -keys remain usable by trusted app code and are not protection against a malicious -host. Each connection keeps its own opt-in; new connections start without it. -Storage failure leaves temporary connections available. +Later sessions check fresh signed proofs bound to both device keys and both +connection fingerprints; file acceptance is still required. A changed or missing +identity falls back to manual comparison and only replaces the paired device if +you tick **Replace the paired device**. **Forget device** unpairs it. One device +can be paired with several connections. -Identity-enabled codes use signaling version **4** and require the new build. -Temporary codes retain version **3**. If only one peer enables identity, the -current build uses manual comparison without remembering that connection. -See [the identity protocol and storage](docs/device-identities.md). +Identity-enabled codes use signaling **v4**; temporary codes use **v3**. If only +one peer enables identity, the session uses manual comparison without +remembering. Public identities in codes can link sessions. Browser-stored keys +are usable by any code the host serves, so they do not protect against a +malicious host. See [the identity protocol and storage](docs/device-identities.md). -## Network privacy and optional TURN +## Privacy and security -STUN discovers externally reachable addresses. Its operator can see your public -IP address and request metadata, but STUN does not relay file contents. Lookups, -retries and connectivity checks may involve multiple packets. Choosing None -avoids contacting a configured STUN provider; direct connectivity depends on -addresses, routing, browser policy and firewalls, not simply whether peers share -one network. A VPN is not automatically a guarantee against address disclosure. +### Codes and links -Connection codes are **compressed and Base64url-encoded, not encrypted** -(`HC1.` followed by deflated JSON). They contain SDP, including candidate -addresses, temporary ICE credentials and certificate fingerprints. Peers and -anyone who sees these codes (including the messaging service used to exchange -them) may learn connection details. Local addresses may be obscured by the -browser, but this app does not provide anonymity. Treat codes as private session -information; do not publish them. +Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.` +followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE +credentials, and certificate fingerprints. Anyone who sees a code, including the +messaging service, may learn these details. Treat codes as private and do not +publish them. The browser may obscure local addresses, but this app does not +provide anonymity. 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). +the host, and the app removes it from the address bar on opening. Otherwise a +link is as sensitive as its code; browser history, including synced history, may +keep it. Opening an offer link never answers automatically. Answer links reach +the waiting tab over a same-origin `BroadcastChannel`. See [the invitation +design](docs/invitations.md). -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 -relay**, supply their authorized TURN URL, username and password, and generate -new codes. Otherwise TURN URLs are rejected in the STUN field and codes with -relay candidates are rejected. Enabling TURN allows the browser to contact that -relay during gathering and select a relay route when needed. This does not force -relay-only routing or hide your IP from the peer. A remote peer can independently -proxy their own traffic; the opt-in controls this app's configuration and the -relay candidates it accepts, not arbitrary software run by the other person. +File transfers use protocol **v3**; codes from older builds are rejected before +connecting. -When a credential endpoint is configured (including the local development setup -below), **Use the configured relay with temporary credentials** replaces manual -credential entry. The app fetches fresh credentials for each new connection, -only after TURN opt-in. The issued relay address, username and masked password -appear in read-only fields while the connection is active. Uncheck it to use a -different relay manually. +### STUN and optional TURN -TURN credentials stay in the current component's memory; the app does not persist -them or include them in codes. The relay receives its authentication exchange and -can observe addresses, timing and traffic volume, and may charge for bandwidth. -Resetting, cancelling or ending a connection clears TURN consent; -check the option again before creating another relayed connection. -File traffic remains DTLS encrypted through the relay. The web host, DNS resolver, -and code-exchange service are also relevant third parties. +STUN discovers externally reachable addresses. Its operator sees your public IP +and request metadata but never file contents. Choosing None avoids contacting a +STUN provider; direct connectivity then depends on addresses, routing, browser +policy, and firewalls. A VPN does not guarantee against address disclosure. -## Security model and limits +Restrictive NATs or firewalls can block direct connections, and there is no +silent TURN fallback. To permit a relay, both people check **Allow a TURN +relay**, enter their authorized TURN URL, username, and password, and create new +codes. Otherwise TURN URLs and codes with relay candidates are rejected. Enabling +TURN lets the browser use a relay route when needed; it does not force relay-only +routing or hide your IP from the peer, and it cannot control software the other +person runs. -Data channels use **SCTP over DTLS**, which provides transport confidentiality and -integrity. This is not DTLS-SRTP (the media transport). DTLS authenticates the -certificate in the connection description; an independently authenticated full -fingerprint comparison binds that certificate to the intended peer. Comparing -fingerprints through a channel an attacker can rewrite provides no such assurance. +When a credential endpoint is configured, **Use the configured relay with +temporary credentials** fetches fresh credentials for each connection after +opt-in and shows them read-only. Uncheck it to enter a relay manually. TURN +credentials stay in memory and never enter codes. The relay sees its +authentication exchange, addresses, timing, and traffic volume, but file traffic +remains DTLS-encrypted. Reset, cancel, or a closed connection clears TURN +consent; opt in again for the next relayed connection. -You must trust your browser, device, and **the JavaScript you load**. A compromised -host or build can steal plaintext or falsify the verification display. Serve the -production build over HTTPS, or run a verified build you control on localhost. -HTTPS protects delivery against network tampering, not against a malicious host. -The app does not upload files to its web host in this implementation; that is a -property of this code, not a guarantee against a host serving different code. +### Security model and limits -The protocol accepts one ordered, reliable data channel, bounded metadata and -messages, exact declared byte counts, and at most one accepted file per direction. -Monotonic per-direction file IDs bind offers, data, and receipts to their files. It rejects unexpected -states, excess data and duplicate metadata. An acknowledged 1 MiB send window per transfer -and a bounded receive queue limit buffering during disk writes. Files are treated -as opaque downloads; metadata is not rendered as HTML. Encryption does not make -a file safe to open. These limits reduce denial-of-service exposure but do not -eliminate browser, device, network, or malicious-peer risks. +Data channels use **SCTP over DTLS** for transport confidentiality and integrity. +DTLS authenticates the certificate in the connection description; comparing full +fingerprints over an independently authenticated channel binds that certificate +to the intended peer. Comparing over a channel an attacker can rewrite proves +nothing. -For deployment, serve `dist/` as static files over HTTPS. Do not expose the Vite -dev or preview server as the production service. Configure hosting headers such -as `Content-Security-Policy` (including `frame-ancestors 'none'`), -`X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. A baseline -CSP for this build is `default-src 'self'; script-src 'self'; style-src 'self' -'unsafe-inline'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri -'none'; frame-ancestors 'none'`. Inline styles are currently used for progress and -Vue visibility. Test headers on the actual host; CSP is defense in depth and is -not a substitute for trusting the host or a portable WebRTC egress filter. -`robots.txt` and indexing metadata are crawler requests, not access control. +You must trust your browser, device, and **the JavaScript you load**. A +compromised host or build can steal plaintext or falsify the verification +display. HTTPS protects delivery, not against a malicious host. This code does +not upload files to its host, but that is no guarantee against a host serving +different code. The web host, DNS resolver, and code-exchange service are also +relevant third parties. -Deploy the complete `dist/` directory, including `download/worker.js`, served -with a JavaScript MIME type. The download worker has scope `download/` only: -it does not control the app page, cache the app, or proxy normal web requests. -It serves single-use, randomly named download URLs from incoming browser -streams, with bounded buffering. The default CSP above permits this; custom -policies must permit same-origin workers and frames. No third-party helper, -download backend, or additional hosting service is required. Closing/resetting -an unfinished transfer aborts it; interrupted transfers must restart. +The protocol accepts one ordered, reliable data channel with bounded metadata +and messages, exact declared byte counts, and at most one accepted file per +direction. Monotonic per-direction file IDs bind offers, data, and receipts to +their files; unexpected states, excess data, and duplicate metadata are rejected. +A 1 MiB acknowledged send window and a bounded receive queue limit buffering. +Files are opaque downloads and metadata is never rendered as HTML. Encryption +does not make a file safe to open. These limits reduce, but do not eliminate, +denial-of-service and malicious-peer risks. -## Build and self-host +## Self-hosting -From a clone of the repository, run `bun install --frozen-lockfile` and -`bun run build`. Serve the whole `dist/` directory, including `assets/` and -`download/`, using a static web server over HTTPS. For local build inspection, -run `bun run preview` and open the printed localhost URL. +```sh +bun install --frozen-lockfile +bun run build +``` + +Serve the whole `dist/` directory over HTTPS as static files, including +`assets/` and `download/worker.js` (with a JavaScript MIME type). No backend or +third-party helper is needed. Do not expose the Vite dev or preview server; +`bun run preview` is for local inspection only. + +Configure `Content-Security-Policy`, `X-Content-Type-Options: nosniff`, and +`Referrer-Policy: no-referrer`. A baseline CSP for this build: + +```text +default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; +img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; +frame-ancestors 'none' +``` + +Inline styles are used for progress and Vue visibility. Custom policies must +permit same-origin workers and frames. Test headers on the actual host; CSP is +defense in depth, not a substitute for trusting the host or a WebRTC egress +filter. `robots.txt` and indexing metadata are crawler requests, not access +control. + +The download worker's scope is `download/` only: it does not control the app +page, cache the app, or proxy other requests. It serves single-use, randomly +named URLs from incoming streams with bounded buffering. Closing or resetting an +unfinished transfer aborts it; interrupted transfers must restart. ## Development -### Local WebTorrent tracker - -The repository includes [our tracker Dockerfile](tracker/Dockerfile) and a -separate [Compose service](compose.tracker.yaml), built from the official Node -image and a locked upstream `bittorrent-tracker` release. With Docker running: - -```sh -bun run tracker:up # build and start ws://127.0.0.1:8000 -bun run test:tracker # integration checks inside the test image -bun run tracker:down -``` - -See [tracker setup and deployment](tracker/README.md) for configuration and VPS -use. The tracker container is ready for development; automatic reconnect in -the browser is still [planned](docs/webtorrent-reconnect.md). Current app -connections continue to use manual codes. - -### Local STUN/TURN environment (Linux) - -Keep Vite on the host for hot reload; only coturn runs in Docker. Both bind to -loopback, so use two browser tabs on this machine. No DNS, certificates, firewall -changes or production services are needed. Nothing is enabled at boot, and the -container has no automatic restart policy. - -```sh -# Start Docker only when needed (if it isn't already running). -sudo systemctl start docker.service -# If you just joined the docker group, log in again or run: newgrp docker -bun install --frozen-lockfile -bun run dev:setup # creates ignored .env.development, without overwriting it -bun run turn:up -bun run dev # open the printed localhost URL in two tabs -``` - -Pick a file in the sender tab, choose Receive in the other, and check **Allow a -TURN relay** in both tabs. Leave **Use the configured relay with temporary -credentials** checked. Exchange codes and compare fingerprints as usual. Reset, -failure or disconnect clears consent, so check it again for each connection. -STUN defaults to the local server; TURN remains opt-in, with direct routes preferred. - -```sh -bun run test # protocol and temporary-credential unit tests -bun run test:turn # real Chromium file transfer, forced TURN/UDP -bun run test:turn --tcp # same test, TURN/TCP only -bun run build -bun run test:browser # direct-path browser regressions and axe accessibility checks -docker compose --env-file .env.development logs --tail=50 coturn -``` - -The TURN checks start and stop their own Vite server and isolated browser profiles; -coturn must already be running. They obtain real temporary credentials, force -relay-only routing, assert selected relay candidates on both ends, verify exact -received bytes and receipts, and exercise cancellation and reconnection. TCP here -means browser-to-TURN transport; relay-to-peer traffic is UDP. These same-machine -checks do not test Internet NATs or a remote server's firewall. - -Stop Vite with Ctrl-C, then: - -```sh -bun run turn:down -# Optional: stop Docker too, after finishing any other containers. -sudo systemctl stop docker.service docker.socket containerd.service -``` - -`.env.development` contains the private shared `TURN_SECRET`, server-side -`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` settings. -See [.env.example](.env.example). The secret never enters the client bundle. -Compose passes it directly to coturn; no config-file environment substitution is -assumed. If changing the port, update both `TURN_PORT` and `VITE_STUN_URL`, then -rerun `turn:up` and restart Vite. The image is pinned to a concrete release; -loopback listeners and UDP relay ports 49160–49200 are defined in [compose.yaml](compose.yaml). -Loopback peer access is explicitly allowed for these local tests. - -The credential endpoint is **development-only**, implemented as Vite middleware. -It isn't included in `dist/` or `vite preview`. Production builds ignore -`.env.development` and retain the existing static/manual configuration. To reuse -the client integration later, set `VITE_ICE_ENDPOINT` and `VITE_STUN_URL` when -building and implement the same JSON endpoint behind your production access -policy. [dev/ice-server.ts](dev/ice-server.ts) contains the HMAC issuance logic. -There are no accounts or room sessions in this app to authorize production -credential issuance automatically. Don't expose this development endpoint or -reuse the loopback-permitting Compose configuration as a public relay. - -Credentials expire after one hour; each new code exchange fetches fresh ones. -Automatic renewal during long transfers is not implemented because this app -uses manual signaling. Keep development transfers below that duration; expired -or failed sessions need fresh codes. - -Configuration references: [coturn Docker usage](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md) -and [coturn configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf). - -### Existing checks and static build - -Use Bun for dependency installation and Node.js 22.18+ for the scripts and tests. -All application code, Vue scripts, development middleware, and checks use strict -TypeScript. `vue-tsc` checks both TypeScript and Vue templates, and runs before -every production build. TypeScript stays on 5.9 until Vue's checker supports the -TypeScript 7 compiler. - -Vite 8 supplies VoidZero's Rolldown bundler and Oxc transforms. The only added -development dependencies are TypeScript, `vue-tsc`, and Node types. Node runs -the TypeScript tests directly; no separate test framework or TS loader is needed. +Use Bun to install dependencies and Node.js 22.18+ to run scripts and tests. All +code is strict TypeScript; `vue-tsc` checks scripts and templates and runs before +every production build. TypeScript stays on 6.0 until Vue's checker supports +TypeScript 7. Vite 8 supplies the Rolldown bundler and Oxc transforms. Node runs +the TypeScript tests directly, with no test framework or loader. The lockfile +pins dependencies; review updates and advisories before publishing a build. ```sh bun install --frozen-lockfile bun run dev bun run typecheck -bun run test +bun run test # unit tests bun run build -bun run test:browser # local Chromium integration checks against dist/ -bun run test:browser --connections # sidebar, persistence, live switching, and mobile layout -bun run test:download # real hosted downloads, including 120 MiB, with native picker disabled -bun run test:cross-browser # Brave sender → Firefox receiver -bun run preview # local build inspection only +bun run test:browser # Chromium integration and axe checks against dist/ +bun run test:browser --connections # sidebar, persistence, live switching, mobile layout +bun run test:download # real hosted downloads up to 120 MiB, no native picker +bun run test:cross-browser # Brave sender → Firefox receiver bun audit ``` -The lockfile pins dependencies. Review dependency updates and advisories before -publishing a build. Protocol regression tests cover verification gating, malformed -messages, size limits, cancellation, receipt acknowledgment, and relay opt-in. -The browser check requires Chromium at `/usr/bin/chromium` (override with -`CHROMIUM_PATH`); it uses an isolated temporary profile and a loopback server. -Run `CHROMIUM_PATH=/usr/bin/brave bun run test:download` for the streaming -download check in Brave. Worker tests cover byte counts, backpressure, single-use -URLs, and browser/app cancellation; integration checks verify the actual saved bytes. -The cross-browser check uses Brave and Firefox at `/usr/bin/brave` and -`/usr/bin/firefox` (override with `BRAVE_PATH` and `FIREFOX_PATH`). It checks -that the received file remains downloadable after the sender disconnects. -Pass `--reverse` to test Firefox → Brave, or `--default-network` to use PageQuit -STUN instead of the local test's default None. These checks use temporary -browser profiles and do not modify your normal browser settings. +Browser checks run against `dist/`, so build first. They use isolated temporary +profiles and a loopback server, and never touch your normal browser settings. -This is experimental software, not independently audited or battle-tested. -Browser compatibility, network connectivity and storage availability vary. +- `test:browser` and `test:download` need Chromium at `/usr/bin/chromium` + (override with `CHROMIUM_PATH`, e.g. `/usr/bin/brave`). They verify the actual + saved bytes; worker tests cover byte counts, backpressure, single-use URLs, and + cancellation. +- `test:cross-browser` needs `/usr/bin/brave` and `/usr/bin/firefox` (override + with `BRAVE_PATH` and `FIREFOX_PATH`) and checks the received file stays + downloadable after the sender disconnects. Pass `--reverse` for Firefox → + Brave, or `--default-network` for PageQuit STUN instead of None. + +### Local STUN/TURN (Linux) + +Vite stays on the host for hot reload; only coturn runs in Docker. Both bind to +loopback, so test with two tabs on this machine. Nothing starts at boot and the +container has no restart policy. + +```sh +sudo systemctl start docker.service # if not already running +# After joining the docker group, log in again or run: newgrp docker +bun install --frozen-lockfile +bun run dev:setup # creates .env.development without overwriting it +bun run turn:up +bun run dev # open the printed URL in two tabs +``` + +Pick a file in one tab and choose Receive in the other. Check **Allow a TURN +relay** in both, leave **Use the configured relay with temporary credentials** +checked, then exchange codes as usual. Consent clears after each connection. + +```sh +bun run test:turn # real file transfer over forced TURN/UDP +bun run test:turn --tcp # browser-to-TURN over TCP only +docker compose --env-file .env.development logs --tail=50 coturn +bun run turn:down +sudo systemctl stop docker.service docker.socket containerd.service # optional +``` + +The TURN checks start their own Vite server and browsers but need coturn +running. They force relay-only routing, assert relay candidates on both ends, +verify received bytes and receipts, and exercise cancellation and reconnection. +They do not test Internet NATs or a remote firewall. + +`.env.development` holds the private `TURN_SECRET`, server-side +`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` (see +[.env.example](.env.example)). The secret never enters the client bundle. When +changing the port, update `TURN_PORT` and `VITE_STUN_URL`, rerun `turn:up`, and +restart Vite. Listeners, relay ports 49160–49200, and the pinned image are in +[compose.yaml](compose.yaml). + +The credential endpoint is **development-only** Vite middleware and is not part +of `dist/` or `vite preview`. To use it in production, set `VITE_ICE_ENDPOINT` +and `VITE_STUN_URL` at build time and implement the same JSON endpoint behind +your own access policy; [dev/ice-server.ts](dev/ice-server.ts) has the HMAC +logic. Never expose the development endpoint or the loopback-permitting Compose +setup as a public relay. Credentials expire after one hour and are not renewed +during a transfer. See the [coturn Docker +guide](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md) and +[configuration +reference](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf). + +### Local WebTorrent tracker + +[tracker/Dockerfile](tracker/Dockerfile) and +[compose.tracker.yaml](compose.tracker.yaml) build a locked `bittorrent-tracker` +release on the official Node image: + +```sh +bun run tracker:up # build and start ws://127.0.0.1:8000 +bun run test:tracker # integration checks inside the test image +bun run tracker:down +``` + +See [the tracker README](tracker/README.md) for configuration and VPS use. +Automatic reconnect in the browser is still +[planned](docs/webtorrent-reconnect.md); the app uses manual codes. + +## Roadmap + +See [the hosted-first UX roadmap](docs/ux-roadmap.md). ## License -MIT — see `LICENSE`. - -## UX roadmap - -See [the hosted-first UX roadmap](docs/ux-roadmap.md) for repeat transfers, file -queues and bidirectional sessions, remembered devices, invitations, and guided setup. +MIT — see [LICENSE](LICENSE). diff --git a/docs/ux-roadmap.md b/docs/ux-roadmap.md index 693a6b2..6ed9b43 100644 --- a/docs/ux-roadmap.md +++ b/docs/ux-roadmap.md @@ -12,17 +12,15 @@ feature is planned, not implemented; the sections below describe current behavio The app title and connection list live in a sidebar. The first slot is **Con 1**; users add subsequent slots explicitly and can rename them. Selecting a slot opens -its setup, transfer controls, and persistent activity timeline. Cached workspaces +its setup and transfer controls. Cached workspaces keep live sessions and file selections intact while navigating between slots. The sidebar collapses on mobile; network configuration is expandable. -IndexedDB stores slot names, paired devices, and up to 50 transfer -results per slot. Each result includes its direction, filename, size, timestamp, -and completion/decline/interruption status. File contents and connection codes -are never stored. Slot mutations are transactional and other tabs refresh their -lists after changes. Storage failures show an explicit warning. +IndexedDB stores slot names and paired devices. Transfer history, file contents, +and connection codes are not stored. Slot mutations are transactional, and other +tabs refresh their lists after changes. Storage failures show an explicit warning. -Disconnect and Reset retain history. Reloading ends live sessions and requires +Disconnect and Reset keep the slot. Reloading ends live sessions and requires fresh codes; a slot's paired device is authenticated by fresh signed proofs, and setup re-reads it from storage so a device forgotten elsewhere is not trusted. @@ -46,7 +44,7 @@ that compatibility path with protocol v3; both peers now need the current build. Session ownership is independent of the initial Send/Receive setup choice. After verification, Send/Receive navigates between sections while preserving the session. Both people can select or drop multiple files and add more while transferring. Each local queue is capped at 32 including -its active outgoing file; a rolling list retains the last 50 results. +its active outgoing file. The arbitration decision is one sequential queue per direction, permitting two active files total. Simultaneous offers therefore never compete for one global diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 2cb4c1e..0bb3a73 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -239,68 +239,76 @@ try { if (connections) { const sender = await page(), receiver = await page(origin.replace('127.0.0.1', 'localhost')); const selectConnection = (session: string, name: string) => evaluate(session, (name: string) => { - const button = [...document.querySelectorAll('.connection-link')].find(item => item.querySelector('.connection-name')?.textContent === name); - if (!button) throw new Error('Missing connection: ' + name); - button.click(); + const label = [...document.querySelectorAll('.connection-name')].find(item => item.textContent === name); + if (!label) throw new Error('Missing connection: ' + name); + label.click(); }, name); 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('.main-pane h1')?.textContent), 'Con 1'); assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.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 screenshot(sender, 'connections-desktop'); - await evaluate(sender, () => window.__hellcon.element('#connection-name').focus()); - await input(sender, '#connection-name', 'Work laptop'); - await evaluate(sender, () => window.__hellcon.element('#connection-name').blur()); + assert.equal(await evaluate(sender, () => !!document.querySelector('.connection-rename-input')), false, 'Names start locked'); + await click(sender, 'Rename Con 1'); + assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('connection-rename-input')), true, 'The pen focuses the name editor'); + await input(sender, '.connection-rename-input', 'Work laptop'); + await evaluate(sender, () => window.__hellcon.element('.connection-rename-input').blur()); await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop'); - await evaluate(sender, () => window.__hellcon.element('#connection-name').focus()); - await input(sender, '#connection-name', ' '); - await evaluate(sender, () => window.__hellcon.element('#connection-name').blur()); - assert.equal(await evaluate(sender, () => window.__hellcon.element('#connection-name').value), 'Work laptop'); - await evaluate(sender, () => window.__hellcon.element('#connection-name').focus()); - await input(sender, '#connection-name', 'Work laptop '); + await click(sender, 'Rename Work laptop'); + await input(sender, '.connection-rename-input', ' '); + await evaluate(sender, () => window.__hellcon.element('.connection-rename-input').blur()); + assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop'); + await click(sender, 'Rename Work laptop'); + await input(sender, '.connection-rename-input', 'Work laptop '); await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender); await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender); - assert.equal(await evaluate(sender, () => window.__hellcon.element('#connection-name').value), 'Work laptop'); - assert.equal(await evaluate(sender, () => document.activeElement?.id === 'connection-name'), false); + assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop'); + assert.equal(await evaluate(sender, () => !!document.querySelector('.connection-rename-input')), false, 'Enter relocks the name'); + await click(sender, 'Rename Work laptop'); + await input(sender, '.connection-rename-input', 'Cancelled name'); + await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, sender); + await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, sender); + assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop', 'Escape discards the draft'); + assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('edit-action')), true, 'Escape returns focus to the pen'); await click(receiver, 'Receive'); await connect(sender, receiver, 4097); const fingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)); await click(sender, 'Add connection'); - await wait(sender, () => document.querySelector('.title-line h1')?.textContent === 'Con 2'); + await wait(sender, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2'); assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false); await click(receiver, 'Accept file'); - await wait(sender, () => document.querySelector('.connection-link .connection-preview')?.textContent === 'browser-test.bin'); - assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0, 'Hidden session activity must stay in its own slot'); + await wait(sender, () => document.querySelector('.connection-item .connection-status')?.textContent === 'Connected'); + assert.equal(await evaluate(sender, () => document.querySelector('.connection-nav')?.textContent?.includes('browser-test.bin')), false, 'The sidebar shows connection status instead of filenames'); + assert.equal(await evaluate(sender, () => !!document.querySelector('.activity-panel')), false, 'The workspace has no activity timeline'); await selectConnection(sender, 'Work laptop'); - await wait(sender, () => document.querySelector('.session-badge')?.textContent?.includes('Connected')); + await wait(sender, () => document.querySelector('.connection-item.selected .connection-status')?.textContent === 'Connected'); assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)), fingerprints); await evaluate(sender, () => window.__hellcon.chooseFile(1234, 'after-switch.bin')); await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin')); await click(receiver, 'Accept file'); - await wait(sender, () => document.querySelectorAll('.activity-item').length === 2); + await wait(sender, () => document.querySelector('.progress[aria-label="Sending progress"]')?.getAttribute('aria-valuenow') === '100'); const received = await evaluate(receiver, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element('a.download').href)).arrayBuffer()); return { size: bytes.length, valid: bytes.every(byte => byte === 123) }; }); assert.deepEqual(received, { size: 1234, valid: true }); await click(sender, 'Disconnect'); await click(sender, 'Reset'); - assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 2, 'Reset must preserve slot history'); - await checkAccessibility(sender, 'Connections with history'); - await screenshot(sender, 'connections-history'); + assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop', 'Reset keeps the connection slot'); + await checkAccessibility(sender, 'Connections after transfer'); + await screenshot(sender, 'connections-after-transfer'); await selectConnection(sender, 'Con 2'); await evaluate(sender, () => window.__hellcon.chooseFile(10, 'draft.bin')); await selectConnection(sender, 'Work laptop'); await selectConnection(sender, 'Con 2'); assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.panel li')].some(item => item.textContent?.includes('draft.bin'))), true, 'Selected file state survives slot switching'); await call('Page.navigate', { url: origin }, sender); - await wait(sender, () => document.querySelectorAll('.activity-item').length === 2); - assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Work laptop'); - assert.equal(await evaluate(sender, () => document.querySelector('.session-badge')?.textContent), 'Ready to connect'); + await wait(sender, () => !!document.querySelector('#stun-provider')); + assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop'); + assert.equal(await evaluate(sender, () => document.querySelector('.connection-item.selected .connection-status')?.textContent), 'Ready to connect'); await selectConnection(sender, 'Con 2'); - assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0); assert.equal(await evaluate(sender, () => document.querySelector('#file-input')?.files?.length), 0, 'File contents must not persist after reload'); - console.log('PASS: connections retain names and separate histories across reload; switching preserves live transfers and drafts; Reset preserves history.'); + console.log('PASS: connections retain names across reload; switching preserves live transfers and drafts; Reset keeps the slot without activity history.'); const other = await page(); await Promise.all([click(sender, 'Add connection'), click(other, 'Add connection')]); @@ -311,16 +319,18 @@ try { await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, sender); await selectConnection(sender, 'Work laptop'); + assert.deepEqual(await evaluate(sender, () => [document.querySelector('.mobile-current-name')?.textContent, document.querySelector('.mobile-current-status')?.textContent]), + ['Work laptop', 'Ready to connect'], 'Mobile shows the open connection and its status'); await checkAccessibility(sender, 'Connections mobile'); assert.equal(await evaluate(sender, () => document.documentElement.scrollWidth <= innerWidth), true, 'Mobile workspace must not overflow horizontally'); await screenshot(sender, 'connections-mobile'); - await click(sender, 'Remove'); + await click(sender, 'Show connections'); + await click(sender, 'Remove Work laptop'); await wait(sender, () => !!document.querySelector('dialog[open]')); await checkAccessibility(sender, 'Removal dialog mobile'); await screenshot(sender, 'connections-mobile-dialog'); await click(sender, 'Close dialog'); await wait(sender, () => !document.querySelector('dialog[open]')); - await click(sender, 'Show connections'); await checkAccessibility(sender, 'Connections mobile sidebar'); assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'flex'); await screenshot(sender, 'connections-mobile-sidebar'); @@ -333,8 +343,8 @@ try { await connect(sender, receiver, 1024); await selectConnection(sender, 'Con 2'); await selectConnection(other, 'Work laptop'); - await evaluate(other, () => window.__hellcon.element('.header-action').focus()); - await click(other, 'Remove'); + await evaluate(other, () => window.__hellcon.element('.connection-item.selected .remove-action').focus()); + await click(other, 'Remove Work laptop'); await wait(other, () => !!document.querySelector('dialog[open]')); assert.equal(await evaluate(other, () => document.activeElement?.textContent?.trim()), 'Keep connection', 'Dialog starts on its non-destructive action'); await checkAccessibility(other, 'Remove connection confirmation'); @@ -347,30 +357,82 @@ try { await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other); await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other); await wait(other, () => !document.querySelector('dialog[open]')); - assert.equal(await evaluate(other, () => document.activeElement?.classList.contains('header-action')), true, 'Dialog restores focus to the opener'); - await click(other, 'Remove'); + assert.equal(await evaluate(other, () => document.activeElement?.classList.contains('remove-action')), true, 'Dialog restores focus to the opener'); + await click(other, 'Remove Work laptop'); await click(other, 'Keep connection'); assert.equal(await evaluate(other, () => document.querySelectorAll('.connection-link').length), 4); - await click(other, 'Remove'); await click(other, 'Remove connection'); + await click(sender, 'Remove Work laptop'); + await wait(sender, () => !!document.querySelector('dialog[open]')); + await click(other, 'Remove Work laptop'); await click(other, 'Remove connection'); await wait(other, () => document.querySelectorAll('.connection-link').length === 3); await wait(sender, () => document.querySelectorAll('.connection-link').length === 3); + await wait(sender, () => !document.querySelector('dialog[open]')); await wait(receiver, () => !document.querySelector('.incoming')); await call('Page.navigate', { url: origin }, sender); await wait(sender, () => !!document.querySelector('#stun-provider')); assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Work laptop')), false); for (let count = 3; count > 0; count--) { - const oldName = await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent); - await click(sender, 'Remove'); await click(sender, 'Remove connection'); + const oldName = await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent); + await click(sender, `Remove ${oldName}`); await click(sender, 'Remove connection'); await wait(sender, () => !document.querySelector('dialog[open]')); assert.equal(await evaluate(sender, () => document.querySelectorAll('.connection-link').length), Math.max(1, count - 1)); - assert.notEqual(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), oldName); + assert.notEqual(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), oldName); } - assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1'); - assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0); + assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1'); await call('Page.navigate', { url: origin }, sender); await wait(sender, () => !!document.querySelector('#stun-provider')); assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Con 1']); console.log('PASS: removal can be cancelled, persists across reload, closes cached sessions in other tabs, and replaces the last slot with a fresh Con 1.'); + await click(sender, 'Add connection'); + await wait(sender, () => document.querySelectorAll('.connection-link').length === 2); + await selectConnection(sender, 'Con 1'); + const spareName = await evaluate(sender, () => document.querySelectorAll('.connection-name')[1]?.textContent); + await click(sender, `Rename ${spareName}`); + await input(sender, '.connection-rename-input', 'Spare device'); + await evaluate(sender, () => window.__hellcon.element('.connection-rename-input').blur()); + await wait(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Spare device')); + assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1', 'Renaming another row keeps the current connection'); + await click(sender, 'Remove Spare device'); + assert.match(await dialogText(sender), /Remove Spare device\?/); + await click(sender, 'Remove connection'); + await wait(sender, () => document.querySelectorAll('.connection-link').length === 1); + assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1', 'Removing another row keeps the current connection'); + assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('connection-link')), true, 'Focus returns to the remaining connection after removal'); + console.log('PASS: sidebar actions target their own connection without changing the active workspace.'); + await evaluate(sender, async () => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('hellcon-connections', 1); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + await new Promise((resolve, reject) => { + const tx = db.transaction('connections', 'readwrite'); + const store = tx.objectStore('connections'); + const request = store.getAll(); + request.onsuccess = () => store.put({ ...request.result[0], history: [{ name: 'old-file.bin' }] }); + tx.oncomplete = () => resolve(); + tx.onerror = tx.onabort = () => reject(tx.error); + }); + db.close(); + }); + await call('Page.navigate', { url: origin }, sender); + await wait(sender, () => !!document.querySelector('#stun-provider')); + const oldHistoryRemoved = await evaluate(sender, async () => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('hellcon-connections', 1); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + const record = await new Promise>((resolve, reject) => { + const request = db.transaction('connections', 'readonly').objectStore('connections').getAll(); + request.onsuccess = () => resolve(request.result[0]); + request.onerror = () => reject(request.error); + }); + db.close(); + return { name: record.name, hasHistory: Object.hasOwn(record, 'history') }; + }); + assert.deepEqual(oldHistoryRemoved, { name: 'Con 1', hasHistory: false }, 'Loading an old slot removes saved transfer history'); + console.log('PASS: legacy transfer history is removed from saved connections on load.'); assert.deepEqual(browserErrors, []); } else if (streaming) { const sender = await page(), receiver = await page(); @@ -607,17 +669,17 @@ try { // 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 wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2'); await evaluate(invitedPaired, (code: string) => { location.hash = code; }, offer); await wait(invitedPaired, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files')); assert.match(await dialogText(invitedPaired), /matches the paired device of Con 1/); assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element('#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, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1'); assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element('#offer-input').value), offer); - await evaluate(invitedPaired, () => [...document.querySelectorAll('.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 evaluate(invitedPaired, () => [...document.querySelectorAll('.connection-name')].find(item => item.textContent === 'Con 2')?.click()); + await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2'); + await click(invitedPaired, 'Remove Con 2'); await click(invitedPaired, 'Remove connection'); await wait(invitedPaired, () => document.querySelectorAll('.connection-link').length === 1); await closePage(invitedPaired); console.log('PASS: an invitation from a paired device suggests its slot over the current one and hands the code to it.'); diff --git a/src/App.vue b/src/App.vue index 11216a9..2747251 100644 --- a/src/App.vue +++ b/src/App.vue @@ -2,9 +2,8 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'; import ConnectionWorkspace from './components/ConnectionWorkspace.vue'; import AppDialog from './components/AppDialog.vue'; -import EditableName from './components/EditableName.vue'; import InvitationDialog from './components/InvitationDialog.vue'; -import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionActivity, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts'; +import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts'; import { takeFragment } from './lib/invitations.ts'; import { asError } from './lib/validation.ts'; @@ -17,7 +16,10 @@ const connections = ref([]), selected = ref(''); const states = ref>({}); const current = computed(() => connections.value.find(item => item.id === selected.value)); const sidebarOpen = ref(false), adding = ref(false); -const confirmingRemoval = ref(false), removing = ref(false); +const confirmingRemoval = ref(false), removing = ref(false), removalId = ref(''); +const renamingId = ref(''), renameDraft = ref(''); +let renameContainer: HTMLElement | null = null; +const removalTarget = computed(() => connections.value.find(item => item.id === removalId.value)); const error = ref(''), removalError = ref(''); const heading = ref(null); // An opened link awaiting review, and an accepted offer on its way to a slot. @@ -30,9 +32,30 @@ function select(id: string) { selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false; void nextTick(() => heading.value?.focus()); } +function startRename(item: SavedConnection, opener: HTMLButtonElement) { + renameContainer = opener.closest('.connection-item'); + renamingId.value = item.id; + renameDraft.value = item.name; + void nextTick(() => { const input = document.querySelector('.connection-rename-input'); input?.focus(); input?.select(); }); +} +function saveRename() { + const id = renamingId.value; + if (!id) return; + renamingId.value = ''; + const name = renameDraft.value.trim(); + const item = connections.value.find(record => record.id === id); + if (name && item && name !== item.name) update(id, { name }); +} +function focusRenameAction() { void nextTick(() => renameContainer?.querySelector('.edit-action')?.focus()); } +function cancelRename() { renamingId.value = ''; focusRenameAction(); } +function finishRename(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); focusRenameAction(); } +function confirmRemove(id: string) { removalId.value = id; removalError.value = ''; confirmingRemoval.value = true; } function applyRecords(records: SavedConnection[]) { connections.value = records; for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id]; + if (!records.some(item => item.id === renamingId.value)) renamingId.value = ''; + // Close a removal prompt whose connection another tab already removed. + if (!removing.value && !records.some(item => item.id === removalId.value)) confirmingRemoval.value = false; if (!records.some(item => item.id === selected.value)) select(records[0]!.id); } function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') { @@ -50,7 +73,7 @@ onMounted(async () => { try { connections.value = await loadConnections(); } catch (err) { persistent = false; connections.value = [emptyConnection()]; - error.value = `${asError(err).message} Connections and activity will only last for this tab.`; + error.value = `${asError(err).message} Connections will only last for this tab.`; } selected.value = connections.value[0]!.id; if (typeof BroadcastChannel !== 'undefined') { @@ -99,13 +122,12 @@ function update(id: string, change: ConnectionUpdate) { if (pending === 1) applyRecords(records); updates?.postMessage('changed'); } catch (err) { - // Keep this tab's activity usable without pretending it reached storage. + // Keep this tab usable without pretending the change reached storage. error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`; refreshRequested = true; } finally { pending--; if (!pending && refreshRequested) void refresh(); } }); } -function record(id: string, activity: ConnectionActivity) { update(id, { activity }); } // Connection setup re-reads the record so trust forgotten in another tab is // never reused from this tab's copy. A failed read stops setup. async function trust(id: string) { @@ -117,14 +139,21 @@ async function trust(id: string) { return record; } async function remove() { - if (!current.value || removing.value || adding.value) return; - const id = current.value.id; + if (!removalTarget.value || removing.value || adding.value) return; + const id = removalTarget.value.id, wasSelected = id === selected.value; + const index = connections.value.findIndex(item => item.id === id); removing.value = true; removalError.value = ''; try { await writes; const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id); applyRecords(records.length ? records : [emptyConnection()]); confirmingRemoval.value = false; + await nextTick(); + // Focus the newly opened row, or the row that took the removed row's place. + const row = wasSelected ? document.querySelector('.connection-item.selected') : document.querySelectorAll('.connection-item')[Math.min(index, connections.value.length - 1)]; + const link = row?.querySelector('.connection-link'); + if (link?.offsetParent) link.focus(); + else heading.value?.focus(); updates?.postMessage('changed'); } catch (err) { removalError.value = asError(err).message; } finally { removing.value = false; if (refreshRequested) void refresh(); } @@ -141,12 +170,20 @@ async function remove() {
@@ -156,7 +193,7 @@ async function remove() { About privacy & connections

Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or let a connection authenticate its remembered device. Reconnect by exchanging fresh codes.

Trust your browser and the app’s host: its code can read selected files and use your device identity. HTTPS protects delivery. A TURN relay is used only after opt-in.

-

Clearing site data removes saved connections, identities, and history.

+

Clearing site data removes saved connections and identities.

@@ -165,34 +202,28 @@ async function remove() {
-
+

{{ current.name }}

+
+
+ + {{ statusLabel(current.id) }} +
- -
+

Opening your connections…

- -

This ends its session and deletes its saved activity and remembered device. Saved files and your device identity are kept.

+ +

This ends its session and forgets its remembered device. Saved files and your device identity are kept.

A fresh Con 1 will replace your last connection.