Streamline the connections workspace

Rename and remove now live on each sidebar row instead of a header
above the workspace. The pen swaps the row to an inline input (Enter or
blur saves, Escape cancels and returns focus to the pen) and the remove
control targets its own row without switching the open connection. The
row shows a status dot with text; on mobile a bar beside Show
connections shows the open connection and its status.

The per-connection activity timeline and its saved transfer history are
removed. Records from pre-release 0.0.5 builds lose their history field
on first load. A removal dialog closes when another tab removes its
connection, and focus moves to the next row after removing another one.

The README is reorganized without repetition and corrects the TypeScript
version; the 0.0.5 changelog now describes the net change since 0.0.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-19 23:46:12 +02:00
1 parent 4323a8b774
commit f320bfb541
11 files changed
+552 -650

No files matched your search

+27 -31
View File
@@ -4,39 +4,34 @@
### Added ### Added
- Add a messenger-style workspace with a connections sidebar, editable slot - A connections sidebar with up to 100 named slots. Each row shows its session
names, session status, and a persistent activity timeline per connection. status and lets you rename or remove that connection. Switching slots keeps
- Preserve live sessions and file selections while switching slots. Save names, live sessions and selected files; names and paired devices are saved locally.
paired-device associations, and the last 50 transfer results locally; keep On mobile the sidebar collapses and a bar shows the open connection and its
manual reconnection with fresh codes. Add collapsible mobile navigation. status.
- Add opt-in hosted device identities and saved contacts, with fresh mutual - Remembered devices. Each browser can create an opt-in device identity with a
signatures bound to both connection fingerprints before remembered verification. non-extractable private key. After one manual fingerprint comparison, a
- Add contact removal and identity reset. 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. Identity-enabled signaling uses v4; temporary v3 sessions remain available.
- Keep verified sessions open for “Send another file”, with separate acceptance - Verified sessions stay open for more files: bounded queues (32 files per
and storage for each file. side), sending in both directions, per-file acceptance, progress, and
- Preserve the previous memory download until the next file is accepted. receipts, queue removal, and incoming-file decline.
- Add bounded queues (32 files per side), sending in both directions, per-file - **Disconnect**, which aborts unfinished writes, and Send/Receive navigation
progress and results, queue removal, and incoming-file decline. within a live session. The initial receiver can send files without
- Add explicit Disconnect and live Send/Receive navigation. The initial receiver reconnecting.
can use Send to add files without reconnecting. Disconnect - Shareable invitation links. Codes travel in the URL fragment, which is never
aborts unfinished writes while preserving the last completed memory download. sent to the host and is removed from the address bar on opening. An offer
- Document the hosted-first, serverless UX roadmap. link opens a preview that suggests an idle connection (the one paired with
- Add shareable invitation links. Codes travel in the URL fragment, which is the sender's device first) and fills in the code without answering. An answer
never sent to the host and is removed from the address bar on opening. An link opened in the same browser connects the waiting sender tab; elsewhere it
offer link opens a preview that suggests an idle connection (the one paired shows the answer to copy. **Share link** uses the Web Share API where
with the sender's device first) and fills in the code without answering. An available; **Copy link** and the bare code always remain.
answer link opened in the same browser connects the waiting sender tab; - The hosted-first, serverless [UX roadmap](docs/ux-roadmap.md).
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
- 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 - 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 - 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 and carries a reference shared by both, so a pasted offer in the
answer field, or an answer to a different code, is rejected with a clear answer field, or an answer to a different code, is rejected with a clear
message while the live offer stays valid. Codes may be pasted as part of a message while the live offer stays valid. Codes may be pasted as part of a
link. Earlier 0.0.5 drafts' codes are rejected. link. Codes from earlier 0.0.5 drafts are rejected.
- 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
use the native save picker, else buffer up to 64 MiB in memory and hand it use the native save picker, else buffer up to 64 MiB in memory and hand it
to Downloads automatically on completion. to Downloads automatically on completion.
- A completed memory download stays available via **Save again** until the next
file is accepted, including after Disconnect.
### Removed ### Removed
+293 -352
View File
@@ -1,407 +1,348 @@
# HellCon # HellCon
Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release notes Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release
and compatibility changes. notes 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. There are no accounts, no
backend, or server-side file storage. You exchange invitation links or signaling backend, and no server-side file storage: you exchange invitation links
connection codes yourself, through any messenger. or connection codes yourself, through any messenger. Connections are direct by
Direct connections are the default. TURN relaying is optional and requires default. A TURN relay is used only when both people opt in.
explicit opt-in by both people; no relay is configured automatically.
## 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** ## Connections
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.
Connection names, remembered devices, and the last 50 transfer results The sidebar lists your connections, starting with **Con 1**, up to 100. Each one
per slot are saved in this browser. History includes filenames, sizes, directions, has its own setup and live session.
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.
Each slot can remember one device. Under **Remembered device**, create the - **Open** a connection by clicking its row. The row shows its name and this
browser's device identity once, then opt each slot in. After the first manual tab's session status (not whether the remote device is online).
fingerprint comparison, **Remember this device for …** (ticked by default) pairs - **Rename** with the pen. Enter or leaving the field saves; Escape cancels.
the verified peer with that slot; later sessions on it authenticate the peer An empty name keeps the previous one.
automatically. The slot name is the device's name. **Forget device** unpairs it. - **Remove** with ✕, then confirm. This ends the connection's sessions in all
The same device may be paired with several slots. Clearing site data removes saved open tabs and forgets its remembered device. Downloaded files and your device
connections and trust. Storage failures are shown explicitly; temporary sessions identity remain. Removing the last connection leaves a fresh **Con 1**.
remain available. Up to 100 connection slots are supported. - **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, Names and remembered devices are saved in this browser. Transfer history, file
Cloudflare, a custom provider, or None). They create a code and send it as a contents, connection codes, and relay credentials are not. Clearing site data
link (**Share link** where the browser supports it, or **Copy link**) removes saved connections, identities, and trust. If storage fails, the app says
privately to the intended receiver through an authenticated channel. The bare so and temporary sessions still work.
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.
Once both people verify, either person can add files without new codes or another ## Sharing files
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.
**Disconnect** ends the entire session, drops waiting files and aborts unfinished 1. **Create a code.** The person starting picks one or more files, chooses a
disk writes. To cancel an already active transfer, disconnect; cancelling only an STUN provider (PageQuit by default, Google, Cloudflare, custom, or None), and
active file is not supported. A completed memory transfer stays available via **Save again** after clicks **Create code**. They send the link privately to the receiver through
disconnect, until the next acceptance replaces it. **Reset** discards it and an authenticated channel, with **Share link** where supported or **Copy
returns to setup. Before connecting, Send/Receive chooses who starts the connection. Once link**. The bare code is under **Show code instead**.
verified, these controls navigate to the sending and receiving sections without 2. **Answer it.** The receiver opens the link or pastes the link or code. An
reconnecting. The initial receiver can click **Send**, then **Add files to send**. 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 Streamed transfers have no app-defined size cap; browser, filesystem, and storage
the session, although browsers and mobile operating systems can suspend pages. limits apply, and byte counts must stay below 2^53. Files above 120 MiB have not
Pending verification/acceptance expires after five minutes; stalled transfers been tested end to end.
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.
If an answer is rejected as invalid, correct the pasted answer and click Connect ### During a session
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.
### 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 **Disconnect** ends the session, drops waiting files, and aborts unfinished disk
retains local/remote candidate type counts, candidate-pair states, selected writes; cancelling a single active file is not supported. A completed memory
route types, DTLS transport states, and ICE check request/response counters after failure. download stays available via **Save again** until the next accepted file
Four snapshots during ICE checking preserve evidence before failed pairs disappear. Final stats replaces it. **Reset** discards it and returns to setup; the connection stays.
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.
Same-machine success does not establish cross-device connectivity. Error 701 Switching tabs or apps does not end the session, but browsers and mobile systems
alone does not establish the cause of a failed connection. A receiver shutdown may suspend pages. Pending verification or acceptance expires after five
after both sides report completion can be normal sender cleanup. minutes, stalled transfers after one minute; idle verified sessions stay open.
The comparison with the first commit and controlled test results are recorded in ### Troubleshooting
[the investigation notes](docs/connection-investigation.md). Run the isolated
ICE experiment with `node scripts/compare-ice.mjs firefox` or replace `firefox` - A pasted answer that is invalid, an offer in the answer field, or an answer for
with `chromium`. This uses local browser peers and deliberately unusable offer a different code is reported without discarding the live offer. Fix it and
ports plus a 20-second answer delay; it is **not a cross-device test**. Add click **Connect** again.
`--normal-candidates` to preserve the real candidate ports. No firewall changes, - After a connection closes or fails, use **Reset** and exchange a new offer and
TURN credentials or public STUN service are required. 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 ## Remembered devices
On the hosted app, expand **Remembered device** and choose **Create device Each connection can remember one device, so later sessions skip the manual
identity** on both browsers; this also enables **Use my device identity on this fingerprint comparison.
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.
Later sessions on that connection need no extra steps: HellCon checks fresh 1. On both browsers, expand **Remembered device** and choose **Create device
signed proofs bound to both device keys and both connection fingerprints. A identity**. This also turns on **Use my device identity on this connection**;
matching paired key replaces manual fingerprint comparison; file acceptance is each connection has its own opt-in, and new connections start without it.
still required. A changed or missing identity requires manual comparison and 2. Connect and compare full fingerprints once. Leave **Remember this device for
only replaces the paired device if you tick **Replace the paired device**. …** ticked when confirming, and the verified peer is paired with this
Connection names stay local. Public identities in codes can link sessions. 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. Later sessions check fresh signed proofs bound to both device keys and both
Clearing site data loses saved trust and requires pairing again. Browser-stored connection fingerprints; file acceptance is still required. A changed or missing
keys remain usable by trusted app code and are not protection against a malicious identity falls back to manual comparison and only replaces the paired device if
host. Each connection keeps its own opt-in; new connections start without it. you tick **Replace the paired device**. **Forget device** unpairs it. One device
Storage failure leaves temporary connections available. can be paired with several connections.
Identity-enabled codes use signaling version **4** and require the new build. Identity-enabled codes use signaling **v4**; temporary codes use **v3**. If only
Temporary codes retain version **3**. If only one peer enables identity, the one peer enables identity, the session uses manual comparison without
current build uses manual comparison without remembering that connection. remembering. Public identities in codes can link sessions. Browser-stored keys
See [the identity protocol and storage](docs/device-identities.md). 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 ### Codes and links
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.
Connection codes are **compressed and Base64url-encoded, not encrypted** Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.`
(`HC1.` followed by deflated JSON). They contain SDP, including candidate followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE
addresses, temporary ICE credentials and certificate fingerprints. Peers and credentials, and certificate fingerprints. Anyone who sees a code, including the
anyone who sees these codes (including the messaging service used to exchange messaging service, may learn these details. Treat codes as private and do not
them) may learn connection details. Local addresses may be obscured by the publish them. The browser may obscure local addresses, but this app does not
browser, but this app does not provide anonymity. Treat codes as private session provide anonymity.
information; do not publish them.
Invitation links carry the code after `#`. Browsers do not send this fragment to 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 the host, and the app removes it from the address bar on opening. Otherwise a
otherwise exactly as sensitive as its code: recipients and messengers see it, and link is as sensitive as its code; browser history, including synced history, may
browser history (including synced history) may keep it. Opening an offer link keep it. Opening an offer link never answers automatically. Answer links reach
never answers automatically. Answer links reach the waiting tab over a the waiting tab over a same-origin `BroadcastChannel`. See [the invitation
same-origin `BroadcastChannel`; other sites cannot post to it. See design](docs/invitations.md).
[the invitation design](docs/invitations.md).
Restrictive NATs or firewalls can prevent direct connections. There is no silent File transfers use protocol **v3**; codes from older builds are rejected before
TURN retry. To permit a relay, both people must explicitly check **Allow a TURN connecting.
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.
When a credential endpoint is configured (including the local development setup ### STUN and optional TURN
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.
TURN credentials stay in the current component's memory; the app does not persist STUN discovers externally reachable addresses. Its operator sees your public IP
them or include them in codes. The relay receives its authentication exchange and and request metadata but never file contents. Choosing None avoids contacting a
can observe addresses, timing and traffic volume, and may charge for bandwidth. STUN provider; direct connectivity then depends on addresses, routing, browser
Resetting, cancelling or ending a connection clears TURN consent; policy, and firewalls. A VPN does not guarantee against address disclosure.
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.
## 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 When a credential endpoint is configured, **Use the configured relay with
integrity. This is not DTLS-SRTP (the media transport). DTLS authenticates the temporary credentials** fetches fresh credentials for each connection after
certificate in the connection description; an independently authenticated full opt-in and shows them read-only. Uncheck it to enter a relay manually. TURN
fingerprint comparison binds that certificate to the intended peer. Comparing credentials stay in memory and never enter codes. The relay sees its
fingerprints through a channel an attacker can rewrite provides no such assurance. 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 ### Security model and limits
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.
The protocol accepts one ordered, reliable data channel, bounded metadata and Data channels use **SCTP over DTLS** for transport confidentiality and integrity.
messages, exact declared byte counts, and at most one accepted file per direction. DTLS authenticates the certificate in the connection description; comparing full
Monotonic per-direction file IDs bind offers, data, and receipts to their files. It rejects unexpected fingerprints over an independently authenticated channel binds that certificate
states, excess data and duplicate metadata. An acknowledged 1 MiB send window per transfer to the intended peer. Comparing over a channel an attacker can rewrite proves
and a bounded receive queue limit buffering during disk writes. Files are treated nothing.
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.
For deployment, serve `dist/` as static files over HTTPS. Do not expose the Vite You must trust your browser, device, and **the JavaScript you load**. A
dev or preview server as the production service. Configure hosting headers such compromised host or build can steal plaintext or falsify the verification
as `Content-Security-Policy` (including `frame-ancestors 'none'`), display. HTTPS protects delivery, not against a malicious host. This code does
`X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. A baseline not upload files to its host, but that is no guarantee against a host serving
CSP for this build is `default-src 'self'; script-src 'self'; style-src 'self' different code. The web host, DNS resolver, and code-exchange service are also
'unsafe-inline'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri relevant third parties.
'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.
Deploy the complete `dist/` directory, including `download/worker.js`, served The protocol accepts one ordered, reliable data channel with bounded metadata
with a JavaScript MIME type. The download worker has scope `download/` only: and messages, exact declared byte counts, and at most one accepted file per
it does not control the app page, cache the app, or proxy normal web requests. direction. Monotonic per-direction file IDs bind offers, data, and receipts to
It serves single-use, randomly named download URLs from incoming browser their files; unexpected states, excess data, and duplicate metadata are rejected.
streams, with bounded buffering. The default CSP above permits this; custom A 1 MiB acknowledged send window and a bounded receive queue limit buffering.
policies must permit same-origin workers and frames. No third-party helper, Files are opaque downloads and metadata is never rendered as HTML. Encryption
download backend, or additional hosting service is required. Closing/resetting does not make a file safe to open. These limits reduce, but do not eliminate,
an unfinished transfer aborts it; interrupted transfers must restart. 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 ```sh
`bun run build`. Serve the whole `dist/` directory, including `assets/` and bun install --frozen-lockfile
`download/`, using a static web server over HTTPS. For local build inspection, bun run build
run `bun run preview` and open the printed localhost URL. ```
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 ## Development
### Local WebTorrent tracker 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
The repository includes [our tracker Dockerfile](tracker/Dockerfile) and a every production build. TypeScript stays on 6.0 until Vue's checker supports
separate [Compose service](compose.tracker.yaml), built from the official Node TypeScript 7. Vite 8 supplies the Rolldown bundler and Oxc transforms. Node runs
image and a locked upstream `bittorrent-tracker` release. With Docker running: the TypeScript tests directly, with no test framework or loader. The lockfile
pins dependencies; review updates and advisories before publishing a build.
```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.
```sh ```sh
bun install --frozen-lockfile bun install --frozen-lockfile
bun run dev bun run dev
bun run typecheck bun run typecheck
bun run test bun run test # unit tests
bun run build bun run build
bun run test:browser # local Chromium integration checks against dist/ bun run test:browser # Chromium integration and axe checks against dist/
bun run test:browser --connections # sidebar, persistence, live switching, and mobile layout bun run test:browser --connections # sidebar, persistence, live switching, mobile layout
bun run test:download # real hosted downloads, including 120 MiB, with native picker disabled bun run test:download # real hosted downloads up to 120 MiB, no native picker
bun run test:cross-browser # Brave sender → Firefox receiver bun run test:cross-browser # Brave sender → Firefox receiver
bun run preview # local build inspection only
bun audit bun audit
``` ```
The lockfile pins dependencies. Review dependency updates and advisories before Browser checks run against `dist/`, so build first. They use isolated temporary
publishing a build. Protocol regression tests cover verification gating, malformed profiles and a loopback server, and never touch your normal browser settings.
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.
This is experimental software, not independently audited or battle-tested. - `test:browser` and `test:download` need Chromium at `/usr/bin/chromium`
Browser compatibility, network connectivity and storage availability vary. (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 ## License
MIT — see `LICENSE`. MIT — see [LICENSE](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.
+6 -8
View File
@@ -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**; 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 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. keep live sessions and file selections intact while navigating between slots.
The sidebar collapses on mobile; network configuration is expandable. The sidebar collapses on mobile; network configuration is expandable.
IndexedDB stores slot names, paired devices, and up to 50 transfer IndexedDB stores slot names and paired devices. Transfer history, file contents,
results per slot. Each result includes its direction, filename, size, timestamp, and connection codes are not stored. Slot mutations are transactional, and other
and completion/decline/interruption status. File contents and connection codes tabs refresh their lists after changes. Storage failures show an explicit warning.
are never 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 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. 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 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 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 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 The arbitration decision is one sequential queue per direction, permitting two
active files total. Simultaneous offers therefore never compete for one global active files total. Simultaneous offers therefore never compete for one global
+107 -45
View File
@@ -239,68 +239,76 @@ try {
if (connections) { if (connections) {
const sender = await page(), receiver = await page(origin.replace('127.0.0.1', 'localhost')); 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 selectConnection = (session: string, name: string) => evaluate(session, (name: string) => {
const button = [...document.querySelectorAll<HTMLButtonElement>('.connection-link')].find(item => item.querySelector('.connection-name')?.textContent === name); const label = [...document.querySelectorAll<HTMLElement>('.connection-name')].find(item => item.textContent === name);
if (!button) throw new Error('Missing connection: ' + name); if (!label) throw new Error('Missing connection: ' + name);
button.click(); label.click();
}, name); }, name);
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('.main-pane h1')?.textContent), 'Con 1');
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll<HTMLDetailsElement>('.config-details')].map(details => [details.querySelector('summary')?.textContent?.trim(), details.open])), [ 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], ['Remembered device', false], ['Network settings', false],
], 'Configuration panels start closed'); ], '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()); assert.equal(await evaluate(sender, () => !!document.querySelector('.connection-rename-input')), false, 'Names start locked');
await input(sender, '#connection-name', 'Work laptop'); await click(sender, 'Rename Con 1');
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur()); 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<HTMLInputElement>('.connection-rename-input').blur());
await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop'); await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop');
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus()); await click(sender, 'Rename Work laptop');
await input(sender, '#connection-name', ' '); await input(sender, '.connection-rename-input', ' ');
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur()); await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.connection-rename-input').blur());
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').value), 'Work laptop'); assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop');
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus()); await click(sender, 'Rename Work laptop');
await input(sender, '#connection-name', '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: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender);
await call('Input.dispatchKeyEvent', { type: 'keyUp', 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<HTMLInputElement>('#connection-name').value), 'Work laptop'); assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop');
assert.equal(await evaluate(sender, () => document.activeElement?.id === 'connection-name'), false); 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 click(receiver, 'Receive');
await connect(sender, receiver, 4097); await connect(sender, receiver, 4097);
const fingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)); const fingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent));
await click(sender, 'Add connection'); 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); assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false);
await click(receiver, 'Accept file'); await click(receiver, 'Accept file');
await wait(sender, () => document.querySelector('.connection-link .connection-preview')?.textContent === 'browser-test.bin'); await wait(sender, () => document.querySelector('.connection-item .connection-status')?.textContent === 'Connected');
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0, 'Hidden session activity must stay in its own slot'); 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 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); 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 evaluate(sender, () => window.__hellcon.chooseFile(1234, 'after-switch.bin'));
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin')); await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin'));
await click(receiver, 'Accept file'); 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 received = await evaluate(receiver, async () => {
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer()); const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
return { size: bytes.length, valid: bytes.every(byte => byte === 123) }; return { size: bytes.length, valid: bytes.every(byte => byte === 123) };
}); });
assert.deepEqual(received, { size: 1234, valid: true }); assert.deepEqual(received, { size: 1234, valid: true });
await click(sender, 'Disconnect'); await click(sender, 'Reset'); await click(sender, 'Disconnect'); await click(sender, 'Reset');
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 2, 'Reset must preserve slot history'); assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop', 'Reset keeps the connection slot');
await checkAccessibility(sender, 'Connections with history'); await checkAccessibility(sender, 'Connections after transfer');
await screenshot(sender, 'connections-history'); await screenshot(sender, 'connections-after-transfer');
await selectConnection(sender, 'Con 2'); await selectConnection(sender, 'Con 2');
await evaluate(sender, () => window.__hellcon.chooseFile(10, 'draft.bin')); await evaluate(sender, () => window.__hellcon.chooseFile(10, 'draft.bin'));
await selectConnection(sender, 'Work laptop'); await selectConnection(sender, 'Con 2'); 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'); 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 call('Page.navigate', { url: origin }, sender);
await wait(sender, () => document.querySelectorAll('.activity-item').length === 2); await wait(sender, () => !!document.querySelector('#stun-provider'));
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Work laptop'); assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop');
assert.equal(await evaluate(sender, () => document.querySelector('.session-badge')?.textContent), 'Ready to connect'); assert.equal(await evaluate(sender, () => document.querySelector('.connection-item.selected .connection-status')?.textContent), 'Ready to connect');
await selectConnection(sender, 'Con 2'); await selectConnection(sender, 'Con 2');
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
assert.equal(await evaluate(sender, () => document.querySelector<HTMLInputElement>('#file-input')?.files?.length), 0, 'File contents must not persist after reload'); assert.equal(await evaluate(sender, () => document.querySelector<HTMLInputElement>('#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(); const other = await page();
await Promise.all([click(sender, 'Add connection'), click(other, 'Add connection')]); 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 call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, sender);
await selectConnection(sender, 'Work laptop'); 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'); await checkAccessibility(sender, 'Connections mobile');
assert.equal(await evaluate(sender, () => document.documentElement.scrollWidth <= innerWidth), true, 'Mobile workspace must not overflow horizontally'); assert.equal(await evaluate(sender, () => document.documentElement.scrollWidth <= innerWidth), true, 'Mobile workspace must not overflow horizontally');
await screenshot(sender, 'connections-mobile'); 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 wait(sender, () => !!document.querySelector('dialog[open]'));
await checkAccessibility(sender, 'Removal dialog mobile'); await checkAccessibility(sender, 'Removal dialog mobile');
await screenshot(sender, 'connections-mobile-dialog'); await screenshot(sender, 'connections-mobile-dialog');
await click(sender, 'Close dialog'); await click(sender, 'Close dialog');
await wait(sender, () => !document.querySelector('dialog[open]')); await wait(sender, () => !document.querySelector('dialog[open]'));
await click(sender, 'Show connections');
await checkAccessibility(sender, 'Connections mobile sidebar'); await checkAccessibility(sender, 'Connections mobile sidebar');
assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'flex'); assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'flex');
await screenshot(sender, 'connections-mobile-sidebar'); await screenshot(sender, 'connections-mobile-sidebar');
@@ -333,8 +343,8 @@ try {
await connect(sender, receiver, 1024); await connect(sender, receiver, 1024);
await selectConnection(sender, 'Con 2'); await selectConnection(sender, 'Con 2');
await selectConnection(other, 'Work laptop'); await selectConnection(other, 'Work laptop');
await evaluate(other, () => window.__hellcon.element<HTMLButtonElement>('.header-action').focus()); await evaluate(other, () => window.__hellcon.element<HTMLButtonElement>('.connection-item.selected .remove-action').focus());
await click(other, 'Remove'); await click(other, 'Remove Work laptop');
await wait(other, () => !!document.querySelector('dialog[open]')); 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'); assert.equal(await evaluate(other, () => document.activeElement?.textContent?.trim()), 'Keep connection', 'Dialog starts on its non-destructive action');
await checkAccessibility(other, 'Remove connection confirmation'); 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: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other);
await call('Input.dispatchKeyEvent', { type: 'keyUp', 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]')); 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'); assert.equal(await evaluate(other, () => document.activeElement?.classList.contains('remove-action')), true, 'Dialog restores focus to the opener');
await click(other, 'Remove'); await click(other, 'Remove Work laptop');
await click(other, 'Keep connection'); await click(other, 'Keep connection');
assert.equal(await evaluate(other, () => document.querySelectorAll('.connection-link').length), 4); 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(other, () => document.querySelectorAll('.connection-link').length === 3);
await wait(sender, () => 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 wait(receiver, () => !document.querySelector('.incoming'));
await call('Page.navigate', { url: origin }, sender); await call('Page.navigate', { url: origin }, sender);
await wait(sender, () => !!document.querySelector('#stun-provider')); await wait(sender, () => !!document.querySelector('#stun-provider'));
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Work laptop')), false); assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Work laptop')), false);
for (let count = 3; count > 0; count--) { for (let count = 3; count > 0; count--) {
const oldName = await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent); const oldName = await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent);
await click(sender, 'Remove'); await click(sender, 'Remove connection'); await click(sender, `Remove ${oldName}`); await click(sender, 'Remove connection');
await wait(sender, () => !document.querySelector('dialog[open]')); await wait(sender, () => !document.querySelector('dialog[open]'));
assert.equal(await evaluate(sender, () => document.querySelectorAll('.connection-link').length), Math.max(1, count - 1)); 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.querySelector('.main-pane h1')?.textContent), 'Con 1');
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
await call('Page.navigate', { url: origin }, sender); await call('Page.navigate', { url: origin }, sender);
await wait(sender, () => !!document.querySelector('#stun-provider')); await wait(sender, () => !!document.querySelector('#stun-provider'));
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Con 1']); 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.'); 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<HTMLInputElement>('.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<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open('hellcon-connections', 1);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
await new Promise<void>((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<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open('hellcon-connections', 1);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const record = await new Promise<Record<string, unknown>>((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, []); assert.deepEqual(browserErrors, []);
} else if (streaming) { } else if (streaming) {
const sender = await page(), receiver = await page(); 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. // suggests the slot paired with the sender's device, and Open hands it there.
const invitedPaired = await page(receiverOrigin); const invitedPaired = await page(receiverOrigin);
await click(invitedPaired, 'Add connection'); 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 evaluate(invitedPaired, (code: string) => { location.hash = code; }, offer);
await wait(invitedPaired, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files')); 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.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'); 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]')); 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<HTMLTextAreaElement>('#offer-input').value), offer); 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 evaluate(invitedPaired, () => [...document.querySelectorAll<HTMLElement>('.connection-name')].find(item => item.textContent === 'Con 2')?.click());
await wait(invitedPaired, () => document.querySelector('.title-line h1')?.textContent === 'Con 2'); await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
await click(invitedPaired, 'Remove'); await click(invitedPaired, 'Remove connection'); await click(invitedPaired, 'Remove Con 2'); await click(invitedPaired, 'Remove connection');
await wait(invitedPaired, () => document.querySelectorAll('.connection-link').length === 1); await wait(invitedPaired, () => document.querySelectorAll('.connection-link').length === 1);
await closePage(invitedPaired); 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.'); console.log('PASS: an invitation from a paired device suggests its slot over the current one and hands the code to it.');
+62 -31
View File
@@ -2,9 +2,8 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'; import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue'; import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.vue'; import AppDialog from './components/AppDialog.vue';
import EditableName from './components/EditableName.vue';
import InvitationDialog from './components/InvitationDialog.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 { takeFragment } from './lib/invitations.ts';
import { asError } from './lib/validation.ts'; import { asError } from './lib/validation.ts';
@@ -17,7 +16,10 @@ const connections = ref<SavedConnection[]>([]), selected = ref('');
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({}); const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
const current = computed(() => connections.value.find(item => item.id === selected.value)); const current = computed(() => connections.value.find(item => item.id === selected.value));
const sidebarOpen = ref(false), adding = ref(false); 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 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. // 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; selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false;
void nextTick(() => heading.value?.focus()); void nextTick(() => heading.value?.focus());
} }
function startRename(item: SavedConnection, opener: HTMLButtonElement) {
renameContainer = opener.closest<HTMLElement>('.connection-item');
renamingId.value = item.id;
renameDraft.value = item.name;
void nextTick(() => { const input = document.querySelector<HTMLInputElement>('.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<HTMLButtonElement>('.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[]) { function applyRecords(records: SavedConnection[]) {
connections.value = records; connections.value = records;
for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id]; 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); if (!records.some(item => item.id === selected.value)) select(records[0]!.id);
} }
function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') { function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') {
@@ -50,7 +73,7 @@ onMounted(async () => {
try { connections.value = await loadConnections(); } try { connections.value = await loadConnections(); }
catch (err) { catch (err) {
persistent = false; connections.value = [emptyConnection()]; 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; selected.value = connections.value[0]!.id;
if (typeof BroadcastChannel !== 'undefined') { if (typeof BroadcastChannel !== 'undefined') {
@@ -99,13 +122,12 @@ function update(id: string, change: ConnectionUpdate) {
if (pending === 1) applyRecords(records); if (pending === 1) applyRecords(records);
updates?.postMessage('changed'); updates?.postMessage('changed');
} catch (err) { } 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.`; error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`;
refreshRequested = true; refreshRequested = true;
} finally { pending--; if (!pending && refreshRequested) void refresh(); } } 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 // 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. // never reused from this tab's copy. A failed read stops setup.
async function trust(id: string) { async function trust(id: string) {
@@ -117,14 +139,21 @@ async function trust(id: string) {
return record; return record;
} }
async function remove() { async function remove() {
if (!current.value || removing.value || adding.value) return; if (!removalTarget.value || removing.value || adding.value) return;
const id = current.value.id; const id = removalTarget.value.id, wasSelected = id === selected.value;
const index = connections.value.findIndex(item => item.id === id);
removing.value = true; removalError.value = ''; removing.value = true; removalError.value = '';
try { try {
await writes; await writes;
const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id); const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id);
applyRecords(records.length ? records : [emptyConnection()]); applyRecords(records.length ? records : [emptyConnection()]);
confirmingRemoval.value = false; 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<HTMLButtonElement>('.connection-link');
if (link?.offsetParent) link.focus();
else heading.value?.focus();
updates?.postMessage('changed'); updates?.postMessage('changed');
} catch (err) { removalError.value = asError(err).message; } } catch (err) { removalError.value = asError(err).message; }
finally { removing.value = false; if (refreshRequested) void refresh(); } finally { removing.value = false; if (refreshRequested) void refresh(); }
@@ -141,12 +170,20 @@ async function remove() {
</header> </header>
<div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div> <div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div>
<nav class="connection-nav" aria-label="Connections"> <nav class="connection-nav" aria-label="Connections">
<button v-for="item in connections" :key="item.id" class="connection-link" :class="{ selected: selected === item.id }" <div v-for="item in connections" :key="item.id" class="connection-item" :class="{ selected: selected === item.id }">
:aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)"> <button v-if="renamingId !== item.id" class="connection-link" :aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)">
<span class="connection-avatar" aria-hidden="true">{{ item.name.slice(0, 1).toUpperCase() }}</span> <span class="connection-name">{{ item.name }}</span>
<span class="connection-label"><span class="connection-name">{{ item.name }}</span><span class="connection-preview">{{ item.history.at(-1)?.name || (item.peerKey ? 'Remembered device' : 'No activity yet') }}</span></span> <span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
<span class="connection-dot" :class="states[item.id] || 'ready'" :aria-label="statusLabel(item.id)"></span> </button>
</button> <div v-else class="connection-edit">
<input v-model="renameDraft" class="connection-rename-input" :aria-label="`New name for ${item.name}`" aria-describedby="rename-hint" maxlength="80" autocomplete="off" spellcheck="false"
@blur="saveRename" @keydown.enter.prevent="finishRename" @keydown.esc.prevent="cancelRename" />
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
</div>
<button v-if="renamingId !== item.id" class="connection-action edit-action" :aria-label="`Rename ${item.name}`" :title="`Rename ${item.name}`" :disabled="removing" @click="startRename(item, $event.currentTarget as HTMLButtonElement)"><span aria-hidden="true">✎</span></button>
<button class="connection-action remove-action" :aria-label="`Remove ${item.name}`" :title="`Remove ${item.name}`" :disabled="adding || removing" @click="confirmRemove(item.id)"><span aria-hidden="true">✕</span></button>
</div>
<span id="rename-hint" class="sr-only">Press Enter or leave the field to save. Press Escape to cancel.</span>
</nav> </nav>
<button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button> <button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button>
<footer class="sidebar-footer"> <footer class="sidebar-footer">
@@ -156,7 +193,7 @@ async function remove() {
<summary>About privacy &amp; connections</summary> <summary>About privacy &amp; connections</summary>
<p>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.</p> <p>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.</p>
<p>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.</p> <p>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.</p>
<p>Clearing site data removes saved connections, identities, and history.</p> <p>Clearing site data removes saved connections and identities.</p>
</details> </details>
<a class="source-link" href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer" aria-label="View HellCon source code on Gitea"> <a class="source-link" href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer" aria-label="View HellCon source code on Gitea">
<img :src="giteaIconUrl" width="20" height="20" alt="" /> <img :src="giteaIconUrl" width="20" height="20" alt="" />
@@ -165,34 +202,28 @@ async function remove() {
</footer> </footer>
</aside> </aside>
<main id="main-content" class="main-pane" tabindex="-1"> <main id="main-content" class="main-pane" tabindex="-1">
<header class="connection-header"> <h1 v-if="current" ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
<div class="mobile-bar">
<div v-if="current" class="mobile-current">
<span class="mobile-current-name" aria-hidden="true">{{ current.name }}</span>
<span class="connection-status-line"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span><span class="mobile-current-status">{{ statusLabel(current.id) }}</span></span>
</div>
<button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button> <button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button>
<template v-if="current"> </div>
<div class="connection-title">
<p class="eyebrow">Connection</p>
<div class="title-line">
<h1 ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
<EditableName :key="current.id" :name="current.name" :disabled="removing" @rename="update(current!.id, { name: $event })" />
<button class="header-action" :disabled="adding || removing" @click="removalError = ''; confirmingRemoval = true"><span class="header-action-icon" aria-hidden="true">✕</span> Remove</button>
</div>
</div>
<span class="session-badge" :class="states[current.id] || 'ready'"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span>{{ statusLabel(current.id) }}</span>
</template>
</header>
<div class="workspace-scroll"> <div class="workspace-scroll">
<p v-if="error" class="storage-error" role="alert">{{ error }}</p> <p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id"> <template v-for="item in connections" :key="item.id">
<KeepAlive> <KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null" <ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null"
@status="setStatus" @activity="record" @update="update" @invitation-taken="handoff = null" /> @status="setStatus" @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>
</div> </div>
</main> </main>
</div> </div>
<AppDialog v-model="confirmingRemoval" :title="`Remove ${current?.name || 'connection'}?`" :busy="removing"> <AppDialog v-model="confirmingRemoval" :title="`Remove ${removalTarget?.name || 'connection'}?`" :busy="removing">
<p>This ends its session and deletes its saved activity and remembered device. Saved files and your device identity are kept.</p> <p>This ends its session and forgets its remembered device. Saved files and your device identity are kept.</p>
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p> <p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p> <p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
<template #actions="{ close }"> <template #actions="{ close }">
+11 -40
View File
@@ -1,11 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, ref, watch } 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, ConnectionUpdate } from '../lib/connections.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; invitation?: { code: string } | null }>(); const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; 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];
update: [id: string, change: ConnectionUpdate]; update: [id: string, change: ConnectionUpdate];
invitationTaken: []; invitationTaken: [];
}>(); }>();
@@ -28,48 +27,20 @@ watch(() => props.invitation, async invitation => {
await nextTick(); await nextTick();
panel.value?.importCode(invitation.code); panel.value?.importCode(invitation.code);
}, { immediate: true }); }, { immediate: true });
function sizeLabel(size: number) {
if (size < 1024) return `${size} B`;
const index = Math.min(5, Math.floor(Math.log(size) / Math.log(1024)));
return `${(size / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
}
</script> </script>
<template> <template>
<div class="connection-workspace"> <div class="connection-workspace">
<div class="session-column"> <div class="workspace-intro">
<div class="workspace-intro"> <h2>{{ connected ? 'Share files' : 'Start a session' }}</h2>
<h2>{{ connected ? 'Share files' : 'Start a session' }}</h2> <p>{{ connected ? 'Your connection is ready.' : 'Exchange connection codes with your peer to start sharing.' }} Each direction sends one file at a time; both people can send on this connection.</p>
<p>{{ connected ? 'Your connection is ready.' : 'Exchange connection codes with your peer to start sharing.' }} Each direction sends one file at a time; both people can send on this connection.</p>
</div>
<div class="tabs" role="group" :aria-label="connected ? 'Transfer sections' : 'Connection setup'">
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
</div>
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)"
@session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
@activity="emit('activity', connection.id, $event)" @update="emit('update', connection.id, $event)" />
</div> </div>
<aside class="activity-panel" aria-labelledby="activity-heading"> <div class="tabs" role="group" :aria-label="connected ? 'Transfer sections' : 'Connection setup'">
<div class="activity-heading"><h2 id="activity-heading">Activity</h2><span>{{ connection.history.length }}</span></div> <button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
<div v-if="!connection.history.length" class="empty-activity"> <button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
<span class="empty-activity-icon" aria-hidden="true">↔</span> </div>
<h3>A fresh connection</h3> <TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)"
<p>Files you share here will appear in this timeline.</p> @session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
<p class="activity-note">History stays in this browser. File contents aren’t kept here.</p> @update="emit('update', connection.id, $event)" />
</div>
<ol v-else class="activity-list" aria-label="Recent file results">
<li v-for="item in [...connection.history].reverse()" :key="item.id" class="activity-item">
<span class="activity-icon" aria-hidden="true">{{ item.direction === 'send' ? '↗' : '↙' }}</span>
<div>
<p class="activity-filename">{{ item.name }}</p>
<p class="activity-meta">{{ item.direction === 'send' ? 'Outgoing' : 'Incoming' }} · {{ sizeLabel(item.size) }}</p>
<p class="activity-result">{{ item.result === 'complete' ? 'Transfer complete' : item.result === 'declined' ? 'Declined' : 'Interrupted' }}</p>
<time :datetime="new Date(item.time).toISOString()">{{ new Date(item.time).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) }}</time>
</div>
</li>
</ol>
<p v-if="connection.history.length" class="activity-note">Last 50 transfers · Saved in this browser</p>
</aside>
</div> </div>
</template> </template>
-24
View File
@@ -1,24 +0,0 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
const props = defineProps<{ name: string; disabled?: boolean }>();
const emit = defineEmits<{ rename: [name: string] }>();
const draft = ref(props.name), editing = ref(false);
watch(() => props.name, value => { if (!editing.value) draft.value = value; });
function save() {
editing.value = false;
const name = draft.value.trim();
draft.value = name || props.name;
if (name && name !== props.name) emit('rename', name);
}
function finish(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); }
</script>
<template>
<div class="editable-name">
<label class="sr-only" for="connection-name">Connection name</label>
<input id="connection-name" v-model="draft" :size="Math.max(5, Math.min(draft.length + 2, 24))" :disabled="disabled" maxlength="80" autocomplete="off" spellcheck="false"
aria-describedby="connection-name-hint" @focus="editing = true" @blur="save" @keydown.enter.prevent="finish" />
<span class="name-edit-icon" aria-hidden="true">✎</span>
<span id="connection-name-hint" class="sr-only">Edit the name. Changes save when you leave this field.</span>
</div>
</template>
+5 -10
View File
@@ -13,7 +13,7 @@ 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';
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts'; import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
import type { ConnectionActivity, ConnectionUpdate, SavedConnection } from '../lib/connections.ts'; import type { ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState; type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session { interface Session {
@@ -48,7 +48,7 @@ const receiveState = ref<TransferState | null>(null);
const outgoing = ref<FileMetadata | null>(null); const outgoing = ref<FileMetadata | null>(null);
const receiveProgress = ref(0); const receiveProgress = ref(0);
const lastDirection = ref<'send' | 'receive'>('send'); const lastDirection = ref<'send' | 'receive'>('send');
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; activity: [item: ConnectionActivity]; update: [change: ConnectionUpdate] }>(); const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; update: [change: ConnectionUpdate] }>();
const inputCode = ref(''); const inputCode = ref('');
const outputCode = ref(''); const outputCode = ref('');
const step = ref<Step>('idle'); const step = ref<Step>('idle');
@@ -132,8 +132,8 @@ function saveDownload() {
function dispose() { function dispose() {
const old = active; const old = active;
if (old) { if (old) {
if (outgoing.value && sendState.value && !['done', 'closed'].includes(sendState.value)) { remember('send', outgoing.value, 'interrupted'); sendState.value = 'closed'; } if (outgoing.value && sendState.value && !['done', 'closed'].includes(sendState.value)) sendState.value = 'closed';
if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) { remember('receive', incoming.value, 'interrupted'); receiveState.value = 'closed'; } if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) receiveState.value = 'closed';
} }
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false); active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
managedCredentials.value = null; settings.value.allowTurn = false; managedCredentials.value = null; settings.value.allowTurn = false;
@@ -191,9 +191,6 @@ function pickFiles(event: Event) {
if (event.target instanceof HTMLInputElement) event.target.value = ''; if (event.target instanceof HTMLInputElement) event.target.value = '';
} }
function removeQueued(id: number) { active?.transfer?.remove(id); } function removeQueued(id: number) { active?.transfer?.remove(id); }
function remember(direction: ConnectionActivity['direction'], meta: FileMetadata, result: ConnectionActivity['result']) {
emit('activity', { id: crypto.randomUUID(), time: Date.now(), direction, name: meta.name, size: meta.size, result });
}
function disconnect() { function disconnect() {
dispose(); step.value = 'closed'; dispose(); step.value = 'closed';
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed'; if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
@@ -234,14 +231,12 @@ function attach(session: Session, channel: RTCDataChannel) {
onComplete: (direction, { blob, meta }) => { onComplete: (direction, { blob, meta }) => {
if (active !== session) return; if (active !== session) return;
if (direction === 'send') progress.value = 100; else receiveProgress.value = 100; if (direction === 'send') progress.value = 100; else receiveProgress.value = 100;
remember(direction, meta, 'complete');
void session.diagnostics.capture(); void session.diagnostics.capture();
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); } if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
}, },
onDecline: (direction, meta) => { onDecline: direction => {
if (active !== session) return; if (active !== session) return;
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; } if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
remember(direction, meta, 'declined');
if (lastDirection.value === direction) { if (lastDirection.value === direction) {
const other = direction === 'send' ? receiveState.value : sendState.value; const other = direction === 'send' ? receiveState.value : sendState.value;
step.value = other && other !== 'done' ? other : 'session-ready'; step.value = other && other !== 'done' ? other : 'session-ready';
+13 -29
View File
@@ -1,15 +1,6 @@
import { isRecord } from './validation.ts'; import { isRecord } from './validation.ts';
export const CONNECTION_LIMIT = 100; export const CONNECTION_LIMIT = 100;
export const HISTORY_LIMIT = 50;
export interface ConnectionActivity {
id: string;
time: number;
direction: 'send' | 'receive';
name: string;
size: number;
result: 'complete' | 'declined' | 'interrupted';
}
export interface SavedConnection { export interface SavedConnection {
id: string; id: string;
number: number; number: number;
@@ -18,9 +9,8 @@ export interface SavedConnection {
peerKey: string; peerKey: string;
// Per-connection opt-in to include this browser's identity in codes. // Per-connection opt-in to include this browser's identity in codes.
rememberDevice: boolean; rememberDevice: boolean;
history: ConnectionActivity[];
} }
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean } | { activity: ConnectionActivity }; export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean };
export function connectionName(value: string) { export function connectionName(value: string) {
const name = value.trim(); const name = value.trim();
if (!name || name.length > 80) throw new Error('Use a connection name between 1 and 80 characters.'); if (!name || name.length > 80) throw new Error('Use a connection name between 1 and 80 characters.');
@@ -33,26 +23,15 @@ export function updateConnection(current: SavedConnection, update: ConnectionUpd
return { ...current, peerKey: update.peerKey }; return { ...current, peerKey: update.peerKey };
} }
if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true }; if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true };
const item = update.activity; throw new Error('Invalid connection update.');
if (typeof item.id !== 'string' || !item.id || !Number.isSafeInteger(item.time) || item.time < 0 || item.time > 8640000000000000 ||
typeof item.name !== 'string' || !item.name || item.name.length > 255 ||
!Number.isSafeInteger(item.size) || item.size < 0 || !['send', 'receive'].includes(item.direction) ||
!['complete', 'declined', 'interrupted'].includes(item.result)) throw new Error('Invalid connection activity.');
return { ...current, history: [...current.history.filter(previous => previous.id !== item.id), item].sort((a, b) => a.time - b.time).slice(-HISTORY_LIMIT) };
} }
export function emptyConnection(number = 1): SavedConnection { export function emptyConnection(number = 1): SavedConnection {
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false, history: [] }; return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false };
} }
function validateConnection(value: unknown): SavedConnection { function validateConnection(value: unknown): SavedConnection {
if (!isRecord(value) || typeof value.id !== 'string' || !value.id || !Number.isSafeInteger(value.number) || (value.number as number) < 1 || if (!isRecord(value) || typeof value.id !== 'string' || !value.id || !Number.isSafeInteger(value.number) || (value.number as number) < 1 ||
typeof value.name !== 'string' || typeof value.peerKey !== 'string' || !Array.isArray(value.history) || value.history.length > HISTORY_LIMIT) throw new Error('Saved connections are unreadable.'); typeof value.name !== 'string' || typeof value.peerKey !== 'string') throw new Error('Saved connections are unreadable.');
let record: SavedConnection = { id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true, history: [] }; return updateConnection({ id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true }, { peerKey: value.peerKey });
record = updateConnection(record, { peerKey: value.peerKey });
for (const item of value.history) {
if (!isRecord(item)) throw new Error('Saved activity is unreadable.');
record = updateConnection(record, { activity: item as unknown as ConnectionActivity });
}
return record;
} }
async function database() { async function database() {
return new Promise<IDBDatabase>((resolve, reject) => { return new Promise<IDBDatabase>((resolve, reject) => {
@@ -63,8 +42,8 @@ async function database() {
request.onblocked = () => reject(new Error('Close other HellCon tabs to open connection storage.')); request.onblocked = () => reject(new Error('Close other HellCon tabs to open connection storage.'));
}); });
} }
// Read and write within one transaction so other tabs cannot overwrite a rename, // Read and write within one transaction so other tabs cannot overwrite a rename
// paired device, or history entry with a stale copy of the entire record. // or paired device with a stale copy of the entire record.
async function change(action: (records: SavedConnection[], store: IDBObjectStore) => void) { async function change(action: (records: SavedConnection[], store: IDBObjectStore) => void) {
const db = await database(); const db = await database();
try { try {
@@ -74,7 +53,12 @@ async function change(action: (records: SavedConnection[], store: IDBObjectStore
const read = store.getAll(); const read = store.getAll();
read.onsuccess = () => { read.onsuccess = () => {
try { try {
records = read.result.map(validateConnection).sort((a, b) => a.number - b.number); records = read.result.map((raw: unknown) => {
const record = validateConnection(raw);
// Pre-release 0.0.5 builds saved filenames here. Remove them on the first load.
if (isRecord(raw) && 'history' in raw) store.put(record);
return record;
}).sort((a, b) => a.number - b.number);
action(records, store); action(records, store);
} catch (error) { failure = error; tx.abort(); } } catch (error) { failure = error; tx.abort(); }
}; };
+24 -60
View File
@@ -279,16 +279,24 @@ p.stun-hint {
.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; }
.sidebar-section-heading { display: flex; align-items: center; justify-content: space-between; padding: 0 0.65rem; } .sidebar-section-heading { display: flex; align-items: center; justify-content: space-between; padding: 0 0.65rem; }
.sidebar-section-heading h2, .eyebrow { text-transform: uppercase; font-size: 0.68rem; letter-spacing: 0.12em; color: var(--muted); margin: 0; font-weight: 650; } .sidebar-section-heading h2 { text-transform: uppercase; font-size: 0.68rem; letter-spacing: 0.12em; color: var(--muted); margin: 0; font-weight: 650; }
.sidebar-section-heading > span { font-size: 0.72rem; color: var(--muted); } .sidebar-section-heading > span { font-size: 0.72rem; color: var(--muted); }
.connection-nav { display: flex; flex-direction: column; gap: 0.35rem; } .connection-nav { display: flex; flex-direction: column; gap: 0.35rem; }
.connection-link { display: flex; align-items: center; gap: 0.7rem; width: 100%; text-align: left; background: transparent; border: 1px solid transparent; padding: 0.75rem 0.6rem; border-radius: 9px; } .connection-item { position: relative; border: 1px solid transparent; border-radius: 9px; }
.connection-link.selected { background: var(--accent-soft); border-color: #65472e; } .connection-item.selected { background: var(--accent-soft); border-color: #65472e; }
.connection-avatar { flex: 0 0 34px; height: 34px; display: grid; place-items: center; border-radius: 10px; background: #252a36; font-size: 0.88rem; color: var(--muted); } .connection-link, .connection-edit { display: flex; flex-direction: column; align-items: stretch; justify-content: center; gap: 0.4rem; min-width: 0; width: 100%; min-height: 64px; padding: 0.55rem 4.2rem 0.55rem 0.7rem; }
.selected .connection-avatar { color: var(--accent); background: #473022; } .connection-link { text-align: left; background: transparent; border: 0; border-radius: 8px; }
.connection-label { display: flex; flex-direction: column; gap: 0.3rem; min-width: 0; flex: 1; } .connection-link:hover:not(:disabled) { background: #ffffff08; }
.connection-name { font-size: 0.87rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .connection-edit { padding-right: 2.4rem; }
.connection-preview { font-size: 0.72rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .connection-name { color: var(--text); font-size: 0.87rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.connection-status-line { display: flex; align-items: center; gap: 0.45rem; min-width: 0; color: var(--muted); font-size: 0.72rem; }
.connection-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.connection-action { position: absolute; top: 0.45rem; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; background: transparent; color: var(--muted); font-size: 0.9rem; }
.connection-action:hover:not(:disabled), .connection-action:focus-visible { color: var(--accent); }
.edit-action { right: 2.25rem; }
.remove-action { right: 0.35rem; }
.remove-action:hover:not(:disabled), .remove-action:focus-visible { color: #ff9185; }
.connection-rename-input { width: 100%; min-width: 0; border: 1px solid var(--accent); border-radius: 6px; padding: 0.28rem 0.35rem; background: var(--bg); color: var(--text); font: inherit; font-size: 0.87rem; font-weight: 600; }
.connection-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #7c8495; flex-shrink: 0; } .connection-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #7c8495; flex-shrink: 0; }
.connection-dot.connected { background: #69d6a4; } .connection-dot.connected { background: #69d6a4; }
.connection-dot.connecting { background: var(--accent); } .connection-dot.connecting { background: var(--accent); }
@@ -306,19 +314,8 @@ 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 var(--space-xl); border-bottom: 1px solid var(--border); background: #141720; }
.connection-title { min-width: 0; flex: 1; }
.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; }
.header-action { font-size: 0.72rem; padding: 0.3rem 0.5rem; color: var(--muted); background: transparent; border-color: transparent; }
.header-action-icon { margin-right: 0.15rem; opacity: 0.65; }
.header-action:hover:not(:disabled), .header-action:focus-visible { color: #ff9185; }
.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.connected { color: #8ddbb6; border-color: #315344; }
.workspace-scroll { flex: 1; overflow-y: auto; padding: var(--space-2xl) 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: var(--space-2xl); max-width: 1200px; margin-inline: auto; align-items: start; } .connection-workspace { width: 100%; max-width: 720px; min-width: 0; margin-inline: auto; }
.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; }
@@ -338,32 +335,11 @@ input[type=file]::file-selector-button { border: 1px solid #505667; border-radiu
.code-details > .code-entry { margin-top: var(--space-md); } .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 { display: flex; flex-direction: column; gap: var(--space-md); min-width: 0; }
.code-entry > button { align-self: start; font-size: 0.88rem; } .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 > 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-icon { font-size: 1.6rem; display: grid; place-items: center; margin: 0 auto 1rem; width: 54px; height: 54px; border-radius: 16px; border: 1px solid var(--border); color: var(--muted); }
.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); }
p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.empty-activity .activity-note { margin-top: var(--space-xl); }
.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 > div { min-width: 0; }
.activity-icon { color: var(--accent); padding-top: 0.1rem; font-size: 1rem; }
.activity-filename { margin: 0; overflow-wrap: anywhere; font-weight: 500; }
.activity-meta, .activity-result { color: var(--muted); margin: 0.4rem 0; font-size: 0.72rem; }
.activity-item time { font-size: 0.68rem; color: var(--muted); }
.storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; } .storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; }
.sidebar-toggle { display: none; } .mobile-bar { display: none; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
@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: var(--space-2xl); }
.activity-panel { border-left: 0; border-top: 1px solid var(--border); padding: var(--space-xl) 0 0; }
.empty-activity { padding: var(--space-xl) 0; }
.connection-header { padding-inline: var(--space-xl); }
.workspace-scroll { padding: var(--space-xl); } .workspace-scroll { padding: var(--space-xl); }
} }
@media (max-width: 700px) { @media (max-width: 700px) {
@@ -373,23 +349,14 @@ p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.sidebar-open .sidebar { display: flex; } .sidebar-open .sidebar { display: flex; }
.brand { padding-bottom: 0; } .brand { padding-bottom: 0; }
.sidebar-footer { padding-top: 0; } .sidebar-footer { padding-top: 0; }
.connection-header { flex-wrap: wrap; padding: 1rem; min-height: 0; gap: 0.75rem; } .mobile-bar { display: flex; align-items: center; gap: 0.75rem; margin: 0.75rem 1rem 0; }
.sidebar-toggle { display: block; flex-basis: 100%; font-size: 0.8rem; text-align: left; background: transparent; padding: 0.5rem; } .mobile-current { display: flex; flex-direction: column; gap: 0.3rem; flex: 1; min-width: 0; }
.mobile-current-name { font-size: 0.95rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mobile-current-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sidebar-toggle { flex-shrink: 0; margin-left: auto; font-size: 0.8rem; background: transparent; padding: 0.5rem; }
.workspace-scroll { padding: var(--space-lg) 1rem; overflow: visible; } .workspace-scroll { padding: var(--space-lg) 1rem; overflow: visible; }
.title-line { gap: 0.4rem; }
.title-line h1 { font-size: 1.15rem; }
.panel { padding: 1rem; } .panel { padding: 1rem; }
.session-badge { font-size: 0.65rem; padding: 0.35rem 0.5rem; }
} }
.title-line { flex-wrap: wrap; column-gap: 0.6rem; }
.editable-name { display: inline-flex; position: relative; max-width: min(100%, 26rem); min-width: 0; }
.editable-name input { width: 100%; min-width: 0; max-width: 100%; border: 1px solid transparent; border-radius: 7px; padding: 0.12rem 1.65rem 0.12rem 0.4rem; margin-left: -0.4rem; font: inherit; font-size: 1.35rem; font-weight: 600; color: var(--text); background: #ffffff03; text-overflow: ellipsis; transition: border-color 120ms, background 120ms; }
.editable-name input:hover { border-color: var(--border); background: #ffffff06; }
.editable-name input:focus { border-color: var(--accent); outline: none; background: var(--bg); }
.name-edit-icon { position: absolute; right: 0.65rem; top: 50%; transform: translateY(-50%); color: var(--muted); font-size: 0.9rem; pointer-events: none; opacity: 0.65; }
.editable-name:focus-within .name-edit-icon { color: var(--accent); opacity: 1; }
.app-dialog { width: min(460px, calc(100% - 2rem)); max-height: calc(100dvh - 2rem); margin: auto; padding: 1.5rem; border: 1px solid #414858; border-radius: 14px; color: var(--text); background: var(--panel); box-shadow: 0 24px 100px #0009; overflow-y: auto; } .app-dialog { width: min(460px, calc(100% - 2rem)); max-height: calc(100dvh - 2rem); margin: auto; padding: 1.5rem; border: 1px solid #414858; border-radius: 14px; color: var(--text); background: var(--panel); box-shadow: 0 24px 100px #0009; overflow-y: auto; }
.app-dialog::backdrop { background: #080b12b8; backdrop-filter: blur(4px); } .app-dialog::backdrop { background: #080b12b8; backdrop-filter: blur(4px); }
.dialog-header { display: flex; align-items: start; justify-content: space-between; gap: 1rem; } .dialog-header { display: flex; align-items: start; justify-content: space-between; gap: 1rem; }
@@ -401,7 +368,4 @@ p.activity-note { font-size: 0.7rem; color: var(--muted); line-height: 1.6; }
.dialog-actions button { font-size: 0.85rem; } .dialog-actions button { font-size: 0.85rem; }
button.danger { border-color: #b84d42; background: #672f2b; color: #ffe3df; } button.danger { border-color: #b84d42; background: #672f2b; color: #ffe3df; }
button.danger:hover:not(:disabled) { border-color: #ff9185; background: #813b34; } button.danger:hover:not(:disabled) { border-color: #ff9185; background: #813b34; }
@media (max-width: 700px) { @media (max-width: 700px) { .app-dialog { padding: 1.2rem; } }
.editable-name input { font-size: 1.15rem; }
.app-dialog { padding: 1.2rem; }
}
+4 -20
View File
@@ -1,12 +1,10 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { emptyConnection, updateConnection, HISTORY_LIMIT, type ConnectionActivity } from '../src/lib/connections.ts'; import { emptyConnection, updateConnection } from '../src/lib/connections.ts';
test('renaming and pairing preserve a slot identity and its activity', () => { test('renaming and pairing preserve a slot identity', () => {
const initial = emptyConnection(2); const initial = emptyConnection(2);
const activity: ConnectionActivity = { id: 'transfer', time: 1, direction: 'send', name: 'example.txt', size: 123, result: 'complete' }; const renamed = updateConnection(initial, { name: ' Work laptop ' });
const withHistory = updateConnection(initial, { activity });
const renamed = updateConnection(withHistory, { name: ' Work laptop ' });
const remembering = updateConnection(renamed, { rememberDevice: true }); const remembering = updateConnection(renamed, { rememberDevice: true });
const paired = updateConnection(remembering, { peerKey: '04' + 'a'.repeat(128) }); const paired = updateConnection(remembering, { peerKey: '04' + 'a'.repeat(128) });
assert.equal(initial.name, 'Con 2'); assert.equal(initial.name, 'Con 2');
@@ -15,22 +13,8 @@ test('renaming and pairing preserve a slot identity and its activity', () => {
assert.equal(updateConnection(paired, { peerKey: '' }).rememberDevice, true, 'Forgetting a device keeps the opt-in'); assert.equal(updateConnection(paired, { peerKey: '' }).rememberDevice, true, 'Forgetting a device keeps the opt-in');
assert.equal(paired.id, initial.id); assert.equal(paired.id, initial.id);
assert.equal(paired.name, 'Work laptop'); assert.equal(paired.name, 'Work laptop');
assert.deepEqual(paired.history, [activity]); assert.equal('history' in paired, false);
assert.equal(initial.history.length, 0);
assert.throws(() => updateConnection(paired, { name: ' ' })); assert.throws(() => updateConnection(paired, { name: ' ' }));
assert.throws(() => updateConnection(paired, { name: 'a'.repeat(81) })); assert.throws(() => updateConnection(paired, { name: 'a'.repeat(81) }));
assert.throws(() => updateConnection(paired, { peerKey: 'invalid' })); assert.throws(() => updateConnection(paired, { peerKey: 'invalid' }));
}); });
test('history is bounded, ordered, and does not duplicate an event', () => {
let connection = emptyConnection();
for (let i = 0; i < HISTORY_LIMIT + 10; i++) {
connection = updateConnection(connection, { activity: { id: String(i), time: i, direction: 'receive', name: 'file', size: 0, result: 'declined' } });
}
const last = connection.history.at(-1)!;
connection = updateConnection(connection, { activity: last });
assert.equal(connection.history.length, HISTORY_LIMIT);
assert.equal(connection.history[0]!.time, 10);
assert.throws(() => updateConnection(connection, { activity: { ...last, size: -1 } }));
assert.throws(() => updateConnection(connection, { activity: { ...last, direction: 'invalid' as 'send' } }));
});