Compare commits

...
73 Commits
Author SHA1 Message Date
SchluffeandClaude Fable 5.2 3c47047ddd Release 1.0.2: take a file picked again, refuse a dropped folder
Chromium fires no change event when the picker returns the file its input
already holds. The page kept the old one then, though the file may have
changed on disk, which makes the old one unreadable, or another file was
dropped in between, which the input never saw. The input is now emptied as
soon as its file is taken, so every pick fires. Its title names the file
taken, the browser's own tooltip would say no file is chosen.

A dropped folder came as a file of 0 B that can't be read and failed only
once the receiver downloaded it. It is refused with a note now, the file
picked before stays.

Both are covered for Chromium, whose protocol is the only one that reaches
the real picker and a drag from the file manager.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 13:00:35 +01:00
SchluffeandClaude Opus 5.5 1b2696b6b4 Release 1.0.1: update dependencies, count only the lost tracker's offers
Node 26.13.1, Vue 3.5.45, Playwright 1.65.0, Vite 8.3.8, Vitest 5.1.0,
vue-tsc 3.3.14, @vitejs/plugin-vue 6.0.11 and ws 8.23.0 for its bugfix.
ws 8.23.0 is younger than pnpm's minimum release age, pnpm-workspace.yaml
excludes it until then.

The test of an offer waiting on a lost tracker counted every offer the
sender answered. The silent receiver proves the code on its next channel and
may come back by the second tracker before the test ends, so it failed most
runs. It now counts the offers via the lost tracker only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:59:58 +01:00
SchluffeandClaude Opus 5.5 ac4d496a48 Version the protocol for 1.0, fail downloads the page abandoned
PROTOCOL (hellcon/1) goes in front of the PBKDF2 salt and names the data
channel, so different versions never meet via a tracker and the manual
receiver tells a sender on another protocol apart. The footer shows it, the
receiver's hints ask to compare it. Forks are asked to name their own.

public/sw.js and the page exchange a VERSION, a mismatch fails the download
with outdated. The worker fails a download after 20 s without a chunk or
ping from its page, else Firefox saves the truncated file of a closed tab as
complete.

The build uses relative links and works under any path. On https only wss:
trackers and ws: to this device are accepted, one the browser refuses to
open counts as lost. Also: a file read short stops the transfer, an offer
waiting on a lost tracker isn't answered, a share ended while its key was
derived opens no tracker, and tracker and receiver errors lose hidden
characters. The README lists what isn't planned and the phone limitation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:10:09 +01:00
SchluffeandClaude Opus 5.5 44a8a72261 Keep the screen on and ask before leaving while a session is busy
While a share waits or a transfer runs, the page holds a Screen Wake Lock,
requested again once the page is visible, since the browser releases it
whenever it's hidden. A beforeunload handler makes the browser ask before a
reload or a closed tab ends the session, only while busy so the page stays
eligible for the back/forward cache otherwise. Covered by awake: with a fake
wake lock, a headless browser may not grant a real one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:51:51 +01:00
Schluffe 870d55b44f Set Content-Security-Policy 2026-10-30 13:39:16 +01:00
SchluffeandClaude Opus 5.5 af0a8c9fee Strip controls, line separators and bidi controls from offered file names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:38:10 +01:00
SchluffeandClaude Opus 5.5 7f4811485a Limit what a tracker can make the page do, recommend anti-framing headers
A tracker message over 64 KiB isn't parsed, before acceptance it rejects
the tracker like a failure reason. Beyond 20 messages per 10 s the rest is
dropped, so a tracker can't keep the page parsing and decrypting. What a
tracker makes a socket log goes through one note: each line once, at most
10 per socket. The log keeps the last 1000 lines in a shallow ref and says
how many went.

index.html sets Referrer-Policy itself, the README recommends the headers a
<meta> can't set: frame-ancestors, X-Frame-Options and nosniff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:29:23 +01:00
SchluffeandClaude Opus 5.5 b102e55495 Limit the tracker per address and harden its plain HTTP path
Per address and minute: connects and forwarded signaling, so reconnecting
doesn't reset a client's allowance. X-Forwarded-For only counts from PROXIES,
checked with net.BlockList, with one warning when an uncovered peer sends it.
Plain requests get timeouts and a closing 404, silent connections go after
30 s and all queues together share a budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:27:50 +01:00
SchluffeandClaude Opus 5.5 ae1e3bef9b Hash all fingerprints into the manual security check
The manual check used to show the first 8 bytes of the first fingerprint
each SDP named, so an interposer could add its own certificate beside the
claimed one and the codes still matched. Now each code is the first 16
bytes of a SHA-256 over every fingerprint the SDP names, also ones hidden
in other lines, so whatever the browser uses changes the code. Without a
fingerprint on either side the connection ends. End-to-end tests try a
claimed certificate in several hiding places.

The README says that a working connection isn't necessarily direct and what
the meeting tracker sees, TODO.md lists hardening from a security review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:23:04 +01:00
Schluffe ae871a2647 Improve tests 2026-10-28 22:24:24 +01:00
Schluffe 8f82700736 Refactor the app 2026-10-28 21:05:47 +01:00
SchluffeandClaude Opus 5.5 f53d39ae69 Update Biome to 2.6.3 and pnpm to 12.16.1
TypeScript stays on 6, vue-tsc can't load TypeScript 7 yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:01:49 +01:00
SchluffeandClaude Opus 5.5 aa61efcc10 Let the receiver fix a wrong salt during a search
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:51:20 +01:00
SchluffeandClaude Opus 5.5 2e47b55901 Salt the tracker swarm with the clock or an own salt
The code used to be derived with a fixed salt, so a tracker could compute a
table from swarm to code ahead of time, once for every share. Now the salt
is the UTC 6 minute window the share was made in, and the code's new 11th
character names that window, so the receiver finds it even with a clock
hours off. Use own salt adds a salt both sides agree on, which nobody can
guess ahead for; Generate makes a random one. The salt is locked while a
tracker share or search runs, and a receiver that finds no sender is told
to check the salt too.

Settings are no longer kept in localStorage: a remembered list or salt that
differs from the other side's would silently break shares. The core now
reports when a share expires and until when it lasts, and the session owns
a tracker's timers, so a socket still closing after an abort announces
nothing more. Header options line up with the cards, disabled switches look
disabled, and sizes, percents and times don't wrap. postcss 8.5.32.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:14:27 +01:00
Schluffe e3a2b348d6 Harden the app 2026-10-26 20:48:24 +01:00
SchluffeandClaude Opus 5.5 d92c4b50cf Let one pill pass through the bar until the transfer starts
Start, wait and retry used a gradient sweep and a pulse, which felt restless.
Now a solid pill passes through the bar at an even speed for all three, pink
while retrying, and the line below says the rest. The sender's waiting line
is shorter, the code's label already says to give it to the receiver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 19:28:45 +01:00
SchluffeandClaude Opus 5.5 f7e8999439 Show how a session is doing on the progress bar
Each side's bar now shows the session's phase by color and movement, with a
short line below saying what is going on: a sweep while connecting, a pulse
while someone has to act, a slow pink sweep while retrying after a failure
(with the reason and the attempt), then the transfer, done, stopped or error.
A receiver whose code no tracker knows says so right away instead of after
6 minutes, and a connection that fails though both sides have a public
address names a blocking network as the likely reason.

The log marks where each session starts. The send card names the session's
file once another one is picked, and a blocked clipboard is shown inline with
the text selected for copying by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:26:53 +01:00
Schluffe 02668de602 Add IPv6 to the coturn config 2026-10-25 20:46:19 +01:00
SchluffeandClaude Opus 5.5 3c4e706e1f Keep a finished download's frame for a moment
Small downloads, empty or one byte, were sometimes never saved, though the worker reported them
finished and both sides logged success. The browser can read the whole response before it hands
the navigation to its download manager, and the frame was removed right then, which cancels it.
Without a delay an empty file failed 8 of 10 runs, a one byte file 4 of 10.

The download's frame now stays for DOWNLOAD_GRACE (1 s) after finished, the frame that holds the
worker still goes right away. No event tells when the browser took the download, so the 1 s is
empirical. A new test checks the retention on a paused clock, it fails without the delay and with
the worker's frame held too. The browser's timing it can't cover, TODO.md keeps a record of that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
SchluffeandClaude Opus 5.5 bd0154db68 Tell the user when a missing public address explains a failed connection
Without STUN a side offers only local addresses, enough on the same network or VPN. Between
networks the connection never came up, and nothing said why: tracker signaling only logged "did
not connect" and ended after 6 minutes with the generic message, the manual exchange in Chromium
never ended at all, since Chromium doesn't fail a connection without usable addresses.

A connection that doesn't come up now checks both SDPs for a public address (typ srflx) and names
the side without one, in the log and in the error at the end of the session. That covers STUN
turned off, an empty list and servers that don't answer, on either side. A device with a public
address of its own offers none either, so it's a hint. The manual sender gives up 30 s after the
answer, the receiver after 6 minutes, it has to hand the answer over first.

A note above the cards says when STUN is off or no server is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
Schluffe 21ea9a7e02 Update node packages 2026-10-25 19:04:06 +01:00
SchluffeandClaude Opus 5.5 840bc3572b Contact one STUN server and one tracker at a time
Both sides used to contact every STUN server and tracker at once, so each of them learned the IP
address and each tracker that A sent to B.

Connections now use one STUN server: the first in the list that reports a public address to a
throwaway probe connection within 2 s. It stays for the page's lifetime. If a connection gets no
address from it, the next connection probes on from the server after it. A probe runs only while a
session waits for it and stops once none does, STUN is turned off or the list changes.

The sender joins the first tracker that accepts it and moves to the next only once that one rejects
it, can't be reached within 10 s or is lost. The receiver walks the list with one offer each and
stays where a tracker reports a seeder (complete), which is the sender: it always announces before
anyone has the code. Trackers it passed keep its offer. backend/tracker.mjs now sends complete.

wss://tracker.pagequit.net comes first in the default trackers, the public ones are fallbacks.
TODO.md drops the server tasks, they aren't work on this codebase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:51:42 +01:00
SchluffeandClaude Opus 5.5 5729ed62f7 Add backend/.env.example
It shows what ORIGINS has to look like: exactly what browsers send as Origin, so scheme, host and a
non-default port, without path or trailing slash. Anything else locks out every client. CADDY_NETWORK
is there too, commented out with its default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:51:42 +01:00
SchluffeandClaude Opus 5.5 8b36e51b56 Require Node.js 26.12.1, it fixes CVE-2026-111497
26.11.1 has the out-of-bounds write in its Brotli decoder. The tracker decompresses nothing, but
the image and development machines should still not run an affected version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:09:49 +01:00
SchluffeandClaude Opus 5.5 4725b14a40 Limit pings like messages in the tracker
ws answered every ping on its own, past the message rate limit and past the bound on bytes queued
for a peer: a client pinging without reading made the tracker buffer pongs until it ran out of
memory. Pongs are now sent by the tracker, pings and pongs count as messages, and a pong is queued
only within the same bound as any message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:54:03 +01:00
SchluffeandClaude Opus 5.5 22d794965e Add an own tracker and STUN server in backend/
backend/ runs both as Docker Compose services, neither is needed: the client works with any
WebTorrent tracker and STUN server. The tracker is one file on Node and ws that does only the part
of the protocol HellCon uses. It accepts allowed origins only and messages of at most 16 KiB, only
announce, one offer per announce and answers only to offers it delivered, once. Forwarded messages
are rebuilt from the checked fields. It limits the message rate, the signaling each connection
sends, the bytes queued for a peer that stops reading, connection age, connections per IP and in
total, and peers per swarm. It logs nothing. coturn runs STUN only on the host network, pinned,
read-only and without capabilities beyond the one its binary needs.

backend/tracker.spec.mjs tests its rules one by one, e2e.spec.ts sends a real file through it alone
in both directions between Chromium and Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:26:42 +01:00
SchluffeandClaude Opus 5.5 bb69569b51 Seal tracker signaling with the code
The SDP relayed by the trackers is now encrypted with AES-GCM under a key derived from the code,
next to the swarm ID and the proof key. Trackers and peers that found the swarm without the code
no longer learn either side's addresses, and an offer or answer that doesn't decrypt is dropped
before any peer connection exists, so it can't take the sender's turn. The proof stays as a
second layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:52:32 +01:00
Schluffe 338d4d2532 harden e2e tests 2026-10-25 13:31:27 +01:00
SchluffeandClaude Opus 5.5 c6145b8919 Let the code prove tracker connections instead of the user
Both sides derive an HMAC key from the code, next to the swarm ID, and sign
their role and both DTLS fingerprints as they see them. An interposer or a
peer that found the swarm without the code can't, so its connection ends and
the next peer gets its turn, as does one that proves nothing within 10 s.
Tracker transfers need no comparing and no clicks anymore, the manual
exchange keeps its fingerprint check. The swarm ID changes once more, old and
new clients don't find each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:05:58 +01:00
SchluffeandClaude Opus 5.5 707248f36b Derive the swarm ID with PBKDF2 instead of SHA-1
Anyone who sees the swarm IDs could test a GPU's worth of codes against all
of them at once, about 8 % of the codes within a share's 6 minutes. 600,000
iterations of PBKDF2-SHA-256 cost a share ~50 ms and make that negligible.
Old and new clients no longer find each other.

Also note the open decisions for the server at pagequit.net.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 12:46:36 +01:00
SchluffeandClaude Opus 5.5 b6b6e7c29b Lint and format with Biome, and retire used share codes
Biome formats and lints the TypeScript, the Vue templates and the CSS:
pnpm lint checks, pnpm format fixes. It keeps the existing style, single
quotes and 120 columns, and leaves the vendored logo alone. Besides its
recommended rules it looks for promises nobody awaits. Rules that only
flagged deliberate code are off: non-null assertions that state what the
code guarantees, CSS order where no two rules set the same property, and
fieldset for role="group". The one-time formatting pass mostly splits
long chains.

Promises that are deliberately not awaited are marked with void, none of
them can reject today. Buttons say type="button", the any for peer
messages and the checkbox switch keep their reasons in ignore comments.

The sender's code also counts as no longer valid once a transfer started:
that closes the trackers, so another receiver would wait for nothing,
yet the card still offered the code with Copy. The tracker transfer
tests check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 18:46:33 +02:00
SchluffeandClaude Opus 5.5 2167b528b2 Keep tracker shares alive for 6 minutes, then let them go
Both default trackers closed the socket of a peer that announced only
once, after about 2 and 3 minutes, and the card then wrongly said no
tracker was reachable. Sender and receiver now announce again on the
interval the tracker names (at least 30 s apart, whatever it names), the
receiver with its same offer.

A share, or a receiver looking for one, gives up after 6 minutes without
a download: its tracker sockets close and the card says nobody came. A
peer connected by then still gets its turn, the transfer itself has no
time limit. The sender's code shows until when it is valid and is marked
no longer valid, without Copy, once it expired or the share failed.

A receiver that lost every tracker now closes its peer connections too,
and the expiry timer goes with the session when it is cancelled, fails
or the download starts.

Tests fast-forward the page clock: re-announcing and expiry on both sides
against mocked trackers, no timer or connection left after cancelled and
failed sessions, and a live download after the deadline passed during
the security check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 17:55:45 +02:00
SchluffeandClaude Opus 5.5 a35bd71ca7 Report rejecting trackers and let go of closed connections
A tracker that answers the announcement with a failure reason counts as
gone, like an unreachable one: its socket closes, and once no tracker is
left the card says which rejected it and why. A failure after the tracker
accepted only concerns that message and is still just logged.

Closing a connection or socket before the session ends now removes its
abort listener, so repeated unusable offers or rejected peers no longer
pile up until the session ends. The sender drops its per-peer listener
when it stops, the receiver only adds one once the download starts.

Both are covered by tests against mocked trackers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:19:27 +02:00
SchluffeandClaude Opus 5.5 0df1dd4f70 Write the README for users
Explains how to send a file, the security check, how the connection is
set up, what others can see, the settings, self-hosting and the known
limitations. Developer details stay out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:10:28 +02:00
SchluffeandClaude Opus 5.5 2abd0b504d Own each transfer in a session and harden the protocol
Every operation (share, receive, manual offer or answer) now runs as one
session tied to an AbortSignal. Starting another ends it: its connections,
tracker sockets and timers close, and it can no longer touch the shared
security check, progress or incoming file. Finished, failed and cancelled
transfers close their connections, and the sender's tracker sockets close
once the download starts.

- A malformed or never-connecting tracker offer no longer blocks a share
- The receiver validates the file offer and rejects excess bytes and
  data beyond the flow control window; sw.js checks name and size too
- Failures show up in the card instead of disappearing into rejected
  promises: bad manual codes, unreachable trackers, lost connections
- Primary buttons and pink text meet 4.5:1 contrast, the STUN switch
  shows keyboard focus again, the tracker Copy button matches the others
- Split the core into src/core.ts, src/main.ts only mounts the app, which
  removes the main.ts <-> App.vue import cycle
- Bring back the Gitea source link, write the README
- Tests reuse one browser per worker with fresh contexts, fail on page
  errors, check cleanup after transfers, use a local fake STUN server
  and cover empty files, window boundaries, odd names, malformed
  messages, session replacement and the production build

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:04:14 +02:00
SchluffeandClaude Opus 5.5 bacc15baaf Ask before downloading and show transfer progress
Tracker codes now use 8 of [0-9a-zA-Z] instead of 8 digits. After both
security checks the receiver sees the offered file and starts the download
itself, the sender waits for it. Both sides show a progress bar of what the
download manager has read. Copy buttons for the tracker code, offer and
answer; the manual exchange is folded away below the tracker on both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:15:48 +02:00
Schluffe 85ccdbfc03 Add server lists to edit 2026-10-23 20:19:07 +02:00
SchluffeandClaude Opus 5.5 08b9f659c2 Lengthen codes and keep going after a failed security check
The security check compares 8 instead of 5 fingerprint bytes, too many to
brute force matching certificates. The tracker code has 8 digits, making
collisions between concurrent senders 100x less likely.

A "Codes don't match" button, or a peer leaving before the transfer
starts, ends that connection without ending the share: the tracker sender
answers the next (or a queued) offer, the receiver replaces its used up
offers. Both codes are aligned below each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:01:45 +02:00
Schluffe 9282865a8c Add styling 2026-10-23 00:22:49 +02:00
Schluffe 1bfeb9843a add missing ws.js and introduce save check for both sides 2026-10-22 23:29:55 +02:00
Schluffe ff7b84af02 Fix large file download 2026-10-22 22:57:41 +02:00
SchluffeandClaude Opus 5.5 aea75fff92 Add file transfer PoC with manual and tracker signaling
- Core in src/main.ts: manual SDP copy/paste exchange (default, no
  tracker) and optional WebTorrent tracker signaling, STUN opt-out
- Fingerprint security check, sender confirms before sending
- ICE gathering stops after the first STUN result (5 s hard cap)
- Receiver writes to OPFS via an inline dedicated worker instead of RAM
- Playwright e2e suite across Chromium/Firefox and all signaling modes,
  opt-in 2.5 GiB transfer test (pnpm test:large)
- TODO.md with review findings and the service worker plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 00:35:36 +02:00
Schluffe 24307eb96a Start from scratch 2026-10-21 20:57:44 +02:00
Schluffe 9f3f21884f Release 0.0.6 with reconnect fixes and regression coverage 2026-10-21 00:39:08 +02:00
SchluffeandClaude Opus 5.5 acba97a7e1 Confirm reconnect pairings and add connection discovery settings
Setup now waits for both IndexedDB writes: the acceptor acknowledges its
write, a failure on either side is reported to both people, and the
proposer removes its copy if the acceptor could not save. Every session
that authenticates the paired device compares a check value derived from
the stored pairing, so a one-sided pairing (interrupted setup, or Turn off
reconnect on one device) is turned off on the other side too.

The tracker is chosen under Network settings > Connection discovery
(manual, default from VITE_TRACKER_URL, or custom), stored per browser and
editable during a session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:30:04 +02:00
SchluffeandClaude Opus 5.5 3659956967 Add experimental tracker reconnect for paired devices
During a session authenticated by both device identities, one person
proposes a WebTorrent tracker and the other confirms it. Both contribute
a nonce over the data channel; HKDF binds both device keys, the session
fingerprints and the tracker URL into a non-extractable base key stored
with the connection. Forget device, a replaced paired device and Turn
off reconnect clear it.

Reconnect joins a daily swarm derived from that key. Offers, answers and
codeless wakes travel as AES-GCM envelopes bound to the tracker routing
fields. The lower device key offers; the other device wakes it when it
arrives second. Retries are spaced and capped, one attempt per slot runs
under a Web Lock, and fresh device proofs still authenticate the session.

Checked against tracker.openwebtorrent.com and tracker.webtorrent.dev
with the new opt-in browser check (--tracker=<url>). Signaling v5,
midnight rollover, clock skew, CSP and real-network checks remain open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:51:05 +02:00
SchluffeandClaude Opus 5.5 a5935a8324 Remove shareable invitation links
Codes are exchanged by copy and paste again. The URL fragment intake,
the invitation dialog, the BroadcastChannel answer relay and the Share
link / Copy link controls are gone, along with their tests, browser
check scenarios and design doc. Code fields no longer accept links.

The compressed HC1 codes with typed offers/answers and echoed refs stay.
An optional signaling backend is the intended way to simplify the
exchange instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:47:07 +02:00
SchluffeandClaude Opus 5.5 f320bfb541 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>
2026-10-19 23:46:12 +02:00
Schluffe 4323a8b774 Add gitea link 2026-10-19 23:15:19 +02:00
Schluffe 019267cc34 Add shareable invitation links II 2026-10-19 23:09:18 +02:00
SchluffeandClaude Opus 5.5 43ee7f119f Add shareable invitation links
Codes now travel as links with the code in the URL fragment, which the
app reads and clears before mounting (and on hashchange). An offer link
opens a preview that suggests an idle slot, preferring the one paired
with the sender's device, and only fills in the code; the user still
creates the answer. Answer links reach the waiting sender tab over a
same-origin BroadcastChannel, are acknowledged once and reported as
used afterwards, and fall back to copy and paste when no tab answers.

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 21:16:39 +02:00
SchluffeandClaude Opus 5.5 e3af2de051 Add self-hosted WebTorrent tracker container and reconnect plan
Build a WebSocket-only tracker from the official Node image and a locked
bittorrent-tracker 11.2.3, run via compose.tracker.yaml and the
tracker:up/tracker:down/test:tracker scripts. A small wrapper disables
scrape and stats and bounds input: frame validation, per-IP connection
and message limits (IPv6 grouped per /64), origin checks, a fixed peer ID
and at most four swarms per socket (tracked synchronously, so pipelined
frames cannot bypass it), swarm and peer caps, idle-socket timeout and
explicit expiry of stale swarm memberships. Forwarded addresses are taken
from the rightmost X-Forwarded-For entry and only from trusted proxies.

Integration tests use only Node built-ins. Document the planned tracker
reconnect design; the app still uses manual connection codes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 21:03:45 +02:00
Schluffe 8665d04f2c WIP VI improve UX [snapshot task 2] 2026-10-17 15:18:50 +02:00
Schluffe a73b3075b6 WIP V improve UX [snapshot task 2] 2026-10-17 14:51:48 +02:00
SchluffeandClaude Opus 5.5 5f8c6a1916 WIP V improve UX [snapshot task 2]
Add the connections workspace (sidebar, editable slots, per-slot activity,
removal dialog with focus wrapping), remove the downloadable local HTML and
unreleased identity backup/restore, and start the 0.0.5 draft changelog.
Restore the released 0.0.3/0.0.4 changelog entries. Enable focus emulation
in browser checks so background tabs receive focus/blur events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:44:08 +02:00
Schluffe 58c3e2af86 WIP IV improve UX [snapshot task 2] 2026-10-17 00:59:12 +02:00
Schluffe 28c90d1d71 WIP III improve UX [snapshot task 2] 2026-10-16 16:09:43 +02:00
Schluffe b2bab26981 WIP II improve UX [snapshot task 2] 2026-10-16 16:01:56 +02:00
Schluffe cd66321ea6 WIP improve UX [snapshot task 2] 2026-10-16 15:39:31 +02:00
Schluffe 3ae47dde8e Release 0.0.4 2026-10-16 14:57:17 +02:00
Schluffe 7856725c72 Add hosted service-worker streaming downloads 2026-10-16 13:49:17 +02:00
Schluffe a53022d717 Checkpoint before hosted streaming downloads 2026-10-16 13:37:54 +02:00
Schluffe b7f47531b7 fix timeout issue (maybe?) 2026-10-16 12:01:43 +02:00
Schluffe 95e4a879b9 fix ts issue 2026-10-16 11:34:18 +02:00
Schluffe a90bf45db3 update stuff 2026-10-16 11:30:16 +02:00
Schluffe 1d8e595b75 Add stun.pagequit.net 2026-10-09 16:46:13 +02:00
Schluffe 62c749de73 Add local HTML download and release 0.0.3 2026-10-09 15:25:56 +02:00
Schluffe bee62a79a9 bump version 2026-10-09 14:58:14 +02:00
Schluffe 00b2ec7d5c Improve a11y 2026-10-09 14:55:05 +02:00
45 changed files with 8943 additions and 2338 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
# Run bun run dev:setup to create .env.development with a random secret.
TURN_SECRET=replace-with-a-random-secret
TURN_HOST=127.0.0.1
TURN_PORT=3478
VITE_ICE_ENDPOINT=/api/ice-servers
VITE_STUN_URL=stun:127.0.0.1:3478
+1
View File
@@ -3,3 +3,4 @@ dist
.env
.env.*
!.env.example
test-results
-39
View File
@@ -1,39 +0,0 @@
# Changelog
## [0.0.1] - 2026-10-09
### Added
- Mandatory full SHA-256 fingerprint confirmation by both peers before sharing
file metadata or contents.
- Receiver acceptance and direct-to-disk saving in supported browsers.
- Optional TURN relaying, requiring explicit opt-in from both peers. Consent
clears after a connection completes, fails, or is reset or cancelled.
- Protocol regression tests and Chromium, Brave, and Firefox integration checks.
### Changed
- Enforced message validation, exact file sizes, and bounded buffering.
- Limited memory downloads to 64 MiB and direct-to-disk transfers to 64 GiB.
- Report transfer completion only after receiver acknowledgment.
- Updated dependencies, including the fix for the `source-map-js` advisory.
- Clarified encryption, hosting trust, connection-code privacy, and deployment
requirements.
### Fixed
- Reset failing to restore the ready state.
- Invalid answers unnecessarily destroying valid connection offers.
- Connections and unfinished disk writes surviving cancellation or tab changes.
- Completed Firefox downloads disappearing when Brave disconnected.
- Excess data, duplicate metadata, and malformed messages corrupting transfers
or causing unbounded memory growth.
- ICE gathering silently returning incomplete connection information, and
stalled transfers waiting indefinitely.
### Compatibility
- Introduced signaling and transfer protocol v2. Both peers must use the updated
app; connection codes from earlier versions are no longer accepted.
- Files larger than 64 MiB require a receiving browser with direct-to-disk
saving support.
+142 -206
View File
@@ -1,240 +1,176 @@
# HellCon
Current version: **0.0.1**. See the [changelog](CHANGELOG.md) for release notes
and compatibility changes.
Send a file straight from one browser to another. No account, no upload, no app to install, and no
size limit: the file goes directly to the other person and is never stored on a server.
Browser-to-browser file sharing with Vue 3 and WebRTC. No accounts, signaling
backend, or server-side file storage. You exchange connection codes manually.
Direct connections are the default. TURN relaying is optional and requires
explicit opt-in by both people; no relay is configured automatically.
## How to send a file
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
get the file, or pretend to be you, so give it to nobody else.
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
tab was doing.
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
protocol.
### Without a tracker
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
**Connect**. The offer and answer contain your network addresses, so only share them with the person
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
## The security check
Before anything is transferred, both sides make sure they are connected directly to each other and
not to someone who placed themselves in between.
With the code this happens by itself: each side proves to the other that it knows the code, tied
to the encryption keys of this very connection. Someone in between, or anyone else who doesn't
know the code, can't do that, and HellCon drops the connection and waits for the right one.
The manual exchange has no code, so there you compare yourselves. Once connected, both sides see two
codes: **You** and **Peer**. Compare them with the other person over a channel you already trust,
ideally a call or in person:
- your **You** must be their **Peer**, and
- your **Peer** must be their **You**.
If both match, you are connected directly to each other. If they don't, someone has placed
themselves in between: click **Codes don't match** and nothing is sent. Nothing is transferred before
both sides confirmed, so take the time to compare every character, not just the start and end.
The codes are taken from the encryption keys of the connection. Someone in between would need their
own keys, which show up as different codes.
## How it works
1. The sender picks one file and configures STUN (Google by default, Cloudflare,
a custom provider, or None). They create a code and send it privately to the
intended receiver through an authenticated channel.
2. The receiver pastes the code, creates an answer, and sends it back. The sender
pastes the answer. Gathering waits for completion, up to 30 seconds; a timeout
fails rather than quietly exporting incomplete connection information.
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.
4. The receiver sees the filename and size and explicitly accepts the file.
Supported browsers can stream directly to a chosen disk destination, up to
64 GiB. Other browsers can receive files up to 64 MiB in memory and then offer
a download. Larger files require direct-to-disk support. Even capped memory
downloads 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 memory
transfers, after constructing the complete download. This does not prove a
human saved the memory download, nor that a malicious receiver told the truth.
The file travels over a direct, encrypted WebRTC connection between the two browsers. To set that up,
the browsers need two things:
Cancel, reset, changing the selected file, or switching Send/Receive closes the
connection and aborts unfinished disk writes. Keep the tab open until receipt is
confirmed. A completed memory download is discarded when you reset or switch.
Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. The two peers must use this protocol version (v2);
legacy connection codes are rejected.
- **Finding each other.** The code puts both browsers into the same group on a public
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
forth. They are encrypted with the code, so the tracker can't read them, and neither can anyone
else in the group without the code. It never sees the file. With the manual exchange you play the
tracker yourself.
- **Reaching each other.** Most devices sit behind a router and don't know their public address.
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
only on the same network or over a VPN.
If an answer is rejected as invalid, correct the pasted answer and click Connect
again; the sender keeps its existing offer while it is still awaiting an answer.
After a connection actually closes or fails, use Reset and exchange a **new offer
and new answer**. Old codes refer to the closed connection and cannot reopen it.
Reset returns the page to its initial ready state. For a local test, open two
separate browser tabs or windows; switching Send/Receive inside one page cancels
that page's previous connection. Use the specific error shown in red to diagnose
failures; if a configured STUN server is unreachable, try None for a local test.
On the receiving side, HellCon hands the incoming data to the browser's own download manager while
it arrives. That's why files larger than your memory work too, and why the download shows up in
your browser's download list.
## Network privacy and optional TURN
HellCon uses no relay server. If both sides are behind very strict networks, e.g. some company or
mobile networks, a direct connection may not be possible. And a connection that works isn't
necessarily direct: the other side may name a relay of its own, and a STUN server that reports a
wrong address can put itself in between. Either only passes on encrypted data. The security check
makes sure the connection ends at the two of you.
STUN discovers externally reachable addresses. Its operator can see your public
IP address and request metadata, but STUN does not relay file contents. Lookups,
retries and connectivity checks may involve multiple packets. Choosing None
avoids contacting a configured STUN provider; direct connectivity depends on
addresses, routing, browser policy and firewalls, not simply whether peers share
one network. A VPN is not automatically a guarantee against address disclosure.
## Privacy
Connection codes are **Base64-encoded, not encrypted**. They contain SDP,
including candidate addresses, temporary ICE credentials and certificate
fingerprints. Peers and anyone who sees these codes (including the messaging
service used to exchange them) may learn connection details. Local addresses may
be obscured by the browser, but this app does not provide anonymity. Treat codes
as private session information; do not publish them.
- The file only goes to the person you connected with.
- That person learns your IP address, as with any direct connection. One STUN server and one or a
few trackers see it too, from the request itself. HellCon tries the STUN servers in order and
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
receiver goes down the list until it finds the sender, and the trackers it passes keep its
encrypted offer. Nobody without the code learns your address through a tracker. The tracker the
two of you meet on does see which addresses share with each other, and when. If that matters,
use your own tracker and STUN server, or the manual exchange.
- Nothing is kept: every reload starts with the default settings.
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
host your own (below).
Restrictive NATs or firewalls can prevent direct connections. There is no silent
TURN retry. To permit a relay, both people must explicitly check **Allow a TURN
relay**, supply their authorized TURN URL, username and password, and generate
new codes. Otherwise TURN URLs are rejected in the STUN field and codes with
relay candidates are rejected. Enabling TURN allows the browser to contact that
relay during gathering and select a relay route when needed. This does not force
relay-only routing or hide your IP from the peer. A remote peer can independently
proxy their own traffic; the opt-in controls this app's configuration and the
relay candidates it accepts, not arbitrary software run by the other person.
## Settings
When a credential endpoint is configured (including the local development setup
below), **Use the configured relay with temporary credentials** replaces manual
credential entry. The app fetches fresh credentials for each new connection,
only after TURN opt-in. Uncheck it to use a different relay manually.
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
brings back the original lists. The order matters: the sender stays on the first tracker that
works, the receiver tries them in order until it finds the sender. Both lists must contain that
tracker.
TURN credentials stay in the current component's memory; the app does not persist
them or include them in codes. The relay receives its authentication exchange and
can observe addresses, timing and traffic volume, and may charge for bandwidth.
Resetting, cancelling, completing or failing a connection clears TURN consent;
check the option again before creating another relayed connection.
File traffic remains DTLS encrypted through the relay. The web host, DNS resolver,
and code-exchange service are also relevant third parties.
The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC):
guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the
receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could
still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both
sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody
can guess ahead for a salt they don't know.
## Security model and limits
Nothing of this is kept, a reload brings back the defaults.
Data channels use **SCTP over DTLS**, which provides transport confidentiality and
integrity. This is not DTLS-SRTP (the media transport). DTLS authenticates the
certificate in the connection description; an independently authenticated full
fingerprint comparison binds that certificate to the intended peer. Comparing
fingerprints through a channel an attacker can rewrite provides no such assurance.
## Host your own
You must trust your browser, device, and **the JavaScript you load**. A compromised
host or build can steal plaintext or falsify the verification display. Serve the
production build over HTTPS, or run a verified build you control on localhost.
HTTPS protects delivery against network tampering, not against a malicious host.
The app does not upload files to its web host in this implementation; that is a
property of this code, not a guarantee against a host serving different code.
The protocol accepts one ordered, reliable data channel, bounded metadata and
messages, an exact declared byte count, and a single file. It rejects unexpected
states, excess data and duplicate metadata. An acknowledged 1 MiB send window
and a bounded receive queue limit buffering during disk writes. Files are treated
as opaque downloads; metadata is not rendered as HTML. Encryption does not make
a file safe to open. These limits reduce denial-of-service exposure but do not
eliminate browser, device, network, or malicious-peer risks.
For deployment, serve `dist/` as static files over HTTPS. Do not expose the Vite
dev or preview server as the production service. Configure hosting headers such
as `Content-Security-Policy` (including `frame-ancestors 'none'`),
`X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. A baseline
CSP for this build is `default-src 'self'; script-src 'self'; style-src 'self'
'unsafe-inline'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri
'none'; frame-ancestors 'none'`. Inline styles are currently used for progress and
Vue visibility. Test headers on the actual host; CSP is defense in depth and is
not a substitute for trusting the host or a portable WebRTC egress filter.
`robots.txt` and indexing metadata are crawler requests, not access control.
## Development
### 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.
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
```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
pnpm install
pnpm build
```
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 completion clears consent, so check it again for each connection.
STUN defaults to the local server; TURN remains opt-in, with direct routes preferred.
Then serve the `dist/` folder, with these requirements:
```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
docker compose --env-file .env.development logs --tail=50 coturn
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
trying it out).
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
HellCon must reach it unchanged, so don't rewrite them to `index.html`. Any path works, e.g.
`https://example.org/hellcon/`, with the trailing slash: the page links its files relative to it,
so redirect `/hellcon` there.
Recommended, as response headers, a `<meta>` can't set them (`index.html` sets
`Referrer-Policy: no-referrer` and the rest of its Content-Security-Policy itself, which keeps out
scripts and styles from elsewhere but allows connections to any tracker):
```
Content-Security-Policy: frame-ancestors 'none'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
```
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.
The first two keep other sites from framing HellCon and laying their own page over its buttons,
`X-Frame-Options` for older browsers.
Stop Vite with Ctrl-C, then:
Your own tracker and STUN server are optional, any public ones work. `backend/` has both as Docker
Compose services: a tracker that only does what HellCon needs, with an Origin allowlist and limits,
and coturn as STUN server. `backend/compose.yaml` says how to set them up.
```sh
bun run turn:down
# Optional: stop Docker too, after finishing any other containers.
sudo systemctl stop docker.service docker.socket containerd.service
```
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
`.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.
## Not planned
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.
These were considered and decided against, please don't ask for them without a new reason. HellCon
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
needs infrastructure of its own or only helps small files doesn't pay off.
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.
- **The code in a share link:** the code would end up in the browser history and wherever links get
handled, for one click less.
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
the code anyway.
- **Saving without the service worker,** holding the file in memory instead: useless for files of
several GB.
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
- **A longer or extendable share,** **several files as a zip,** and **resuming in Chromium:** not
for now.
- **Keeping a phone sending in the background,** e.g. with a silent audio loop: the sender's page
has to stay in front.
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).
## Known limitations
### 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
bun install --frozen-lockfile
bun run dev
bun run typecheck
bun run test
bun run build
bun run test:browser # local Chromium integration checks against dist/
bun run test:cross-browser # Brave sender → Firefox receiver
bun run preview # local build inspection only
bun audit
```
The lockfile pins dependencies. Review dependency updates and advisories before
publishing a build. Protocol regression tests cover verification gating, malformed
messages, size limits, cancellation, receipt acknowledgment, and relay opt-in.
The browser check requires Chromium at `/usr/bin/chromium` (override with
`CHROMIUM_PATH`); it uses an isolated temporary profile and a loopback server.
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 Google
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.
Browser compatibility, network connectivity and storage availability vary.
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
but Firefox keeps showing the download as in progress until you cancel it.
- **Chromium:** notices a vanished sender only after about 16 seconds.
- An interrupted transfer can't be resumed, it starts over.
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
background. Receiving keeps going.
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
work, and HellCon tells you so.
## License
MIT — see `LICENSE`.
MIT, see [LICENSE](LICENSE).
+47
View File
@@ -0,0 +1,47 @@
# TODO
## Ideas
- Resume interrupted transfers: the receiver already reports how much the download manager has
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
finished or failed download though, so a resume would have to start a new one.
- Keep user settings again: for now every reload starts from the defaults, the server lists and the
own salt too. Open which ones to keep, and how a kept one that differs from the other side's would
show, instead of silently breaking a share.
- Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs
"screen may lock" each time the page is visible again, open whether once per session is enough.
`awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is
still pending, the case the `wakeLock === request` checks in `holdWakeLock` are for.
## Open observations
- A phone can't send in the background: with Brave on Android (Pixel), the connection is lost as
soon as the sender's page goes to the background. Receiving survives it, likely because the
browser's download manager runs as a foreground service while the file streams into it. The wake
lock only keeps the screen from timing out, the sender's page has to stay in front.
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
logs "download failed: connection lost", but the download stays "in progress" until the user
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
complete despite `Content-Length`. Chromium fails the download, but only once the connection
counts as failed (~16 s), because its data channel never fires `close` for a vanished peer.
- Firefox also saves a truncated file as complete when it stops the service worker in the middle of
a download (after 30 s without events). The receiver's pings (`KEEPALIVE`) prevent that, covered by
`large: firefox survives a 40 s stall`. A browser that stops it anyway would still never show
"download complete" or "delivered", only its download manager would be wrong.
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
- Small downloads (empty, one byte) were sometimes never saved, though the worker reported them
finished and both sides logged success: the browser can read the whole response before it hands
the navigation to its download manager, and removing the frame before that cancels it. Without a
delay `boundary: … sends an empty file` failed 8 of 10 runs, the one byte file 4 of 10. The
workaround `DOWNLOAD_GRACE` keeps the download's frame 1 s after finished. No event tells when the
browser took the download, so the 1 s is empirical: `boundary: … keeps a finished download's frame
for DOWNLOAD_GRACE` covers the retention, not the browser's timing. A small download that goes
missing again means it's too short.
+14
View File
@@ -0,0 +1,14 @@
# Copy to .env next to compose.yaml and adjust.
# Where HellCon is served from, as browsers send it in the Origin header: scheme, host and port if not
# the default, no path and no trailing slash. Several separated by commas or spaces. The tracker refuses
# every other origin.
ORIGINS=https://hellcon.example.org
# The external network Caddy is on, "caddy" if unset.
#CADDY_NETWORK=caddy
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs separated by commas or spaces. Every
# private range if unset, see compose.yaml. Narrow it to Caddy's address in CADDY_NETWORK, but keep it
# covered: otherwise all clients count as Caddy's and share its limits, nearly all are refused.
#PROXIES=172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8
+6
View File
@@ -0,0 +1,6 @@
FROM node:26.13.1-alpine3.23
WORKDIR /app
RUN npm install --no-save --omit=dev ws@8.23.0
COPY tracker.mjs .
USER node
CMD ["node", "--max-old-space-size=48", "tracker.mjs"]
+79
View File
@@ -0,0 +1,79 @@
# HellCon's own servers: a tracker behind Caddy and a STUN server. Neither is needed, the client works
# with any WebTorrent tracker and STUN server. Copy .env.example to .env and set ORIGINS there, then
# `docker compose up -d --build`. Caddy, in its own compose
# project, proxies to the tracker over its network (CADDY_NETWORK, "caddy" unless set):
#
# tracker.example.org {
# reverse_proxy hellcon-tracker:8000
# }
name: hellcon
x-logging: &logging
driver: json-file
options: { max-size: 10m, max-file: '2' }
services:
tracker:
build: .
environment:
ORIGINS: ${ORIGINS:?set ORIGINS in .env to where HellCon is served from}
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs, see clientIp in tracker.mjs.
# Caddy reaches it over the shared network, whose subnet is Docker's choice, so the default
# trusts every private range: nothing public should reach the tracker besides Caddy. Set
# PROXIES in .env to narrow it, e.g. to your Caddy's address in that network. If it doesn't
# cover Caddy's address, all clients count as Caddy's and share its limits, nearly all are refused.
PROXIES: ${PROXIES:-172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8}
networks:
caddy:
aliases: [hellcon-tracker]
init: true
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
cpus: 0.5
mem_limit: 96m
memswap_limit: 96m
pids_limit: 32
logging: *logging
restart: unless-stopped
# On the host network, so Docker's NAT can't change the source address clients get back. UDP 3478
# on IPv4 and IPv6, stun.example.org needs an A and an AAAA record. Browsers hide their own addresses,
# only STUN reports an IPv6 one, and mobile networks behind carrier NAT often only connect over IPv6.
coturn:
image: coturn/coturn:4.18.0
network_mode: host
# Off by default since 4.18, their --no- options are gone: DTLS, the admin CLI, the software
# attribute, the RFC 3489 MAPPED-ADDRESS and logging each binding request. The image has no config
# file, -n would only fail with "Unknown argument".
command:
- --log-file=stdout
- --listening-ip=0.0.0.0
- --listening-ip=::
- --listening-port=3478
- --stun-only
- --no-tcp
- --no-tls
# One per CPU core otherwise, more than cpus allows.
- --relay-threads=1
# The pid file lands in /var/tmp, coturn can't write /var/run. The image declares /var/lib/coturn
# a volume, the tmpfs keeps an anonymous one from piling up.
tmpfs: [/var/lib/coturn, /var/tmp]
read_only: true
cap_drop: [ALL]
# turnserver has it as file capability, without it the kernel refuses to run it. 3478 doesn't need
# it, no-new-privileges keeps it from being granted.
cap_add: [NET_BIND_SERVICE]
security_opt: [no-new-privileges:true]
cpus: 1
mem_limit: 128m
memswap_limit: 128m
pids_limit: 64
logging: *logging
restart: unless-stopped
networks:
caddy:
external: true
name: ${CADDY_NETWORK:-caddy}
+351
View File
@@ -0,0 +1,351 @@
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged
// but one warning about PROXIES, without any address.
import { createServer } from 'node:http';
import { BlockList, isIP } from 'node:net';
import { WebSocketServer } from 'ws';
// Read on import, 0 picks a free one, see server.address().
const PORT = Number(process.env.PORT ?? 8000);
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
// connection, so test files sharing one process can each allow their own.
const allowed = (origin) =>
(process.env.ORIGINS ?? '')
.split(/[\s,]+/)
.filter(Boolean)
.includes(origin);
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
// e.g. to a sender that was busy with another receiver.
const INTERVAL = 60;
// A sealed SDP is a few KiB.
const MAX_MESSAGE = 16 * 1024;
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
// gives up a share or a search after 6 minutes.
const MAX_MESSAGES = 10;
const RATE_WINDOW = 10_000;
const MAX_FORWARDED = 64 * 1024;
// A positive number from the environment, read on every use like ORIGINS, so the spec can lower it
// to a testable moment. 0 or a typo would cut every connection short, the default stands then.
const fromEnv = (name, fallback) => {
const value = Number(process.env[name]);
return value > 0 ? value : fallback;
};
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
// a peer that reads never gets near it.
const MAX_QUEUED = 32 * 1024;
// The same for all peers together: MAX_QUEUED for each of MAX_CONNECTIONS would be 32 MiB against
// mem_limit. A quarter of them can still fill theirs.
const maxQueuedAll = () => fromEnv('MAX_QUEUED_ALL', 8 * 1024 * 1024);
const MAX_AGE = 7 * 60_000;
// A connection that announced nothing by then only holds a slot: 1024 of them would serve nobody
// for MAX_AGE.
const maxSilent = () => fromEnv('MAX_SILENT', 30_000);
const MAX_CONNECTIONS = 1024;
const MAX_PER_IP = 16;
// Per address and window, across its connections: MAX_PER_IP is only at once, MAX_FORWARDED only one
// connection, so a client that reconnects would otherwise get a fresh allowance for each. The window
// is long enough for a search to walk the trackers and to reannounce, short enough to cap a relay.
// Relaying through many addresses, e.g. the /64s of one /48, is accepted: other WebTorrent trackers
// relay anything anyway, the caps only keep one address from using this one's bandwidth.
const maxConnectsPerIp = () => fromEnv('MAX_CONNECTS_PER_IP', 120);
const maxForwardedPerIp = () => fromEnv('MAX_FORWARDED_PER_IP', 1024 * 1024);
const IP_WINDOW = 60_000;
// A record without open connections lives until its window is over, a churning client could pile up
// many: past a few thousand, the oldest closed ones go. An address dropping out only forgets its
// rate, the concurrent limit still holds.
const maxIps = () => fromEnv('MAX_IPS', 4 * MAX_CONNECTIONS);
// A share has one sender, receivers keep one connection per tracker.
const MAX_SWARM = 8;
// Offers a sender got and may still answer, the oldest go first.
const MAX_PENDING = 32;
// info_hash → peer_id → peer.
const swarms = new Map();
// address → { open, connects, forwarded, since }, see usage.
const perIp = new Map();
let connections = 0;
// Peers that were sent something and may still have it queued, see fits.
const queued = new Set();
// info_hash, peer_id and offer_id are 20 byte binary strings.
const isId = (value) => typeof value === 'string' && value.length === 20;
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
// Whose X-Forwarded-For to believe, PROXIES' addresses or CIDRs. Read on every connection, like
// ORIGINS. An entry that is none is left out, as is an empty prefix: it would be 0, all of IPv4.
function proxies() {
const list = new BlockList();
for (const entry of (process.env.PROXIES ?? '').split(/[\s,]+/).filter(Boolean)) {
const [base, prefix] = entry.split('/');
const type = { 4: 'ipv4', 6: 'ipv6' }[isIP(base)];
if (!type) continue;
if (prefix === undefined) list.addAddress(base, type);
else if (/^\d+$/.test(prefix) && prefix <= (type === 'ipv4' ? 32 : 128)) list.addSubnet(base, Number(prefix), type);
}
return list;
}
// Once: behind a proxy PROXIES doesn't cover, every client counts as the proxy and shares its limits.
let warned = false;
// The client's address for the per-IP limits. A client that reaches the tracker directly names any
// address it likes in X-Forwarded-For, so without a listed proxy only the socket's own counts. Behind
// a listed proxy, like Caddy on the compose file's network, the last entry is the client's, whatever
// the client put before it. IPv6 counts by /64: a single host usually has a whole one, every address
// in it would get an allowance of its own. IPv4, also mapped to IPv6, counts as it is.
function clientIp(req) {
const peer = req.socket.remoteAddress;
const header = req.headers['x-forwarded-for'];
// BlockList matches IPv4 rules against IPv4-mapped addresses too.
const trusted = isIP(peer) && proxies().check(peer, isIP(peer) === 4 ? 'ipv4' : 'ipv6');
if (header && !trusted && !warned) {
warned = true;
console.warn('X-Forwarded-For from an address PROXIES does not cover, ignored. Behind a proxy, add it.');
}
const forwarded = trusted ? header?.split(',').at(-1).trim() : undefined;
const ip = isIP(forwarded) ? forwarded : peer;
if (!isIP(ip)) return 'unknown';
if (ip.includes('.')) return ip.replace(/^::ffff:/i, '');
const [head, tail] = ip.split('::');
const groups = head ? head.split(':') : [];
if (tail !== undefined) {
const rest = tail ? tail.split(':') : [];
groups.push(...Array(Math.max(0, 8 - groups.length - rest.length)).fill('0'), ...rest);
}
return `${groups
.slice(0, 4)
.map((group) => parseInt(group, 16).toString(16))
.join(':')}::/64`;
}
// The address's record for the current window. Open connections stay counted across a reset, what it
// used starts over. A record without open connections is dropped by the sweep once its window is over.
function usage(ip) {
const now = Date.now();
let record = perIp.get(ip);
if (!record) {
// Room for the new one. At most MAX_CONNECTIONS records have an open connection, so with room to
// spare above that there is always a closed one to drop.
const limit = maxIps();
for (const [old, other] of perIp) {
if (perIp.size < limit) break;
if (!other.open) perIp.delete(old);
}
record = { open: 0, connects: 0, forwarded: 0, since: now };
perIp.set(ip, record);
} else if (now - record.since >= IP_WINDOW) {
record.connects = 0;
record.forwarded = 0;
record.since = now;
}
return record;
}
function refuse(socket, status) {
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
}
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
// wait for its close frame. Past maxQueuedAll() for all of them, the largest queues go first: a peer
// that reads has next to nothing queued, so one without a queue never goes for the others'.
function fits(peer, bytes) {
if (peer.ws.readyState !== peer.ws.OPEN) return false;
if (peer.ws.bufferedAmount + bytes > MAX_QUEUED) return drop(peer);
let total = bytes;
for (const other of queued) {
if (other.ws.bufferedAmount) total += other.ws.bufferedAmount;
else queued.delete(other);
}
queued.add(peer);
if (total > maxQueuedAll()) {
for (const other of [...queued].sort((a, b) => b.ws.bufferedAmount - a.ws.bufferedAmount)) {
if (total <= maxQueuedAll() || !other.ws.bufferedAmount) break;
total -= other.ws.bufferedAmount;
drop(other);
}
}
return peer.ws.readyState === peer.ws.OPEN;
}
// Its queue goes with the socket.
function drop(peer) {
peer.ws.terminate();
queued.delete(peer);
return false;
}
function send(peer, message) {
const data = JSON.stringify(message);
if (fits(peer, Buffer.byteLength(data))) peer.ws.send(data);
}
// HellCon shows the reason, the connection closes.
function reject(peer, reason) {
send(peer, { 'failure reason': reason });
peer.ws.close();
}
function forward(from, to, message, sdp) {
from.forwarded += sdp.length;
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
const used = usage(from.ip);
used.forwarded += sdp.length;
if (used.forwarded > maxForwardedPerIp()) return reject(from, 'too much signaling');
send(to, message);
}
function announce(peer, msg) {
const { info_hash: hash, peer_id: id } = msg;
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
if (!peer.id) {
const swarm = swarms.get(hash) ?? new Map();
if (swarm.has(id)) return reject(peer, 'peer_id taken');
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
swarms.set(hash, swarm.set(id, peer));
peer.id = id;
peer.hash = hash;
clearTimeout(peer.silent);
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
if (msg.event === 'stopped') return peer.ws.close();
peer.seeder = msg.left === 0;
const swarm = swarms.get(hash);
if (msg.offers !== undefined) {
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
return reject(peer, 'invalid offer');
}
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
const sender = senders[Math.floor(Math.random() * senders.length)];
if (offer && sender) {
sender.pending.delete(offer.offer_id);
sender.pending.set(offer.offer_id, peer);
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
const { sdp } = offer.offer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
}
}
if (msg.answer !== undefined) {
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
return reject(peer, 'invalid answer');
}
const receiver = peer.pending.get(msg.offer_id);
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
// cost the share.
if (receiver?.id === msg.to_peer_id) {
peer.pending.delete(msg.offer_id);
const { sdp } = msg.answer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
}
}
// complete counts the seeders, HellCon's receiver moves on to its next tracker without one.
if (peer.ws.readyState === peer.ws.OPEN) {
const complete = [...swarm.values()].filter((other) => other.seeder).length;
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash, complete });
}
}
function open(ws, ip) {
const peer = {
ws,
ip,
id: undefined,
hash: undefined,
seeder: false,
pending: new Map(),
forwarded: 0,
messages: 0,
// Terminated, close would keep the slot for ws's 30 s more if the client ignores the close
// frame. A peer that never announced has nothing to say goodbye to.
silent: setTimeout(() => ws.terminate(), maxSilent()),
};
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
const age = setTimeout(() => ws.close(), MAX_AGE);
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
ws.on('error', () => {});
// Pings and pongs count as messages. ws would answer every ping on its own, past the limits.
const counted = () => ++peer.messages <= MAX_MESSAGES || reject(peer, 'too many messages');
ws.on('ping', (data) => counted() && fits(peer, data.length) && ws.pong(data));
ws.on('pong', counted);
ws.on('message', (data, binary) => {
if (!counted()) return;
let msg;
try {
msg = binary ? undefined : JSON.parse(data);
} catch {}
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
announce(peer, msg);
});
ws.on('close', () => {
clearInterval(rate);
clearTimeout(age);
clearTimeout(peer.silent);
queued.delete(peer);
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
peer.pending.clear();
const swarm = swarms.get(peer.hash);
if (swarm?.get(peer.id) !== peer) return;
swarm.delete(peer.id);
if (!swarm.size) swarms.delete(peer.hash);
// Its offers go only to peers of its swarm.
for (const other of swarm.values()) {
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
}
});
}
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
// Plain requests aren't counted below, only upgraded ones are, so Node's own limits keep them from
// piling up, each one's kernel buffers against mem_limit. Node checks headersTimeout and
// requestTimeout every connectionsCheckingInterval, 30 s unless set. headersTimeout starts only once
// something arrived, the idle timeout on every connection covers one that sends nothing, cleared
// for an accepted upgrade: HellCon's peers sit out their announce interval. The 404 closes the
// socket, nothing of it stays for a keep-alive. maxConnections caps all sockets, plain ones
// included: beyond it Node drops new ones without a response, the one place a client gets a bare
// connection error instead of a 503.
export const server = createServer({ connectionsCheckingInterval: 5_000 }, (_, res) =>
res.writeHead(404, { Connection: 'close' }).end(),
);
server.on('connection', (socket) => socket.setTimeout(10_000, () => socket.destroy()));
server.headersTimeout = 10_000;
server.requestTimeout = 30_000;
server.maxHeadersCount = 100;
server.maxConnections = 2 * MAX_CONNECTIONS;
server.on('upgrade', (req, socket, head) => {
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
// client resetting a refused connection would end the process.
socket.on('error', () => {});
const ip = clientIp(req);
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
const used = usage(ip);
if (used.open >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
// Closing a connection doesn't give the address its allowance back.
if (used.connects >= maxConnectsPerIp()) return refuse(socket, '429 Too Many Requests');
// Counted on the socket, so an upgrade that fails is released too.
connections++;
used.open++;
used.connects++;
socket.once('close', () => {
connections--;
used.open--;
});
// A peer sits out its announce interval, the idle timeout is over for it.
socket.setTimeout(0);
wss.handleUpgrade(req, socket, head, (ws) => open(ws, ip));
});
// An address's window only matters while something of it is open or recent. Once its last connection
// is gone and its window over, the record goes: nothing else would ever delete it.
const sweep = setInterval(() => {
const now = Date.now();
for (const [ip, record] of perIp) if (!record.open && now - record.since >= IP_WINDOW) perIp.delete(ip);
}, IP_WINDOW);
sweep.unref();
server.listen(PORT);
+540
View File
@@ -0,0 +1,540 @@
// The tracker on its own, without browsers: what it forwards, what it refuses and what it keeps.
// tracker.mjs runs in the worker on a free port. e2e.spec.ts sends a real file through it.
import { once } from 'node:events';
import { connect as connectTcp } from 'node:net';
import { queryObjects } from 'node:v8';
import { expect, test } from '@playwright/test';
import { WebSocket as ServerSocket } from 'ws';
const ORIGIN = 'https://hellcon.test';
let server;
let url;
// Every connection a test opened, closed after it.
let clients = [];
// Each test connects from its own address, the tracker takes it from X-Forwarded-For. Otherwise
// connections of the previous test, still closing, would count against the per-IP limit.
let ip;
let tests = 0;
test.beforeAll(async () => {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
// The tracker believes this test's X-Forwarded-For like Caddy's.
process.env.PROXIES = '127.0.0.1';
// Reconnecting tests pass the per-address limits on purpose, the ones about them lower them.
process.env.MAX_CONNECTS_PER_IP = '100000';
process.env.MAX_FORWARDED_PER_IP = String(64 * 1024 * 1024);
({ server } = await import('./tracker.mjs'));
if (!server.listening) await once(server, 'listening');
url = `ws://127.0.0.1:${server.address().port}`;
});
// e2e.spec.ts may run next in this worker, with the tracker as it is deployed.
test.afterAll(() => {
delete process.env.PROXIES;
delete process.env.MAX_CONNECTS_PER_IP;
delete process.env.MAX_FORWARDED_PER_IP;
});
test.beforeEach(() => {
ip = `198.51.100.${++tests}`;
});
test.afterEach(async () => {
for (const client of clients) client.ws.close();
await Promise.all(clients.map((client) => client.closed));
clients = [];
});
// fn with the environment variables in vars, undefined for unset, as they were again after it.
async function withEnv(vars, fn) {
const set = (name, value) => {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
};
const was = Object.keys(vars).map((name) => [name, process.env[name]]);
for (const [name, value] of Object.entries(vars)) set(name, value);
try {
return await fn();
} finally {
for (const [name, value] of was) set(name, value);
}
}
const id = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(20)));
const sdp = (type, text = type) => ({ type, sdp: text });
// A connection like HellCon's, without one if the tracker refused it. Its messages queue up in
// messages, closed resolves with the close code.
function open({ origin = ORIGIN, xff = ip } = {}) {
return new Promise((resolve) => {
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': xff } });
const client = { ws, messages: [], closed: once(ws, 'close').then(([event]) => event.code) };
ws.addEventListener('message', ({ data }) => client.messages.push(JSON.parse(data)));
ws.addEventListener('open', () => {
clients.push(client);
resolve(client);
});
ws.addEventListener('error', () => resolve(undefined));
});
}
// Takes the first message that matches, once one came. open queues each before this sees it.
async function take(client, match) {
while (!client.messages.some(match)) await once(client.ws, 'message');
return client.messages.splice(client.messages.findIndex(match), 1)[0];
}
// Announces and waits for the tracker's reply. Whatever it forwarded to this peer before is in
// messages by then, so a test can tell that something was not forwarded.
async function announce(client, fields) {
client.ws.send(JSON.stringify({ action: 'announce', numwant: 0, uploaded: 0, downloaded: 0, ...fields }));
return take(client, (msg) => 'interval' in msg);
}
// Sends raw and expects the tracker to reject it with reason, then close.
async function rejected(client, data, reason) {
client.ws.send(typeof data === 'string' || data instanceof Uint8Array ? data : JSON.stringify(data));
expect((await take(client, (msg) => 'failure reason' in msg))['failure reason']).toBe(reason);
await client.closed;
}
// A swarm with a sender, a receiver and their peer ids.
async function swarm() {
const hash = id();
const sender = { ...(await open()), id: id() };
const receiver = { ...(await open()), id: id() };
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0, event: 'started' });
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, event: 'started' });
return { hash, sender, receiver };
}
// The receiver's offer, as the sender got it.
async function offer({ hash, sender, receiver }, offerId = id()) {
await announce(receiver, {
info_hash: hash,
peer_id: receiver.id,
left: 1,
offers: [{ offer_id: offerId, offer: sdp('offer') }],
});
return take(sender, (msg) => msg.offer);
}
const answer = ({ hash, sender }, to, offerId, text = 'answer') =>
announce(sender, {
info_hash: hash,
peer_id: sender.id,
left: 0,
to_peer_id: to,
offer_id: offerId,
answer: sdp('answer', text),
});
test('refuses connections from other origins', async () => {
expect(await open({ origin: 'https://evil.test' })).toBeUndefined();
expect(await open({ origin: '' })).toBeUndefined();
});
test('acknowledges an announce with the interval and the seeders only', async () => {
const client = await open();
const hash = id();
expect(await announce(client, { info_hash: hash, peer_id: id(), left: 0 })).toEqual({
action: 'announce',
interval: 60,
info_hash: hash,
complete: 1,
});
});
test('counts the seeders of the swarm in complete', async () => {
const hash = id();
const receiver = { ...(await open()), id: id() };
const seeders = async () => (await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1 })).complete;
expect(await seeders()).toBe(0);
// Another swarm's sender doesn't count.
await announce(await open(), { info_hash: id(), peer_id: id(), left: 0 });
const sender = { ...(await open()), id: id() };
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0 });
expect(await seeders()).toBe(1);
// Gone once the tracker saw the connection close, which may be after the client did.
sender.ws.close();
await expect.poll(seeders).toBe(0);
});
test('forwards an offer to the sender only, rebuilt from its checked fields', async () => {
const peers = await swarm();
const other = { ...(await open()), id: id() };
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
const offerId = id();
await announce(peers.receiver, {
info_hash: peers.hash,
peer_id: peers.receiver.id,
left: 1,
offers: [{ offer_id: offerId, offer: { ...sdp('offer'), extra: 1 } }],
extra: 1,
});
expect(await take(peers.sender, (msg) => msg.offer)).toEqual({
action: 'announce',
info_hash: peers.hash,
peer_id: peers.receiver.id,
offer_id: offerId,
offer: sdp('offer'),
});
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
expect(other.messages).toEqual([]);
});
test('forwards an answer once, only to whoever sent the offer', async () => {
const peers = await swarm();
const { offer_id } = await offer(peers);
// Unknown offer, wrong receiver: dropped, and the sender stays connected.
await answer(peers, peers.receiver.id, id());
await answer(peers, id(), offer_id);
await answer(peers, peers.receiver.id, offer_id, 'sealed');
expect(await take(peers.receiver, (msg) => msg.answer)).toEqual({
action: 'announce',
info_hash: peers.hash,
peer_id: peers.sender.id,
offer_id,
answer: sdp('answer', 'sealed'),
});
await answer(peers, peers.receiver.id, offer_id, 'again');
await announce(peers.receiver, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
expect(peers.receiver.messages).toEqual([]);
});
test('drops an answer to a receiver that left', async () => {
const peers = await swarm();
const { offer_id } = await offer(peers);
peers.receiver.ws.close();
await peers.receiver.closed;
// Its peer_id comes back with a new connection, the old offer stays gone.
const again = await open();
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
await answer(peers, peers.receiver.id, offer_id);
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
expect(again.messages).toEqual([]);
});
for (const [name, data, reason] of [
['text that is no JSON', 'nope', 'invalid message'],
['binary messages', new Uint8Array([1]), 'invalid message'],
['scrape', { action: 'scrape', info_hash: id() }, 'invalid announce'],
['a short info_hash', { action: 'announce', info_hash: 'x', peer_id: id() }, 'invalid announce'],
[
'two offers in one announce',
{
action: 'announce',
info_hash: id(),
peer_id: id(),
left: 1,
offers: [1, 2].map(() => ({ offer_id: id(), offer: sdp('offer') })),
},
'invalid offer',
],
[
'an offer that is an answer',
{ action: 'announce', info_hash: id(), peer_id: id(), left: 1, offers: [{ offer_id: id(), offer: sdp('answer') }] },
'invalid offer',
],
[
'an answer without to_peer_id',
{ action: 'announce', info_hash: id(), peer_id: id(), left: 0, offer_id: id(), answer: sdp('answer') },
'invalid answer',
],
]) {
test(`rejects ${name}`, async () => {
await rejected(await open(), data, reason);
});
}
test('rejects a taken peer_id and a second swarm', async () => {
const { hash, sender } = await swarm();
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: sender.id, left: 0 }, 'peer_id taken');
await rejected(
sender,
{ action: 'announce', info_hash: id(), peer_id: sender.id, left: 0 },
'one swarm per connection',
);
});
test('frees a peer_id once its connection closed', async () => {
const { hash, sender } = await swarm();
sender.ws.close();
await sender.closed;
expect(await announce(await open(), { info_hash: hash, peer_id: sender.id, left: 0 })).toBeTruthy();
});
test('closes on a message beyond 16 KiB', async () => {
const client = await open();
client.ws.send('x'.repeat(16 * 1024 + 1));
expect(await client.closed).toBe(1009);
});
test('limits the message rate', async () => {
const client = await open();
const fields = { action: 'announce', info_hash: id(), peer_id: id(), left: 0 };
for (let i = 0; i < 10; i++) client.ws.send(JSON.stringify(fields));
await rejected(client, fields, 'too many messages');
});
test('limits pings like messages, also from a peer that stops reading', async () => {
// ws's client, browsers send no pings. ws used to answer every one, its pongs piled up in the tracker.
const client = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(client, 'close');
const reasons = [];
client.on('message', (data) => reasons.push(JSON.parse(data)['failure reason']));
await once(client, 'open');
client.ping('x');
expect(String((await once(client, 'pong'))[0])).toBe('x');
client._socket.pause();
for (let i = 0; i < 1000; i++) client.ping('x'.repeat(125));
client._socket.resume();
await closed;
expect(reasons).toEqual(['too many messages']);
});
test('limits the signaling forwarded per connection', async () => {
const { hash, receiver } = await swarm();
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
for (let i = 0; i < 4; i++)
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] });
await rejected(
receiver,
{ action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] },
'too much signaling',
);
});
test('limits the signaling from one address across connections', () =>
withEnv({ MAX_FORWARDED_PER_IP: '20' }, async () => {
const { hash, receiver } = await swarm();
const fields = { action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1 };
// Five bytes each, four fit, the fifth is past the limit though the connection's own is far off.
const offer = { offer_id: id(), offer: sdp('offer') };
for (let i = 0; i < 4; i++) await announce(receiver, { ...fields, offers: [offer] });
await rejected(receiver, { ...fields, offers: [offer] }, 'too much signaling');
// A new connection from the same address doesn't get a fresh allowance.
const again = await open();
const second = { action: 'announce', info_hash: hash, peer_id: id(), left: 1 };
await announce(again, second);
await rejected(again, { ...second, offers: [offer] }, 'too much signaling');
}));
test('limits connections from one address over time, not only at once', () =>
withEnv({ MAX_CONNECTS_PER_IP: '3' }, async () => {
for (let i = 0; i < 3; i++) expect(await open()).toBeTruthy();
// Below MAX_PER_IP, and closing them doesn't reset the rate.
const opened = clients.splice(0);
for (const client of opened) client.ws.close();
await Promise.all(opened.map((client) => client.closed));
expect(await open()).toBeUndefined();
}));
test('forgets the oldest address once too many records pile up', () =>
withEnv({ MAX_IPS: '2', MAX_CONNECTS_PER_IP: '1' }, async () => {
const close = async (address) => {
ip = address;
const client = await open();
client.ws.close();
await client.closed;
// The tracker only evicts closed records, let it see the close first.
await new Promise((resolve) => setTimeout(resolve, 50));
};
await close('192.0.2.1');
await close('192.0.2.2');
// The third record pushes the first out, which may connect again; the second stays limited.
await close('192.0.2.3');
ip = '192.0.2.2';
expect(await open()).toBeUndefined();
ip = '192.0.2.1';
expect(await open()).toBeTruthy();
}));
test('drops a peer that stops reading', async () => {
const hash = id();
const slowId = id();
// ws's client, its socket can stop reading. What the tracker sends then piles up in the kernel's
// buffers first, then in the tracker.
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(slow, 'close').then(([code]) => code);
await once(slow, 'open');
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0, numwant: 0 }));
await once(slow, 'message');
slow._socket.pause();
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
// Receivers that reconnect over and over, each within its own limit. The slow sender's peer_id is
// free again once the tracker dropped it.
let dropped = false;
for (let i = 0; i < 1000 && !dropped; i++) {
const receiver = await open();
const fields = { info_hash: hash, peer_id: id(), left: 1 };
for (let j = 0; j < 4; j++) await announce(receiver, { ...fields, offers: [big()] });
receiver.ws.close();
await receiver.closed;
const probe = await open();
probe.ws.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0 }));
dropped = 'interval' in (await take(probe, (msg) => 'interval' in msg || 'failure reason' in msg));
if (!dropped) await probe.closed;
}
expect(dropped).toBe(true);
slow._socket.resume();
// Terminated, without a close frame.
expect(await closed).toBe(1006);
});
test('drops the largest queues once all of them together pass MAX_QUEUED_ALL', async () => {
// The tracker's side of the slow sender's connection: what its socket holds is queued, the kernel's
// buffers are full by then.
let queue;
const track = (_, socket) => (queue = socket);
server.on('upgrade', track);
const hash = id();
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(slow, 'close').then(([code]) => code);
await once(slow, 'open');
server.off('upgrade', track);
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: id(), left: 0, numwant: 0 }));
await once(slow, 'message');
slow._socket.pause();
// Budget lowered first: once the kernel's buffers are full, the next offer leaves a queue, and
// the reply to the receiver right after it is past the budget. Checked later, the kernel could
// have taken the queue in by then. The slow sender's queue goes, the receiver's reply arrives.
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
await withEnv({ MAX_QUEUED_ALL: '1' }, async () => {
for (let i = 0; i < 1000 && !queue.destroyed; i++) {
const receiver = await open();
const fields = { info_hash: hash, peer_id: id(), left: 1 };
for (let j = 0; j < 4 && !queue.destroyed; j++) {
await announce(receiver, { ...fields, offers: [big()] });
// Gone with its first queue, not once it grew to MAX_QUEUED.
expect(queue.destroyed || !queue.writableLength).toBe(true);
}
receiver.ws.close();
await receiver.closed;
}
});
expect(queue.destroyed).toBe(true);
slow._socket.resume();
expect(await closed).toBe(1006);
});
test('limits a swarm to 8 peers', async () => {
const hash = id();
for (let i = 0; i < 8; i++) await announce(await open(), { info_hash: hash, peer_id: id(), left: 1 });
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: id(), left: 1 }, 'swarm full');
});
test('limits connections per IP to 16', async () => {
for (let i = 0; i < 16; i++) expect(await open()).toBeTruthy();
expect(await open()).toBeUndefined();
ip = '198.51.100.250';
expect(await open()).toBeTruthy();
});
test('counts IPv6 by /64, however it is written', async () => {
for (let i = 1; i <= 16; i++) {
ip = [`2001:db8:${tests}::${i.toString(16)}`, `2001:0DB8:${tests}:0:${i}::`][i % 2];
expect(await open()).toBeTruthy();
}
ip = `2001:db8:${tests}:0:ffff:ffff:ffff:ffff`;
expect(await open()).toBeUndefined();
ip = `2001:db8:${tests}:1::1`;
expect(await open()).toBeTruthy();
});
test('ignores X-Forwarded-For without a trusted proxy', () =>
// Without PROXIES the socket's address counts, a client can't hand-pick a fresh one per
// connection. All these come from 127.0.0.1.
withEnv({ PROXIES: undefined }, async () => {
for (let i = 0; i < 16; i++) expect(await open({ xff: `203.0.113.${i + 1}` })).toBeTruthy();
expect(await open({ xff: '203.0.113.250' })).toBeUndefined();
// With the peer trusted again, the forwarded address counts once more. One that is no address
// counts as the peer's, full by now.
process.env.PROXIES = '127.0.0.1';
for (const xff of ['203.0.113.250:1234', '2001:db8::1::1']) expect(await open({ xff })).toBeUndefined();
expect(await open({ xff: '203.0.113.250' })).toBeTruthy();
// Also as a CIDR, however the proxy's address is written. An IPv4 prefix counts in IPv4's 32
// bits, an empty one is no range at all.
for (const proxies of ['10.0.0.0/8', '10.0.0.0/']) {
process.env.PROXIES = proxies;
expect(await open({ xff: '203.0.113.251' })).toBeUndefined();
}
for (const [i, proxies] of ['127.0.0.0/8', '::ffff:127.0.0.0/120'].entries()) {
process.env.PROXIES = proxies;
expect(await open({ xff: `203.0.113.${251 + i}` })).toBeTruthy();
}
}));
// MAX_SILENT lowered only here: the tests holding 16 silent connections would lose the first ones
// on a busy machine.
test('closes a connection that announces nothing', () =>
// One that only holds a slot goes. Terminated, without a close frame it could ignore.
withEnv({ MAX_SILENT: '500' }, async () => {
const client = await open();
expect(await client.closed).toBe(1006);
}));
test('keeps a connection that announced', () =>
// Also past MAX_SILENT, announcing is the first thing a peer does.
withEnv({ MAX_SILENT: '500' }, async () => {
const client = await open();
const fields = { info_hash: id(), peer_id: id(), left: 0 };
await announce(client, fields);
await new Promise((resolve) => setTimeout(resolve, 750));
await announce(client, fields);
}));
test('answers plain HTTP with a 404 and closes the socket', async () => {
const socket = connectTcp(new URL(url).port, '127.0.0.1');
await once(socket, 'connect');
socket.write('GET / HTTP/1.1\r\nHost: x\r\n\r\n');
const [data] = await once(socket, 'data');
expect(String(data)).toContain('404');
// Connection: close, so unlimited sequential 404s on one connection are over.
expect(String(data).toLowerCase()).toContain('connection: close');
await once(socket, 'close');
});
test('survives clients resetting refused connections', async () => {
for (let i = 0; i < 100; i++) {
const socket = connectTcp(new URL(url).port, '127.0.0.1');
await once(socket, 'connect');
socket.write(
'GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\n' +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: https://evil.test\r\n\r\n',
);
socket.resetAndDestroy();
}
// An unhandled error would have ended this worker.
expect(await open()).toBeTruthy();
});
test('keeps no peer that left', async () => {
// The root stays and gets the first offer, then every peer gets the next one's offer and leaves.
// Held offers used to keep all of them alive, through the root.
const hash = id();
const root = { ...(await open()), id: id() };
await announce(root, { info_hash: hash, peer_id: root.id, left: 0 });
let holder = root;
for (let i = 0; i < 50; i++) {
const peer = { ...(await open()), id: id() };
await announce(peer, {
info_hash: hash,
peer_id: peer.id,
left: 1,
offers: [{ offer_id: id(), offer: sdp('offer') }],
});
await take(holder, (msg) => msg.offer);
// The only sender for the next offer.
await announce(peer, { info_hash: hash, peer_id: peer.id, left: 0 });
if (holder === root) await announce(root, { info_hash: hash, peer_id: root.id, left: 1 });
else {
holder.ws.close();
await holder.closed;
}
holder = peer;
}
// queryObjects collects garbage first.
await expect.poll(() => queryObjects(ServerSocket, { format: 'count' })).toBeLessThanOrEqual(2);
});
+78
View File
@@ -0,0 +1,78 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg", "!**/pnpm-lock.yaml"]
},
"formatter": { "indentStyle": "space", "lineWidth": 120 },
"javascript": { "formatter": { "quoteStyle": "single" } },
"css": { "formatter": { "quoteStyle": "single" } },
"yaml": { "formatter": { "quoteStyle": "single" } },
"html": {
"experimentalFullSupportEnabled": true,
"formatter": { "enabled": true, "selfCloseVoidElements": "always" }
},
"linter": {
"rules": {
"preset": "recommended",
"nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" },
"style": {
"noNonNullAssertion": "off",
"noDescendingSpecificity": "off",
"noRestrictedImports": {
"level": "error",
"options": {
"paths": {
"./core": {
"message": "only src/core.test.ts imports this export of src/core.ts",
"importNames": [
"CHUNK_SIZE",
"MAX_BUFFERED",
"WINDOW",
"TRACKER_TIMEOUT",
"MAX_TRACKER_MESSAGE",
"MAX_TRACKER_MESSAGES",
"MESSAGE_WINDOW",
"TRACKER_NOTES",
"CONNECT_TIMEOUT",
"MIN_INTERVAL",
"PBKDF2_ITERATIONS",
"PROOF_TIMEOUT",
"MAX_NAME",
"own",
"live",
"deadline",
"stunChoice",
"parse",
"decode",
"CODE_CHARS",
"SALT_WINDOW",
"CODE_LENGTH",
"trackerSalt",
"newCode",
"codeSalt",
"secrets",
"seal",
"unseal",
"stunHint",
"securityCheck",
"fingerprints",
"prove",
"Handshake",
"sendFile",
"receiveFile",
"trackerSocket",
"noTracker"
]
}
}
}
}
},
"a11y": { "useSemanticElements": "off" }
}
},
"overrides": [
{ "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } }
]
}
-164
View File
@@ -1,164 +0,0 @@
{
"lockfileVersion": 2,
"configVersion": 1,
"workspaces": {
"": {
"name": "hellcon",
"dependencies": {
"vue": "^3.5.43",
},
"devDependencies": {
"@types/node": "^22",
"@vitejs/plugin-vue": "^6.0.9",
"typescript": "~5.9.3",
"vite": "^8",
"vue-tsc": "^3.3.12",
},
},
},
"packages": {
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
"@babel/parser": ["@babel/parser@7.29.9", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA=="],
"@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.13", "", { "os": "android", "cpu": "arm" }, "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.13", "", { "os": "android", "cpu": "arm64" }, "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA=="],
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw=="],
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.13", "", { "os": "freebsd", "cpu": "x64" }, "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ=="],
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.13", "", { "os": "linux", "cpu": "arm" }, "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg=="],
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ=="],
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow=="],
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.13", "", { "os": "linux", "cpu": "ppc64" }, "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig=="],
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.13", "", { "os": "linux", "cpu": "s390x" }, "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw=="],
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.13", "", { "os": "linux", "cpu": "x64" }, "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ=="],
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.13", "", { "os": "linux", "cpu": "x64" }, "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw=="],
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.13", "", { "os": "none", "cpu": "arm64" }, "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw=="],
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ=="],
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.13", "", { "os": "win32", "cpu": "x64" }, "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@types/node": ["@types/node@22.20.5", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA=="],
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@6.0.9", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25" } }, "sha512-rD/MORlhaZMlXWW0rEn4FB4wMinWC0z/D7Ye160S5+Rs1mC8ZDAdcDp4SjKfUhG5t8q1ktcPVw4xuTkPRlzrSA=="],
"@volar/language-core": ["@volar/language-core@2.4.28", "", { "dependencies": { "@volar/source-map": "2.4.28" } }, "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ=="],
"@volar/source-map": ["@volar/source-map@2.4.28", "", {}, "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ=="],
"@volar/typescript": ["@volar/typescript@2.4.28", "", { "dependencies": { "@volar/language-core": "2.4.28", "path-browserify": "^1.0.1", "vscode-uri": "^3.0.8" } }, "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw=="],
"@vue/compiler-core": ["@vue/compiler-core@3.5.43", "", { "dependencies": { "@babel/parser": "^7.29.8", "@vue/shared": "3.5.43", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-zdiLhnbe1QQqgDT8xZMpNmyqZ3qlI+/Q/FHQco57Kwl/b05HhCzN6eVGN9QU9rbga4CrS0H5SYY8VGHZCt/1Hg=="],
"@vue/compiler-dom": ["@vue/compiler-dom@3.5.43", "", { "dependencies": { "@vue/compiler-core": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-PEZoAk3NQmsn/ejMzSOCyTYqwGqczrWm70PuhBKjjv1+TCoQAaO/zOqNwjV+honlNstT5ILxtc+8r8UUfj+iEQ=="],
"@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.43", "", { "dependencies": { "@babel/parser": "^7.29.8", "@vue/compiler-core": "3.5.43", "@vue/compiler-dom": "3.5.43", "@vue/compiler-ssr": "3.5.43", "@vue/shared": "3.5.43", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", "postcss": "^8.5.28", "source-map-js": "^1.2.1" } }, "sha512-FCbrG3XNCRl+js3huuKx4IVHBLTvMkJhVepjbxSPu1gn4yWLaYtGNQdjJGZaMytXB6qb76qQDDmDSLy/vkmleQ=="],
"@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.43", "", { "dependencies": { "@vue/compiler-dom": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-GF62orf7KiJX9RqrHNGrYBudsQGD0OhJ5nDs90O8UiDuS40+YMYomiXu6w6EuvtXuRDc3MSNis3EaaSKAVSWpg=="],
"@vue/language-core": ["@vue/language-core@3.3.12", "", { "dependencies": { "@volar/language-core": "2.4.28", "@vue/compiler-dom": "^3.5.0", "@vue/shared": "^3.5.0", "alien-signals": "^3.2.1", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1", "picomatch": "^4.0.4" } }, "sha512-k7uIKR0n4CBidk233y7cac9osnDQ5WRidTl6nsrNvpZ3nf8cx9iJxRVsRzVsoPRHbowT/iKgGMTS9RGov3jeIA=="],
"@vue/reactivity": ["@vue/reactivity@3.5.43", "", { "dependencies": { "@vue/shared": "3.5.43" } }, "sha512-G/c9GyOZNI2jVaaS6OX1EF1SSFSv7H0ERqNTl4+DTFMlZmB5eVAB53aLQNam/7NL2NPtaDD7RdVrzf8uJzMuOA=="],
"@vue/runtime-core": ["@vue/runtime-core@3.5.43", "", { "dependencies": { "@vue/reactivity": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-hU6U6VnVhBGQDpvlnnDlIB8ZGJBiOcgk2lh/0InltHiz3D8oSkluvuvY+do1G2H3+udeKFsmaBlgVYP7gXQzEw=="],
"@vue/runtime-dom": ["@vue/runtime-dom@3.5.43", "", { "dependencies": { "@vue/reactivity": "3.5.43", "@vue/runtime-core": "3.5.43", "@vue/shared": "3.5.43", "csstype": "^3.2.3" } }, "sha512-Bb2Jc0YjjJdMt1SJmb9b2L/IWd3I8lIT9x9eS/xvvP9CiVgna0ffua74xKRmt4/uSJ+0r4iN8ex1jrqkhQGWQw=="],
"@vue/server-renderer": ["@vue/server-renderer@3.5.43", "", { "dependencies": { "@vue/compiler-ssr": "3.5.43", "@vue/runtime-dom": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-l2Ygjv9NehV94PSBxNWsAHC0j/eIIKbn92mBuWXAPGLnn6HfJ6MH5ubsd+Nk0YoZ5FRuxWI1P2VSoh+dbPQhCQ=="],
"@vue/shared": ["@vue/shared@3.5.43", "", {}, "sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q=="],
"alien-signals": ["alien-signals@3.2.1", "", {}, "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g=="],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
"lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
"lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
"lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
"lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
"lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
"lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
"lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
"lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
"lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="],
"nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
"path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
"postcss": ["postcss@8.5.29", "", { "dependencies": { "nanoid": "^3.3.19", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ=="],
"rolldown": ["rolldown@1.2.13", "", { "dependencies": { "@oxc-project/types": "=0.153.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.13", "@rolldown/binding-android-arm64": "1.2.13", "@rolldown/binding-darwin-arm64": "1.2.13", "@rolldown/binding-darwin-x64": "1.2.13", "@rolldown/binding-freebsd-x64": "1.2.13", "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", "@rolldown/binding-linux-arm64-gnu": "1.2.13", "@rolldown/binding-linux-arm64-musl": "1.2.13", "@rolldown/binding-linux-ppc64-gnu": "1.2.13", "@rolldown/binding-linux-s390x-gnu": "1.2.13", "@rolldown/binding-linux-x64-gnu": "1.2.13", "@rolldown/binding-linux-x64-musl": "1.2.13", "@rolldown/binding-openharmony-arm64": "1.2.13", "@rolldown/binding-win32-arm64-msvc": "1.2.13", "@rolldown/binding-win32-x64-msvc": "1.2.13" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ=="],
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"vite": ["vite@8.3.4", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.29", "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ=="],
"vscode-uri": ["vscode-uri@3.2.0", "", {}, "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg=="],
"vue": ["vue@3.5.43", "", { "dependencies": { "@vue/compiler-dom": "3.5.43", "@vue/compiler-sfc": "3.5.43", "@vue/runtime-dom": "3.5.43", "@vue/server-renderer": "3.5.43", "@vue/shared": "3.5.43" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-o5qZoksdnjIKvW1srZ3ab7pcDNYAerBjRe54D0LBLfRdCYFrSgBHVXokMas35czQc0//lmx4/tuY4ZNQ+Rf2Ng=="],
"vue-tsc": ["vue-tsc@3.3.12", "", { "dependencies": { "@volar/typescript": "2.4.28", "@vue/language-core": "3.3.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "bin/vue-tsc.js" } }, "sha512-kbpaz18O9jPVkXVHD1BEjpUXM6WhXSu+62L1sGGr6Wbzd8GbvkBQWjoj3KZ/C0aq2MZllce7UdtWzwCIYsBMGA=="],
}
}
-33
View File
@@ -1,33 +0,0 @@
# Linux development only. No boot startup or automatic container restart.
services:
coturn:
image: coturn/coturn:4.18.0-r0-alpine
network_mode: host
restart: "no"
command:
- -n
- --listening-ip=127.0.0.1
- --relay-ip=127.0.0.1
- --listening-port=${TURN_PORT:-3478}
- --realm=hellcon.local
- --use-auth-secret
- --static-auth-secret=${TURN_SECRET:?Run bun run dev:setup first}
- --fingerprint
- --min-port=49160
- --max-port=49200
- --no-tls
# DTLS is opt-in in coturn 4.18; leave it disabled.
- --no-tcp-relay
- --no-multicast-peers
# Needed for two browsers relaying to each other on this machine.
- --allow-loopback-peers
- --no-cli
- --no-software-attribute
- --log-file=stdout
tmpfs:
- /var/lib/coturn
logging:
driver: json-file
options:
max-size: "5m"
max-file: "2"
-35
View File
@@ -1,35 +0,0 @@
import type { IncomingMessage } from 'node:http';
import { createHmac, randomUUID } from 'node:crypto';
interface IceResponse {
setHeader(name: string, value: string): unknown;
writeHead(status: number, headers?: Record<string, string>): unknown;
end(body?: string): unknown;
}
// Shared by Vite and the browser integration checks. Never imported by the client.
export function iceMiddleware(env: NodeJS.ProcessEnv) {
const secret = env.TURN_SECRET;
if (!secret) throw new Error('TURN_SECRET is required. Run bun run dev:setup first.');
const host = env.TURN_HOST || '127.0.0.1';
const port = env.TURN_PORT || '3478';
return (req: Pick<IncomingMessage, 'url' | 'method' | 'headers'>, res: IceResponse, next: () => void) => {
if (req.url?.split('?')[0] !== '/api/ice-servers') return next();
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.writeHead(405, { Allow: 'GET' }); res.end(); return;
}
if (req.headers['sec-fetch-site'] === 'cross-site' ||
(req.headers.origin && req.headers.origin !== `http://${req.headers.host}`)) {
res.writeHead(403); res.end(); return;
}
const expiresAt = Math.floor(Date.now() / 1000) + 3600;
const username = `${expiresAt}:${randomUUID()}`;
const credential = createHmac('sha1', secret).update(username).digest('base64');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ expiresAt, iceServers: [
{ urls: `stun:${host}:${port}` },
{ urls: [`turn:${host}:${port}?transport=udp`, `turn:${host}:${port}?transport=tcp`], username, credential },
] }));
};
}
+1482
View File
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -5,8 +5,13 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="referrer" content="no-referrer" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; style-src 'self'; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'none'; form-action 'none'"
/>
<link rel="icon" type="image/png" href="./HellNet_alt.png" />
<title>HellCon — P2P File Share</title>
<title>HellCon</title>
</head>
<body>
<div id="app"></div>
+23 -18
View File
@@ -1,33 +1,38 @@
{
"name": "hellcon",
"private": true,
"version": "0.0.1",
"version": "1.0.2",
"license": "MIT",
"type": "module",
"scripts": {
"dev": "vite",
"dev:setup": "node scripts/dev-setup.ts",
"turn:up": "docker compose --env-file .env.development up -d",
"turn:down": "docker compose --env-file .env.development down",
"test:turn": "node scripts/browser-check.ts --turn",
"build": "vue-tsc --noEmit && vite build",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test": "node --test tests/*.test.ts",
"test:browser": "node scripts/browser-check.ts",
"test:cross-browser": "node scripts/cross-browser-check.ts",
"typecheck": "vue-tsc --noEmit"
"typecheck": "vue-tsc",
"lint": "biome check",
"format": "biome check --write",
"test": "vitest run && playwright test",
"test:unit": "vitest",
"test:e2e": "playwright test",
"test:install": "playwright install chromium firefox",
"test:large": "LARGE=1 playwright test -g large"
},
"dependencies": {
"vue": "^3.5.43"
"vue": "^3.5.45"
},
"devDependencies": {
"@types/node": "^22",
"@vitejs/plugin-vue": "^6.0.9",
"typescript": "~5.9.3",
"vite": "^8",
"vue-tsc": "^3.3.12"
"@biomejs/biome": "2.6.3",
"@playwright/test": "^1.65.0",
"@types/node": "^26.6.6",
"@vitejs/plugin-vue": "^6.0.11",
"typescript": "~6.0.3",
"vite": "^8.3.8",
"vitest": "^5.1.0",
"vue-tsc": "^3.3.14",
"ws": "8.23.0"
},
"engines": {
"node": ">=22.18.0"
}
"node": ">=26.13.1"
},
"packageManager": "pnpm@12.16.1"
}
+4
View File
@@ -0,0 +1,4 @@
import { defineConfig } from '@playwright/test';
// src/core.test.ts is Vitest's, see vite.config.ts. Loaded by Playwright, its vi.mock fails the whole run.
export default defineConfig({ testIgnore: 'src/**' });
+1382
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
minimumReleaseAgeExclude:
- ws@8.23.0
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="main_outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 640 640" style="enable-background:new 0 0 640 640;" xml:space="preserve">
<g>
<path id="teabag" style="fill:#FFFFFF" d="M395.9,484.2l-126.9-61c-12.5-6-17.9-21.2-11.8-33.8l61-126.9c6-12.5,21.2-17.9,33.8-11.8
c17.2,8.3,27.1,13,27.1,13l-0.1-109.2l16.7-0.1l0.1,117.1c0,0,57.4,24.2,83.1,40.1c3.7,2.3,10.2,6.8,12.9,14.4
c2.1,6.1,2,13.1-1,19.3l-61,126.9C423.6,484.9,408.4,490.3,395.9,484.2z"/>
<g>
<g>
<path style="fill:#609926" d="M622.7,149.8c-4.1-4.1-9.6-4-9.6-4s-117.2,6.6-177.9,8c-13.3,0.3-26.5,0.6-39.6,0.7c0,39.1,0,78.2,0,117.2
c-5.5-2.6-11.1-5.3-16.6-7.9c0-36.4-0.1-109.2-0.1-109.2c-29,0.4-89.2-2.2-89.2-2.2s-141.4-7.1-156.8-8.5
c-9.8-0.6-22.5-2.1-39,1.5c-8.7,1.8-33.5,7.4-53.8,26.9C-4.9,212.4,6.6,276.2,8,285.8c1.7,11.7,6.9,44.2,31.7,72.5
c45.8,56.1,144.4,54.8,144.4,54.8s12.1,28.9,30.6,55.5c25,33.1,50.7,58.9,75.7,62c63,0,188.9-0.1,188.9-0.1s12,0.1,28.3-10.3
c14-8.5,26.5-23.4,26.5-23.4s12.9-13.8,30.9-45.3c5.5-9.7,10.1-19.1,14.1-28c0,0,55.2-117.1,55.2-231.1
C633.2,157.9,624.7,151.8,622.7,149.8z M125.6,353.9c-25.9-8.5-36.9-18.7-36.9-18.7S69.6,321.8,60,295.4
c-16.5-44.2-1.4-71.2-1.4-71.2s8.4-22.5,38.5-30c13.8-3.7,31-3.1,31-3.1s7.1,59.4,15.7,94.2c7.2,29.2,24.8,77.7,24.8,77.7
S142.5,359.9,125.6,353.9z M425.9,461.5c0,0-6.1,14.5-19.6,15.4c-5.8,0.4-10.3-1.2-10.3-1.2s-0.3-0.1-5.3-2.1l-112.9-55
c0,0-10.9-5.7-12.8-15.6c-2.2-8.1,2.7-18.1,2.7-18.1L322,273c0,0,4.8-9.7,12.2-13c0.6-0.3,2.3-1,4.5-1.5c8.1-2.1,18,2.8,18,2.8
l110.7,53.7c0,0,12.6,5.7,15.3,16.2c1.9,7.4-0.5,14-1.8,17.2C474.6,363.8,425.9,461.5,425.9,461.5z"/>
<path style="fill:#609926" d="M326.8,380.1c-8.2,0.1-15.4,5.8-17.3,13.8c-1.9,8,2,16.3,9.1,20c7.7,4,17.5,1.8,22.7-5.4
c5.1-7.1,4.3-16.9-1.8-23.1l24-49.1c1.5,0.1,3.7,0.2,6.2-0.5c4.1-0.9,7.1-3.6,7.1-3.6c4.2,1.8,8.6,3.8,13.2,6.1
c4.8,2.4,9.3,4.9,13.4,7.3c0.9,0.5,1.8,1.1,2.8,1.9c1.6,1.3,3.4,3.1,4.7,5.5c1.9,5.5-1.9,14.9-1.9,14.9
c-2.3,7.6-18.4,40.6-18.4,40.6c-8.1-0.2-15.3,5-17.7,12.5c-2.6,8.1,1.1,17.3,8.9,21.3c7.8,4,17.4,1.7,22.5-5.3
c5-6.8,4.6-16.3-1.1-22.6c1.9-3.7,3.7-7.4,5.6-11.3c5-10.4,13.5-30.4,13.5-30.4c0.9-1.7,5.7-10.3,2.7-21.3
c-2.5-11.4-12.6-16.7-12.6-16.7c-12.2-7.9-29.2-15.2-29.2-15.2s0-4.1-1.1-7.1c-1.1-3.1-2.8-5.1-3.9-6.3c4.7-9.7,9.4-19.3,14.1-29
c-4.1-2-8.1-4-12.2-6.1c-4.8,9.8-9.7,19.7-14.5,29.5c-6.7-0.1-12.9,3.5-16.1,9.4c-3.4,6.3-2.7,14.1,1.9,19.8
C343.2,346.5,335,363.3,326.8,380.1z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+113
View File
@@ -0,0 +1,113 @@
// Streams received files into the browser's download manager. It is the only script besides the app
// because service workers can only be registered from a same-origin script URL. Registered with the
// scope download/ by src/download.ts, its counterpart in the page, it sees no other requests.
// Of the messages with the page, see VERSION in src/download.ts.
const VERSION = 1;
// Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the
// reply port and how many bytes the download manager has read.
const downloads = new Map();
// Responses by download id, until the download navigation fetches them. Each is served only once.
const responses = new Map();
// The page pings every KEEPALIVE while a transfer stalls, see src/download.ts. Silent for this long,
// it is gone, e.g. its tab was closed: Firefox would stop this worker 30 s after the last event and
// save the truncated file as complete. A failed stream leaves the download failed instead. A page
// that is still there, only late, e.g. throttled in the background, is told with silent.
const SILENCE = 20_000;
function watch(id, download) {
clearTimeout(download.watchdog);
download.watchdog = setTimeout(() => {
download.controller.error(new Error('the page is gone'));
forget(id);
download.port.postMessage('silent');
}, SILENCE);
}
function forget(id) {
clearTimeout(downloads.get(id)?.watchdog);
downloads.delete(id);
}
function open(id, { version, name, size }, port) {
if (version !== VERSION) return port.postMessage('outdated');
// The page checks the sender's offer already. Anything else would throw below or lie to the browser.
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
const body = new ReadableStream(
{
start: (controller) => (download.controller = controller),
// With highWaterMark 0 the download manager pulls only when it wants more, so reaching the end
// marker here means it has read every byte.
async pull(controller) {
while (!download.chunks.length) await new Promise((resolve) => (download.wake = resolve));
const chunk = download.chunks.shift();
if (chunk) {
download.read += chunk.byteLength;
// Every MiB, the receiver forwards it to the sender for its flow control window.
if (download.read - download.reported >= 2 ** 20) {
download.reported = download.read;
port.postMessage(download.read);
}
return controller.enqueue(chunk);
}
controller.close();
forget(id);
port.postMessage('finished');
},
// The user cancelled the download.
cancel: () => {
forget(id);
port.postMessage('cancelled');
},
},
{ highWaterMark: 0 },
);
downloads.set(id, download);
watch(id, download);
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
const encoded = encodeURIComponent(name.toWellFormed()).replace(
/['()*]/g,
(char) => `%${char.charCodeAt(0).toString(16)}`,
);
const headers = {
'Content-Type': 'application/octet-stream',
'Content-Length': String(size),
'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
};
responses.set(id, new Response(body, { headers }));
port.postMessage('ready');
}
// The page posts its version and the metadata with a reply port first, then every chunk as its own
// message and finally done (queued as the end marker null) or an error. Pings come in between.
self.addEventListener('message', ({ data, ports: [port] }) => {
if (port) return open(data.id, data, port);
const download = downloads.get(data.id);
if (!download) return;
watch(data.id, download);
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/download.ts.
if (data.ping) return;
if (data.error) {
download.controller.error(new Error(data.error));
forget(data.id);
download.port.postMessage('failed');
} else {
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
download.wake();
}
});
self.addEventListener('fetch', (event) => {
const id = new URL(event.request.url).pathname.split('/').pop();
// download/ itself is the empty page src/download.ts keeps open to hold this worker during a transfer.
if (!id)
return event.respondWith(
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
);
const response = responses.get(id);
responses.delete(id);
event.respondWith(response ?? new Response('download expired', { status: 404 }));
});
-189
View File
@@ -1,189 +0,0 @@
// Dependency-free Chromium integration check. Run after `bun run build`.
import { Readable, Writable } from 'node:stream';
import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
const turn = process.argv.includes('--turn');
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null;
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
const server = createServer(async (req, res) => {
if (vite) return vite.middlewares(req, res);
try {
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
const base = join(root, 'dist');
const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname));
if (!path.startsWith(base + '/')) throw new Error('Invalid path');
const types: Record<string, string> = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png' };
res.setHeader('Content-Type', types[extname(path)] || 'application/octet-stream');
res.end(await readFile(path));
} catch { res.statusCode = 404; res.end(); }
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
assert.ok(address && typeof address !== 'string');
const origin = `http://127.0.0.1:${address.port}`;
const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [
'--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking',
'--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
interface ProtocolResults {
'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string };
'Runtime.enable': object;
'Page.enable': object;
'Page.navigate': object;
'Page.addScriptToEvaluateOnNewDocument': object;
'Runtime.evaluate': { exceptionDetails?: unknown; result: { value?: unknown } };
}
interface ProtocolMessage {
id?: number;
method?: string;
params?: { exceptionDetails?: unknown };
error?: unknown;
result?: unknown;
}
const pipeIn = browser.stdio[3], pipeOut = browser.stdio[4];
assert.ok(pipeIn instanceof Writable && pipeOut instanceof Readable && browser.stderr);
const commandPipe = pipeIn;
let stderr = '', nextId = 0, buffer = '';
const pending = new Map<number, (message: ProtocolMessage) => void>();
const browserErrors: unknown[] = [];
browser.stderr.on('data', data => { stderr += data; });
pipeIn.on('error', () => {}); pipeOut.on('error', () => {});
pipeOut.on('data', data => {
buffer += data;
let end;
while ((end = buffer.indexOf('\0')) !== -1) {
const message: ProtocolMessage = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
if (message.method === 'Runtime.exceptionThrown') browserErrors.push(message.params?.exceptionDetails);
}
});
function call<M extends keyof ProtocolResults>(method: M, params: Record<string, unknown> = {}, sessionId?: string): Promise<ProtocolResults[M]> {
return new Promise((resolve, reject) => {
const id = ++nextId;
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timed out: ${method}\n${stderr.slice(-1500)}`)); }, 45000);
pending.set(id, message => { clearTimeout(timer); message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result as ProtocolResults[M]); });
commandPipe.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
});
}
async function evaluate<T, Args extends unknown[]>(session: string, fn: (...args: Args) => T, ...args: Args): Promise<Awaited<T>> {
const expression = `(${fn.toString()})(...${JSON.stringify(args)})`;
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
// CDP returns the serialized result of this exact callback.
return result.result.value as Awaited<T>;
}
async function wait(session: string, check: () => unknown) {
const expression = `window.__hellcon.wait(${check.toString()})`;
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
}
async function page() {
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId);
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url: origin }, sessionId);
for (let n = 0; n < 100; n++) {
try { if (await evaluate(sessionId, (expected: string) => location.origin === expected && document.readyState === 'complete', origin)) break; }
catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20));
}
await wait(sessionId, () => !!document.querySelector('#stun-provider'));
return sessionId;
}
const click = (session: string, label: string) => evaluate(session, (label: string) => window.__hellcon.click(label), label);
const input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value);
const enableTurn = (session: string) => evaluate(session, () => {
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
if (!checkbox.checked) checkbox.click();
});
async function connect(sender: string, receiver: string, size: number) {
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
await input(sender, '#stun-provider', provider);
await input(receiver, '#stun-provider', provider);
if (turn) { await enableTurn(sender); await enableTurn(receiver); }
await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(receiver, '#offer-input', 'invalid-code!');
await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('[role=alert]'));
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').disabled), false);
if (turn) await enableTurn(receiver);
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect');
await wait(sender, () => !!document.querySelector('[role=alert]'));
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer);
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false);
await input(sender, '#answer-input', answer); await click(sender, 'Connect');
await wait(sender, () => !!document.querySelector('.fingerprint'));
const sf = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
const rf = await evaluate(receiver, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0]?.split(' ').length, 32);
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
await click(sender, 'Both fingerprints match — confirm');
await new Promise(resolve => setTimeout(resolve, 100));
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
await click(receiver, 'Both fingerprints match — confirm');
await wait(receiver, () => !!document.querySelector('.incoming'));
if (turn) {
for (const session of [sender, receiver]) {
const types = await evaluate(session, relayCandidateTypes);
assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates');
}
}
}
try {
const sender = await page(), receiver = await page();
await click(receiver, 'Receive');
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.checkbox input').checked), false);
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
const data = await evaluate(receiver, async () => {
const response = await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href);
const bytes = new Uint8Array(await response.arrayBuffer());
return { length: bytes.length, valid: bytes.every(b => b === 123) };
});
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
await click(sender, 'Reset'); await click(receiver, 'Reset');
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.');
assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.');
console.log('PASS: Reset restores the ready state on both sides.');
await evaluate(receiver, simulateSlowDisk);
await connect(sender, receiver, 2 * 1024 * 1024);
await click(receiver, 'Choose destination & receive to disk');
await wait(receiver, () => !!window.__hellcon.releaseWrite);
await click(sender, 'Receive');
await wait(receiver, () => window.__hellcon.aborted);
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
await click(sender, 'Send'); await click(receiver, 'Reset');
await connect(sender, receiver, 2048);
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
assert.deepEqual(browserErrors, []);
} finally {
browser.kill();
await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
await vite?.close();
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
}
-103
View File
@@ -1,103 +0,0 @@
// These functions are serialized into isolated browser pages by the checks.
// Keep their dependencies inside the function or on window.__hellcon.
export function installBrowserContext() {
function element<E extends Element>(selector: string): E {
const value = document.querySelector<E>(selector);
if (!value) throw new Error(`Missing element: ${selector}`);
return value;
}
const context = {
element,
peers: [] as RTCPeerConnection[],
aborted: false,
releaseWrite: undefined as (() => void) | undefined,
click(label: string) {
const button = [...document.querySelectorAll('button')].find(button => button.textContent?.trim() === label);
if (!button || button.disabled) throw new Error(`Unavailable button: ${label}`);
button.click();
},
input(selector: string, value: string) {
const input = element<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(selector);
input.value = value;
input.dispatchEvent(new Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
},
chooseFile(size: number, name: string) {
const input = element<HTMLInputElement>('#file-input');
const files = new DataTransfer();
files.items.add(new File([new Uint8Array(size).fill(123)], name));
input.files = files.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
},
async wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>> {
const deadline = Date.now() + 36000;
while (Date.now() < deadline) {
const value = await check();
if (value) return value;
await new Promise<void>(resolve => setTimeout(resolve, 20));
}
throw new Error('UI condition timed out: ' + document.body.innerText);
},
};
window.__hellcon = context;
}
declare global {
interface Window {
__hellcon: {
element<E extends Element>(selector: string): E;
peers: RTCPeerConnection[];
aborted: boolean;
releaseWrite?: () => void;
click(label: string): void;
input(selector: string, value: string): void;
chooseFile(size: number, name: string): void;
wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>>;
};
}
}
export function forceRelay(transport: 'udp' | 'tcp') {
const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC {
constructor(config?: RTCConfiguration) {
super({ ...config, iceTransportPolicy: 'relay' });
window.__hellcon.peers.push(this);
}
override setConfiguration(config: RTCConfiguration) {
const iceServers = (config.iceServers ?? []).filter(server => server.username).map(server => ({
...server,
urls: (Array.isArray(server.urls) ? server.urls : [server.urls]).filter(url => url.endsWith(`transport=${transport}`)),
}));
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
}
};
}
export async function relayCandidateTypes() {
for (let attempt = 0; attempt < 50; attempt++) {
const pc = window.__hellcon.peers.at(-1);
if (!pc) throw new Error('No peer connection');
const stats = await pc.getStats();
const transport = [...stats.values()].find((entry: RTCStats) => entry.type === 'transport') as RTCTransportStats | undefined;
const pair = transport?.selectedCandidatePairId ? stats.get(transport.selectedCandidatePairId) as RTCIceCandidatePairStats | undefined : undefined;
if (pair) {
const local = stats.get(pair.localCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
const remote = stats.get(pair.remoteCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
return [local?.candidateType, remote?.candidateType];
}
await new Promise<void>(resolve => setTimeout(resolve, 100));
}
throw new Error('No selected ICE candidate pair in WebRTC statistics');
}
export function simulateSlowDisk() {
window.__hellcon.aborted = false;
// Only the methods used by the app are implemented by this browser test double.
window.showSaveFilePicker = async () => ({
createWritable: async () => ({
write() { return new Promise<void>(resolve => { window.__hellcon.releaseWrite = resolve; }); },
async close() {},
async abort() { window.__hellcon.aborted = true; window.__hellcon.releaseWrite?.(); },
}),
});
}
-72
View File
@@ -1,72 +0,0 @@
// Exercises the built Vue app in separate Brave and Firefox processes.
import { installBrowserContext } from './browser-context.ts';
import { crossBrowserDriver } from './cross-browser-driver.ts';
import { isRecord } from '../src/lib/validation.ts';
import { createServer } from 'node:http';
import { spawn, type ChildProcess } from 'node:child_process';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';
const types: Record<string, string> = {'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'};
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const state: Record<string, unknown> = {};
const profiles: string[] = [];
const children: ChildProcess[] = [];
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
const reversed = process.argv.includes('--reverse');
const driver = `(${installBrowserContext.toString()})(); (${crossBrowserDriver.toString()})(${JSON.stringify(provider)});`;
let finish: () => void = () => {};
const result = new Promise<void>(resolve => { finish = resolve; });
const server = createServer(async (req,res) => {
try {
const pathname=new URL(req.url ?? '/','http://localhost').pathname;
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
if(pathname.startsWith('/.test/')){
const key=pathname.slice('/.test/'.length);
if(req.method==='POST'){
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
const previous=state[key];
state[key]=JSON.parse(body);
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
if(key.endsWith('Result')){
console.log(key+': '+JSON.stringify(state[key]));
if(!isRecord(state[key]) || !state[key].ok ||(state.senderResult&&state.receiverResult))finish();
}
}
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
}
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
let body: string | Buffer = await readFile(path);
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
res.setHeader('Content-Type',types[extname(path)]||'application/octet-stream');res.end(body);
}catch{res.statusCode=404;res.end();}
});
await new Promise<void>(resolve=>server.listen(0,'127.0.0.1',resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Missing server address');
const origin='http://127.0.0.1:'+address.port;
let timer: ReturnType<typeof setTimeout> | undefined;
try{
for(const name of ['brave','firefox']){
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
const role=(name==='brave')!==reversed?'sender':'receiver';
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
child.on('error',err=>{console.error(name,err.message);finish();});
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
}
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
await result;
if(!isRecord(state.senderResult) || !state.senderResult.ok || !isRecord(state.receiverResult) || !state.receiverResult.ok)process.exitCode=1;
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
}finally{
clearTimeout(timer);
for(const child of children)child.kill();
await Promise.all(children.map(child=>new Promise<void>(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit', () => resolve());})));
server.closeAllConnections();await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
}
-61
View File
@@ -1,61 +0,0 @@
import type {} from './browser-context.ts';
interface Exchange {
offer: string;
answer: string;
senderFingerprints: string[];
receiverFingerprints: string[];
senderResult: { ok: boolean };
}
// Serialized by the runner; all runtime dependencies live in this function or window.
export async function crossBrowserDriver(provider: string) {
const role = new URL(location.href).searchParams.get('role');
if (role !== 'sender' && role !== 'receiver') throw new Error('Invalid role');
const { click, input, wait, element } = window.__hellcon;
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
const post = async (key: string, value: unknown) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
const get = async <K extends keyof Exchange>(key: K): Promise<Exchange[K] | null> => (await fetch('/.test/' + key)).json();
const stage = async (text: string) => post(role+'Stage', text);
const peers: RTCPeerConnection[] = []; const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC { constructor(config?: RTCConfiguration) { super(config); peers.push(this); } };
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
try {
await wait(()=>document.querySelector('#stun-provider'));
if(role==='receiver'){click('Receive');await pause(20);}
if(role==='sender'){
window.__hellcon.chooseFile(2*1024*1024+7, 'cross-browser.bin'); await pause(20);
}
input('#stun-provider',provider);await pause(20);
if(role==='sender'){
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
await post('offer',element<HTMLTextAreaElement>('#output-code').value);
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
}else{
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
await post('answer',element<HTMLTextAreaElement>('#output-code').value);
}
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
await post(role+'Fingerprints',fps);
const other=await wait(()=>get(role === 'sender' ? 'receiverFingerprints' : 'senderFingerprints'));
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
click('Both fingerprints match — confirm');
if(role==='receiver'){
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
await stage('receiving');await wait(()=>document.querySelector('a.download'));
await wait(()=>get('senderResult'));
await pause(250);
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
await stage('checking downloaded bytes');
const bytes=new Uint8Array(await (await fetch(element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
}else{
await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file'));
}
await post(role+'Result',{ok:true});
}catch(error){
await post(role+'Result',{ok:false,error:error instanceof Error ? error.message : String(error),peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
}
}
-12
View File
@@ -1,12 +0,0 @@
import { randomBytes } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
try {
await writeFile(new URL('../.env.development', import.meta.url),
`# Local development only; shared by Compose and Vite.\nTURN_SECRET=${randomBytes(32).toString('hex')}\nTURN_HOST=127.0.0.1\nTURN_PORT=3478\nVITE_ICE_ENDPOINT=/api/ice-servers\nVITE_STUN_URL=stun:127.0.0.1:3478\n`,
{ flag: 'wx', mode: 0o600 });
console.log('Created .env.development with a private development TURN secret.');
} catch (error) {
if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
console.log('.env.development already exists; left unchanged. See .env.example for required settings.');
}
+623 -23
View File
@@ -1,34 +1,634 @@
<script setup lang="ts">
import { ref } from 'vue';
import SendPanel from './components/SendPanel.vue';
import ReceivePanel from './components/ReceivePanel.vue';
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
import {
answerOffer,
type Check,
settings as coreSettings,
createOffer,
DEFAULT_STUN_SERVERS,
DEFAULT_TRACKERS,
type Events,
formatTime,
type Incoming,
type Phase,
PROTOCOL,
type ReceiveEvents,
randomCode,
receiveViaTracker,
type SendEvents,
sendViaTracker,
} from './core';
const mode = ref<'send' | 'receive'>('send');
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
// defaults.
const settings = reactive(coreSettings);
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
const ownSalt = reactive({ on: false, text: '' });
// Empty is no salt, Share and Receive wait for one.
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
// From the code's alphabet, 16 characters are about 95 bits.
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
// contacts nobody before an offer, but typing makes one per keystroke, so each line is checked once.
const stunChecks = new Map<string, boolean>();
function isStun(url: string) {
if (!stunChecks.has(url)) {
try {
new RTCPeerConnection({ iceServers: [{ urls: url }] }).close();
stunChecks.set(url, /^stuns?:/i.test(url));
} catch {
stunChecks.set(url, false);
}
}
return stunChecks.get(url)!;
}
// public/ in the build, which works under any path, see vite.config.ts.
const BASE = import.meta.env.BASE_URL;
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
const secure = location.protocol === 'https:';
const isLocal = (hostname: string) =>
hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
hostname === '[::1]';
const isTracker = (url: string) => {
if (!URL.canParse(url) || url.includes('#')) return false;
const { protocol, hostname } = new URL(url);
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
};
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
const text = ref(settings[key].join('\n'));
const lines = computed(() =>
text.value
.split('\n')
.map((line) => line.trim())
.filter(Boolean),
);
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
// Immediate, a default may be a line this browser rejects.
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
// Unwraps both refs, so the template can bind them as plain properties.
return reactive({ text, invalid });
}
const stunServers = serverList('stunServers', isStun);
const trackers = serverList('trackers', isTracker);
function onResetServers() {
stunServers.text = DEFAULT_STUN_SERVERS.join('\n');
trackers.text = DEFAULT_TRACKERS.join('\n');
}
const file = ref<File>();
// The file of the send session, the user may have picked another one since.
const shared = ref<File>();
const offer = ref('');
const answerInput = ref('');
const sendCode = ref('');
// Until when a receiver can find the share with its code, whether with an own salt and whether that
// passed, as the core tells.
const sendUntil = ref(0);
const sendExpired = ref(false);
const offerInput = ref('');
const answer = ref('');
const receiveCode = ref('');
const check = ref<Check>();
const confirmed = ref(false);
// Changed in place and triggered, a deep ref would make each line cost every line kept.
const log = shallowRef<string[]>([]);
// Lines kept, the oldest go first and dropped counts them. A session logs a few dozen, a tracker or
// peer that sends garbage could add lines until the tab freezes.
const MAX_LOG = 1000;
const dropped = ref(0);
// Of the session, shown in the card of its side.
const error = ref('');
const status = ref<{ phase: Phase; text: string }>();
// The bar's look, an error colors whatever it showed.
const phase = computed(() => (error.value ? 'error' : status.value?.phase));
// Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => {
const lines = log.value;
lines.push(`${new Date().toISOString().slice(11, 23)} ${message}`);
if (lines.length > MAX_LOG) dropped.value += lines.splice(0, lines.length - MAX_LOG).length;
triggerRef(log);
},
error: (message) => {
events.log(message);
error.value = message;
},
status: (phase, text) => (status.value = { phase, text }),
check: (result) => {
check.value = result;
confirmed.value = false;
},
};
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
// a transfer starts.
type Progress = { read: number; size: number };
const sent = ref<Progress>();
const sendEvents: SendEvents = {
...events,
progress: (read, size) => (sent.value = { read, size }),
expired: () => (sendExpired.value = true),
};
const incoming = ref<Incoming>();
const received = ref<Progress>();
const receiveEvents: ReceiveEvents = {
...events,
progress: (read, size) => (received.value = { read, size }),
incoming: (file) => {
incoming.value = file;
received.value = undefined;
},
};
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
// Undefined makes the bar indeterminate: until the transfer starts it only shows how the session is
// doing. After it, or an error before it, the bar is full.
function barValue(progress?: Progress) {
if (progress) return percent(progress);
return ['start', 'wait', 'retry'].includes(phase.value!) ? undefined : 100;
}
function onConfirm() {
confirmed.value = true;
check.value?.confirm();
}
// The text copied last and whether that worked. Its button says so, after a success for a moment.
const copied = ref<{ text: string; ok: boolean }>();
let copiedTimer: number | undefined;
const copyLabel = (text: string) => (copied.value?.text !== text ? 'Copy' : copied.value.ok ? 'Copied' : 'Copy failed');
const copyFailed = (text: string) => copied.value?.text === text && !copied.value.ok;
// Copies text, shown in the element with id. If the browser blocks that, the text gets selected, so
// the user can copy it themselves.
async function onCopy(text: string, id: string) {
clearTimeout(copiedTimer);
try {
await navigator.clipboard.writeText(text);
} catch {
events.log('copy failed, the browser blocked the clipboard');
copied.value = { text, ok: false };
const element = document.getElementById(id);
if (element instanceof HTMLTextAreaElement) {
element.focus();
element.select();
} else if (element) getSelection()?.selectAllChildren(element);
return;
}
copied.value = { text, ok: true };
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
}
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
// One session at a time, started by Share, Create offer, Receive or Create answer. Starting one ends
// the one before: its connections close and what it showed goes, so nothing else can write here.
let session: AbortController | undefined;
const side = ref<'send' | 'receive'>();
// Whether the session is a tracker share or search, which runs with the salt it started with.
const viaTracker = ref(false);
// what goes into the log, so the sessions in it can be told apart.
function begin(on: 'send' | 'receive', what: string, tracker = false) {
session?.abort();
session = new AbortController();
side.value = on;
viaTracker.value = tracker;
events.log(`--- ${what} ---`);
error.value = '';
status.value = undefined;
check.value = undefined;
confirmed.value = false;
sent.value = undefined;
incoming.value = undefined;
received.value = undefined;
sendCode.value = '';
sendExpired.value = false;
offer.value = '';
answer.value = '';
acceptAnswer = undefined;
return session.signal;
}
// Resolves with the result of a session step, or undefined if it failed, which is shown, or if a
// newer session replaced it meanwhile.
async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
try {
const result = await step;
return signal.aborted ? undefined : result;
} catch (failure) {
if (!signal.aborted) events.error(failure instanceof Error ? failure.message : String(failure));
}
}
// The name of a dropped folder, until a file takes its place.
const folder = ref('');
function take(picked: File) {
file.value = picked;
folder.value = '';
}
// The input is emptied right away: Chromium fires no change event for the file its input already
// holds, though that file may have changed on disk, or another one was dropped since, which the
// input never saw. An event without a file has nothing to take. Empty, the input's own tooltip says no
// file is chosen, so its title names the one taken.
function onPick(event: Event) {
const input = event.target as HTMLInputElement;
const picked = input.files?.[0];
input.value = '';
if (picked) take(picked);
}
const dragging = ref(false);
// A folder comes as a file too, one that can't be read: refused here, it would fail only once the
// receiver downloads it. The file picked before stays.
function onDrop(event: DragEvent) {
dragging.value = false;
const dropped = event.dataTransfer?.files[0];
const entry = [...(event.dataTransfer?.items ?? [])].find((item) => item.kind === 'file')?.webkitGetAsEntry();
if (entry?.isDirectory) folder.value = entry.name;
else if (dropped) take(dropped);
}
function formatSize(bytes: number) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let unit = 0;
while (bytes >= 1024 && unit < units.length - 1) {
bytes /= 1024;
unit++;
}
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
}
async function onCreateOffer() {
const signal = begin('send', `manual offer for ${file.value!.name}`);
shared.value = file.value;
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
if (!result) return;
offer.value = result.offer;
acceptAnswer = result.accept;
}
// Part of the current session, a wrong answer can be corrected.
function onAcceptAnswer() {
error.value = '';
if (acceptAnswer) attempt(session!.signal, acceptAnswer(answerInput.value));
}
async function onCreateAnswer() {
const signal = begin('receive', 'manual answer');
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
if (result) answer.value = result;
}
async function onShare() {
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
shared.value = file.value;
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
if (!result) return;
sendCode.value = result.code;
sendUntil.value = result.until;
}
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
// the tracker ends it.
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
function onReceive() {
const signal = begin('receive', 'receive via tracker', true);
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
}
// The salt stays as it is while a tracker share runs: it waits in the swarm of the salt it started
// with, another one shown would be the wrong one to give the receiver. A search only takes the salt
// on Receive, so a wrong one can be fixed and searched with again.
const saltLocked = computed(
() => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!),
);
// While a share waits or a transfer runs. A phone that dims and locks may suspend the tab and the
// connection dies, a reload or a closed tab ends it for sure.
const busy = computed(() => ['start', 'wait', 'retry', 'transfer'].includes(phase.value!));
// The screen's, held while busy. The browser releases it whenever the page is hidden, so it's
// requested again once the page is visible.
let wakeLock: Promise<WakeLockSentinel | undefined> | undefined;
function holdWakeLock() {
// Missing outside a secure context, e.g. the dev server opened by its LAN address.
if (!busy.value || document.hidden || wakeLock || !navigator.wakeLock) return;
const request = navigator.wakeLock.request('screen').then(
(sentinel) => {
sentinel.addEventListener('release', () => {
if (wakeLock === request) wakeLock = undefined;
});
// Unless let go of meanwhile, releaseWakeLock releases it then.
if (wakeLock === request) events.log('keeping the screen on');
return sentinel;
},
(failure) => {
if (wakeLock === request) wakeLock = undefined;
events.log(`screen may lock: ${failure instanceof Error ? failure.message : failure}`);
return undefined;
},
);
wakeLock = request;
}
// Forgotten right away, a session started before the browser released it requests a new one.
function releaseWakeLock() {
const request = wakeLock;
wakeLock = undefined;
request?.then((sentinel) => sentinel?.release());
}
// The browser asks before a reload or a closed tab ends it. Only while busy, a page with the handler
// may be kept out of the back/forward cache.
const confirmLeave = (event: BeforeUnloadEvent) => event.preventDefault();
watch(busy, (busy) => {
if (busy) {
holdWakeLock();
addEventListener('beforeunload', confirmLeave);
} else {
releaseWakeLock();
removeEventListener('beforeunload', confirmLeave);
}
});
document.addEventListener('visibilitychange', holdWakeLock);
</script>
<template>
<h1>HellCon</h1>
<p class="subtitle">
Browser-to-browser file sharing. No account or file-hosting backend.
Direct WebRTC connections, with an optional relay you explicitly enable.
</p>
<header>
<div>
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
<h1>HellCon</h1>
</div>
<div id="options">
<div>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
Use STUN
</label>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
Use own salt
</label>
</div>
<div v-if="ownSalt.on" role="group">
<input
id="salt"
v-model="ownSalt.text"
aria-label="Own salt"
placeholder="Same salt on both sides"
:aria-invalid="saltMissing"
:disabled="saltLocked"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
Generate
</button>
</div>
</div>
</header>
<div class="tabs" style="width: 100%; max-width: 680px">
<button :class="{ active: mode === 'send' }" @click="mode = 'send'">Send</button>
<button :class="{ active: mode === 'receive' }" @click="mode = 'receive'">Receive</button>
</div>
<main>
<p v-if="!settings.stun" id="no-stun" role="note">
STUN is off: only devices on the same network or VPN can connect.
</p>
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
No STUN server under Servers: only devices on the same network or VPN can connect.
</p>
<aside v-if="check" role="alert">
<p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
before.
</p>
<dl>
<dt>You</dt>
<dd><output id="check-local">{{ check.local }}</output></dd>
<dt>Peer</dt>
<dd><output id="check-remote">{{ check.remote }}</output></dd>
</dl>
<div v-if="!confirmed">
<button id="confirm" type="button" @click="onConfirm">Codes match</button>
<button id="reject" type="button" @click="check.reject()">Codes don't match</button>
</div>
</aside>
<SendPanel v-if="mode === 'send'" />
<ReceivePanel v-else />
<article>
<h2>Send</h2>
<label
:data-dragging="dragging || undefined"
@dragover.prevent="dragging = true"
@dragleave="dragging = false"
@drop.prevent="onDrop"
>
<input type="file" :title="file?.name" @change="onPick" />
<template v-if="file">
<strong>{{ file.name }}</strong>
{{ formatSize(file.size) }}
</template>
<template v-else>Drop a file or click to choose</template>
<span v-if="folder" id="not-a-file" role="alert">{{ folder }} is a folder, only a single file can be sent</span>
</label>
<div v-if="side === 'send' && phase" :data-phase="phase">
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
<div>
<progress id="send-progress" max="100" :value="barValue(sent)" aria-label="Sent"></progress>
</div>
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="send-status">{{ status!.text }}</span>
<span v-if="sent">{{ percent(sent) }}&nbsp;%</span>
</p>
</div>
<section>
<h3>Tracker</h3>
<button id="share" type="button" :disabled="!file || !settings.trackers.length || saltMissing" @click="onShare">
Share via tracker
</button>
<template v-if="sendCode">
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
<label v-else for="send-code">
Code, give this {{ ownSalt.on ? 'and your salt ' : '' }}to the receiver, valid until
{{ formatTime(sendUntil) }}:
</label>
<div role="group">
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
<button
id="copy-send-code"
type="button"
data-copy
:disabled="codeGone"
@click="onCopy(sendCode, 'send-code')"
>
{{ copyLabel(sendCode) }}
</button>
</div>
<p v-if="copyFailed(sendCode)" role="alert">
The browser blocked copying. The code is selected, copy it yourself.
</p>
</template>
</section>
<details id="send-manual">
<summary>Manual</summary>
<section>
<button id="create-offer" type="button" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
{{ copyLabel(offer) }}
</button>
<p v-if="copyFailed(offer)" role="alert">
The browser blocked copying. The offer is selected, copy it yourself.
</p>
<label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
Connect
</button>
</template>
</section>
</details>
</article>
<article>
<h2>Receive</h2>
<div id="incoming">
<template v-if="incoming">
<strong>{{ incoming.name }}</strong>
{{ formatSize(incoming.size) }}
<button v-if="!received" id="download" type="button" @click="incoming.download()">Download</button>
</template>
<template v-else>The sender's file shows up here after the security check</template>
</div>
<div v-if="side === 'receive' && phase" :data-phase="phase">
<div>
<progress id="receive-progress" max="100" :value="barValue(received)" aria-label="Received"></progress>
</div>
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="receive-status">{{ status!.text }}</span>
<span v-if="received">{{ percent(received) }}&nbsp;%</span>
</p>
</div>
<section>
<h3>Tracker</h3>
<label for="receive-code">Code from the sender:</label>
<div role="group">
<input
id="receive-code"
v-model="receiveCode"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button
id="receive"
type="button"
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
@click="onReceive"
>
Receive
</button>
</div>
</section>
<details id="receive-manual">
<summary>Manual</summary>
<section>
<label for="offer-input">Offer from the sender:</label>
<textarea id="offer-input" v-model="offerInput"></textarea>
<button id="create-answer" type="button" :disabled="!offerInput.trim()" @click="onCreateAnswer">
Create answer
</button>
<template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
{{ copyLabel(answer) }}
</button>
<p v-if="copyFailed(answer)" role="alert">
The browser blocked copying. The answer is selected, copy it yourself.
</p>
</template>
</section>
</details>
</article>
<details id="servers">
<summary>Servers</summary>
<div>
<section>
<h3>STUN</h3>
<label for="stun-servers">Tell each side its public address, one URL per line:</label>
<textarea
id="stun-servers"
v-model="stunServers.text"
:aria-invalid="!!stunServers.invalid.length"
></textarea>
<p v-if="stunServers.invalid.length">
Skipped, not a STUN URL this browser accepts: {{ stunServers.invalid.join(', ') }}
</p>
</section>
<section>
<h3>Trackers</h3>
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label>
<textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
<p v-if="trackers.invalid.length">
Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
{{ trackers.invalid.join(', ') }}
</p>
</section>
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
</div>
</details>
<details>
<summary>Log</summary>
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
</details>
</main>
<footer>
<p>
Files travel over encrypted WebRTC data channels (SCTP over DTLS).
Verify both full fingerprints before sharing. This requires trusted
browsers, a trusted copy of this app, and an authenticated comparison
channel. The website host supplies JavaScript that can read your selected
file; HTTPS protects delivery but cannot protect you from a malicious host.
A TURN relay is used only after opt-in and carries encrypted traffic.
</p>
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
Source code
</a>
<span>Protocol {{ PROTOCOL }}</span>
</footer>
</template>
-30
View File
@@ -1,30 +0,0 @@
<script setup lang="ts">
import type { NetworkSettings } from '../lib/webrtc.ts';
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
const settings = defineModel<NetworkSettings>({ required: true });
defineProps<{ disabled?: boolean }>();
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
</script>
<template>
<fieldset :disabled="disabled" class="network-settings">
<legend>Connection settings</legend>
<label for="stun-provider">STUN provider</label>
<select id="stun-provider" v-model="settings.stunChoice" class="stun-select">
<option v-for="provider in STUN_PROVIDERS" :key="provider.id" :value="provider.id">{{ provider.label }}</option>
<option value="custom">Custom…</option>
</select>
<input v-if="settings.stunChoice === 'custom'" v-model="settings.customStun" class="stun-input" aria-label="Custom STUN address" placeholder="stun:your.domain:3478" />
<p class="status">STUN helps discover a reachable address. Its operator sees your public IP and request timing, but does not carry your file. Direct connections may fail on restrictive networks.</p>
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
<template v-if="settings.allowTurn">
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
<label v-if="iceEndpoint" class="checkbox"><input type="checkbox" v-model="settings.managedTurn" /> Use the configured relay with temporary credentials</label>
<template v-if="!iceEndpoint || !settings.managedTurn">
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
</template>
</template>
</fieldset>
</template>
-4
View File
@@ -1,4 +0,0 @@
<script setup lang="ts">
import TransferPanel from './TransferPanel.vue';
</script>
<template><TransferPanel /></template>
-4
View File
@@ -1,4 +0,0 @@
<script setup lang="ts">
import TransferPanel from './TransferPanel.vue';
</script>
<template><TransferPanel sending /></template>
-283
View File
@@ -1,283 +0,0 @@
<script setup lang="ts">
import { asError } from '../lib/validation.ts';
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
import { computed, onBeforeUnmount, ref } from 'vue';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
pc: RTCPeerConnection;
options: IceOptions;
file: File | null;
controller: AbortController;
transfer: Transfer | null;
timer?: ReturnType<typeof setTimeout>;
}
const props = defineProps<{ sending?: boolean }>();
const file = ref<File | null>(null);
const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
const error = ref('');
const copied = ref(false);
const fps = ref<Fingerprints | null>(null);
const verified = ref(false);
const progress = ref(0);
const incoming = ref<FileMetadata | null>(null);
const downloadUrl = ref('');
const choosing = ref(false);
const dragover = ref(false);
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
const defaultStun = import.meta.env.VITE_STUN_URL || '';
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
let active: Session | null = null;
let copyTimer: ReturnType<typeof setTimeout> | undefined;
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
const status = computed(() => ({
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
gathering: 'Gathering connection info (up to 30 seconds)…',
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.',
'waiting-accept': 'Waiting for the receiver to accept the file…',
'choose-storage': 'Choose how to receive this file.',
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : 'File saved to disk.'),
closed: props.sending
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
}[step.value] || ''));
function revokeDownload() {
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
downloadUrl.value = '';
}
function dispose() {
const old = active;
active = null;
if (!old) return;
clearTimeout(old.timer);
old.controller.abort();
old.transfer?.close();
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
old.pc.close();
}
function reset(keepNetwork = false) {
dispose(); revokeDownload(); clearTimeout(copyTimer);
if (!keepNetwork) settings.value.allowTurn = false;
inputCode.value = outputCode.value = error.value = '';
fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false;
progress.value = 0; step.value = 'idle';
}
function fail(session: Session, err: unknown) {
if (active !== session) return;
dispose(); revokeDownload();
fps.value = incoming.value = null;
outputCode.value = ''; verified.value = false;
settings.value.allowTurn = false;
error.value = asError(err).message; step.value = 'closed';
}
function pickFiles(event: Event) {
const selected = event.target instanceof HTMLInputElement ? event.target.files?.[0]
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined;
if (!selected) return;
reset();
if (selected.size > FILE_LIMIT) { file.value = null; error.value = 'The maximum file size is 64 GiB.'; return; }
file.value = selected;
}
function attach(session: Session, channel: RTCDataChannel) {
if (active !== session) { channel.close(); return; }
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
}
session.transfer = new Transfer(channel, {
file: props.sending ? session.file : null,
onState: state => { if (active === session) step.value = state; },
onMeta: meta => { if (active === session) incoming.value = meta; },
onProgress: (bytes, size) => { if (active === session) progress.value = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100)); },
onComplete: ({ blob }) => {
if (active !== session) return;
progress.value = 100;
settings.value.allowTurn = false;
if (blob) downloadUrl.value = URL.createObjectURL(blob);
// The receiver leaves the channel open until its completion ACK reaches the sender.
if (props.sending) dispose();
else {
clearTimeout(session.timer);
session.timer = setTimeout(() => { if (active === session) dispose(); }, 10000);
}
},
onError: err => fail(session, err),
});
if (verified.value) session.transfer.verify();
}
function start() {
const chosen = settings.value;
const options = {
...chosen,
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
turnUrl: chosen.turnUrl.trim(),
};
// Fetch managed credentials before gathering, while retaining normal cancellation.
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
active = session;
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
pc.ondatachannel = event => attach(session, event.channel);
pc.onconnectionstatechange = () => {
if (active !== session) return;
if (['failed', 'closed'].includes(pc.connectionState)) {
if (step.value === 'done') dispose();
else fail(session, new Error('Connection failed. Direct connections may be blocked; TURN is available only if both people opt in.'));
}
};
return session;
}
async function createCode() {
const pasted = inputCode.value;
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
let session: Session | undefined;
try {
if (props.sending) {
if (!file.value) throw new Error('Choose a file first.');
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
}
session = start();
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
if (active !== session) return;
session.pc.setConfiguration(iceConfiguration(configured));
const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
if (active !== session) return;
outputCode.value = code;
if (!props.sending) fps.value = getFingerprints(session.pc, options);
step.value = props.sending ? 'offer-ready' : 'answer-ready';
} catch (err) {
if (session) fail(session, err);
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
}
}
async function useAnswer() {
const session = active;
if (!session || step.value !== 'offer-ready') return;
error.value = '';
step.value = 'verification';
try {
await acceptAnswerCode(session.pc, inputCode.value, session.options);
if (active !== session) return;
fps.value = getFingerprints(session.pc, session.options);
} catch (err) {
if (active !== session) return;
// A rejected answer does not consume a valid local offer. Let the user
// correct a paste error instead of silently invalidating both peers' codes.
if (session.pc.signalingState === 'have-local-offer') {
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
step.value = 'offer-ready';
} else fail(session, err);
}
}
function verify() {
if (!active || !fps.value || verified.value) return;
verified.value = true; step.value = 'verification';
// Gathering/handshake timeout ends; Transfer manages verification and transfer deadlines.
const session = active;
clearTimeout(session.timer);
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
session.transfer?.verify();
}
async function acceptFile(toDisk: boolean) {
const session = active;
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
choosing.value = true; error.value = '';
let writable: FileDestination | undefined;
try {
if (toDisk) {
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
if (active !== session) return;
writable = await handle.createWritable();
if (active !== session) { await writable.abort(); return; }
}
session.transfer.accept(writable);
} catch (err) {
if (writable) await writable.abort().catch(() => {});
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
} finally { if (active === session) choosing.value = false; }
}
async function copy() {
const session = active;
try {
await navigator.clipboard.writeText(outputCode.value);
if (active !== session) return;
copied.value = true; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
}
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`;
const index = Math.min(3, Math.floor(Math.log(bytes) / Math.log(1024)));
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB'][index]}`;
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script>
<template>
<div class="panel">
<template v-if="sending">
<label class="step" for="file-input">Choose one file (up to 64 GiB)</label>
<div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)">
<p>Drop a file here or choose one below. Choosing a new file cancels the current connection.</p>
<input id="file-input" type="file" @change="pickFiles" />
</div>
<p v-if="file" class="file-chip"><span>{{ file.name }}</span><span>{{ formatBytes(file.size) }}</span></p>
</template>
<NetworkSettings v-model="settings" :disabled="busy" />
<p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</p>
<template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s connection code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" />
</template>
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode">
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
</template>
<template v-if="sending && outputCode">
<label class="step" for="answer-input">Paste the receiver’s answer</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</template>
<div v-if="fps" class="fingerprint">
<label class="step">Verify both full SHA-256 fingerprints</label>
<div class="fp-row"><span>Your fingerprint</span><code>{{ fps.local }}</code></div>
<div class="fp-row"><span>Their fingerprint</span><code>{{ fps.remote }}</code></div>
<p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p>
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Fingerprints confirmed' : 'Both fingerprints match — confirm' }}</button>
</div>
<div v-if="incoming && step === 'choose-storage'" class="incoming">
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile(true)">Choose destination & receive to disk</button>
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile(false)">Receive in memory (up to 64 MiB)</button>
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
</div>
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
<p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
</div>
</template>
+1772
View File
File diff suppressed because it is too large. Load diff
+1404
View File
File diff suppressed because it is too large. Load diff
+165
View File
@@ -0,0 +1,165 @@
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
// This is the page's half of it. The receiver in src/core.ts only sees startDownload, so it can be
// tested against a download in memory, and another way of saving could take this one's place.
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
// Without either for longer, public/sw.js takes the page for gone and fails the download, see SILENCE.
const KEEPALIVE = 10_000;
// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its
// download manager. Its frame removed before that, the download never shows up, though the worker
// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests.
const DOWNLOAD_GRACE = 1000;
// Of the messages between this page and public/sw.js, which has it too. A page can talk to a worker
// of another version: a new page while another tab's download holds the old worker, or an old page
// once an update took over. The worker refuses a version it doesn't speak with outdated, each change
// to the messages takes a new one, in both files.
const VERSION = 1;
const downloads = registerDownloads();
// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window.
downloads.catch(() => {});
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
async function registerDownloads() {
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
const pending = registration.installing ?? registration.waiting;
if (!registration.active && pending) {
await new Promise((resolve) =>
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
);
}
if (!registration.active) throw new Error('service worker did not activate');
}
// Awaited before receiving starts, so a browser without service workers fails before connecting.
export function downloadsReady() {
return downloads.catch((error) => {
throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`);
});
}
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
// worker in the middle of the download.
async function holdWorker() {
await downloads;
const frame = document.createElement('iframe');
frame.hidden = true;
frame.src = 'download/';
document.body.append(frame);
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
if (!worker) {
frame.remove();
throw new Error('service worker did not take over');
}
return { frame, worker };
}
// What the download manager does with a download, see startDownload. Each one but read ends it, only
// the first of them comes, and none after fail.
export type DownloadEvents = {
// How many bytes it has read so far, every MiB.
read: (bytes: number) => void;
// It has read the last byte.
finished: () => void;
// The user cancelled it.
cancelled: () => void;
// Something else than fail ended it: no worker, the worker refused it or stopped.
failed: (reason: string) => void;
};
// The receiver writes every chunk, then ends it once all arrived, or fails it.
export type Download = {
write: (chunk: ArrayBuffer) => void;
end: () => void;
fail: (reason: string) => void;
};
// Starts saving file in the browser's download manager. Writes can come before the worker is held,
// they wait for it in order. Once it ended, its frames go and the worker is free for an update.
export function startDownload(file: { name: string; size: number }, events: DownloadEvents): Download {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let keepalive: ReturnType<typeof setInterval> | undefined;
// By whatever came first: the worker's answer, its stop or fail.
let ended = false;
// Chaining every post on this keeps them in order.
const worker: Promise<ServiceWorker | undefined> = holdWorker().then(
({ frame, worker }) => {
frames.push(frame);
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
// An update takes over only once the frames are released, then this changes nothing. Else
// something stopped it in the middle, e.g. clearing the site data, it can't answer then.
worker.addEventListener('statechange', () => {
if (worker.state !== 'redundant') return;
if (!ended) events.failed('service worker stopped');
ended = true;
release();
});
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
if (typeof data === 'number') return ended || events.read(data);
if (data === 'ready') {
if (ended) return;
// A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe');
download.hidden = true;
download.src = `download/${id}`;
document.body.append(download);
frames.push(download);
return;
}
if (!ended) {
if (data === 'finished') events.finished();
if (data === 'cancelled') events.cancelled();
if (data === 'failed') events.failed('the service worker refused it');
if (data === 'silent') events.failed('the service worker heard nothing from this page for too long');
if (data === 'outdated') {
events.failed('this page and its service worker are different versions, reload once no tab receives');
}
}
ended = true;
release(data === 'finished');
};
worker.postMessage({ id, version: VERSION, ...file }, [port2]);
return worker;
},
(error) => {
if (!ended) events.failed(String(error));
ended = true;
return undefined;
},
);
const post = (message: object, transfer: Transferable[] = []) =>
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
// Removed earlier, Chromium keeps a failed download running instead of failing it. A finished
// download keeps its own frame for DOWNLOAD_GRACE, that one doesn't hold the worker. Only the first
// call counts, a later one would take that frame right away.
let released = false;
function release(finished = false) {
if (released) return;
released = true;
clearInterval(keepalive);
const [hold, download] = frames;
hold?.remove();
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
else download?.remove();
}
return {
write: (chunk) => post({ chunk }, [chunk]),
end: () => post({ done: true }),
// The worker answers with failed, only then the frames go. A worker that restarted lost the
// download, and its stream with it, it never answers: they go after KEEPALIVE anyway.
fail: (reason) => {
if (ended) return;
ended = true;
post({ error: reason });
void worker.then(() => setTimeout(release, KEEPALIVE));
},
};
}
+4 -6
View File
@@ -1,8 +1,6 @@
interface ImportMetaEnv {
readonly VITE_ICE_ENDPOINT?: string;
readonly VITE_STUN_URL?: string;
}
declare module '*.vue' {
import type { DefineComponent } from 'vue';
interface Window {
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
const component: DefineComponent;
export default component;
}
-240
View File
@@ -1,240 +0,0 @@
import { asError, isRecord } from './validation.ts';
import type { BufferedChannel } from './webrtc.ts';
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.ts';
export interface FileMetadata { name: string; size: number; mime: string }
export type TransferState = 'verification' | 'waiting-accept' | 'choose-storage' | 'sending' |
'receiving' | 'saving' | 'awaiting-receipt' | 'done' | 'closed';
export interface TransferResult { blob?: Blob | null; meta: FileMetadata }
export interface FileDestination {
write(data: ArrayBuffer): Promise<void>;
close(): Promise<void>;
abort(): Promise<void>;
}
export interface TransferChannel extends BufferedChannel {
binaryType: BinaryType;
onopen: ((event: Event) => void) | null;
onmessage: ((event: MessageEvent<unknown>) => void) | null;
onclose: ((event: Event) => void) | null;
onerror: ((event: RTCErrorEvent) => void) | null;
send(data: string | ArrayBuffer): void;
close(): void;
}
export interface TransferOptions {
file?: File | null;
onState?: (state: TransferState) => void;
onMeta?: (meta: FileMetadata) => void;
onProgress?: (bytes: number, size: number) => void;
onComplete?: (result: TransferResult) => void;
onError?: (error: Error) => void;
timeout?: number;
}
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
export const MEMORY_LIMIT = 64 * 1024 * 1024;
export const FILE_LIMIT = 64 * 1024 * 1024 * 1024;
const CONTROL_LIMIT = 2048;
const WINDOW = MAX_BUFFERED;
export function validateMetadata(meta: unknown): FileMetadata {
if (!isRecord(meta) || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
throw new Error('Invalid file metadata or file exceeds the 64 GiB limit.');
}
return { name: meta.name, size: meta.size, mime: meta.mime };
}
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
export class Transfer {
readonly dc: TransferChannel;
readonly file: File | null;
readonly onState: NonNullable<TransferOptions['onState']>;
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
readonly onComplete: NonNullable<TransferOptions['onComplete']>;
readonly onError: NonNullable<TransferOptions['onError']>;
readonly timeout: number;
state: TransferState;
verified: boolean;
peerReady: boolean;
readySent: boolean;
closed: boolean;
received: number;
sent: number;
acked: number;
queued: number;
messages: number;
chunks: ArrayBuffer[];
queue: Promise<void>;
readonly controller: AbortController;
private timer: ReturnType<typeof setTimeout> | undefined;
private meta: FileMetadata | null = null;
private writable: FileDestination | null = null;
private wake: (() => void) | null = null;
private get metadata(): FileMetadata {
if (!this.meta) throw new Error('Missing file metadata.');
return this.meta;
}
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 }: TransferOptions = {}) {
this.dc = dc;
this.file = file;
this.onState = onState;
this.onMeta = onMeta;
this.onProgress = onProgress;
this.onComplete = onComplete;
this.onError = onError;
this.timeout = timeout;
this.state = 'verification';
this.verified = false;
this.peerReady = false;
this.readySent = false;
this.closed = false;
this.received = this.sent = this.acked = this.queued = this.messages = 0;
this.chunks = [];
this.queue = Promise.resolve();
this.controller = new AbortController();
dc.binaryType = 'arraybuffer';
dc.onopen = () => this.guard(() => this.ready());
dc.onmessage = e => this.enqueue(e.data);
const transportEnded = (message: string) => {
// Firefox can report an SCTP error when the sender closes its peer
// connection after receiving our completion ACK. The saved file remains
// valid; a transport shutdown must not revoke a completed download.
if (this.state === 'done') this.close();
else this.fail(new Error(message));
};
dc.onclose = () => transportEnded('Connection closed before receipt was confirmed.');
dc.onerror = () => transportEnded('Data channel failed.');
this.touch(5 * 60 * 1000);
}
setState(state: TransferState) { this.state = state; this.onState(state); }
touch(ms = this.timeout) {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
}
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number } = {}) {
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
const text = JSON.stringify({ v: 2, type, ...data });
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
this.dc.send(text);
}
verify() {
if (this.closed || this.verified) return;
this.verified = true;
this.guard(() => this.ready());
}
ready() {
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
if (!this.readySent) { this.control('ready'); this.readySent = true; }
if (this.file && this.peerReady && this.state === 'verification') {
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
this.setState('waiting-accept');
this.control('meta', this.metadata);
this.touch(5 * 60 * 1000);
}
}
enqueue(data: unknown) {
if (this.closed) return;
const binary = data instanceof ArrayBuffer;
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
if (size > (binary ? CHUNK_SIZE : CONTROL_LIMIT) || this.queued + size > WINDOW * 2 || this.messages >= 128) {
this.fail(new Error('Peer exceeded message or buffering limits.')); return;
}
this.queued += size; this.messages++;
this.queue = this.queue.then(async () => {
if (!this.closed) await this.message(data);
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
}
async message(data: unknown) {
if (data instanceof ArrayBuffer) {
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.metadata.size) throw new Error('Unexpected or excess file data.');
// Bound per-chunk overhead as well as payload bytes: millions of tiny
// ArrayBuffers would otherwise defeat the in-memory size limit.
if (data.byteLength !== Math.min(CHUNK_SIZE, this.metadata.size - this.received)) throw new Error('Invalid file chunk size.');
if (this.writable) await this.writable.write(data);
else this.chunks.push(data);
if (this.closed) return;
this.received += data.byteLength;
this.control('ack', { bytes: this.received });
this.onProgress(this.received, this.metadata.size);
this.touch();
return;
}
if (typeof data !== 'string') throw new Error('Unsupported transfer message.');
const msg: unknown = JSON.parse(data);
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
this.peerReady = true; this.ready(); return;
}
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
if (msg.type === 'meta' && !this.file && this.state === 'verification') {
this.meta = validateMetadata(msg);
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
}
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
this.setState('sending'); this.touch();
void this.sendFile().catch(err => this.fail(err)); return;
}
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
if (typeof msg.bytes !== 'number' || !Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
}
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
if (this.received !== this.metadata.size) throw new Error('Incomplete file.');
this.setState('saving');
if (this.writable) await this.writable.close();
if (this.closed) return;
// Treat downloads as opaque files, regardless of the sender's MIME claim.
const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' });
this.chunks = [];
this.control('complete', { bytes: this.received });
this.setState('done'); clearTimeout(this.timer);
this.onComplete({ blob, meta: this.metadata }); return;
}
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata }); this.close(); return;
}
throw new Error('Unexpected transfer message.');
}
accept(writable: FileDestination | null = null) {
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
this.writable = writable;
this.setState('receiving'); this.touch();
this.guard(() => this.control('accept'));
}
async sendFile() {
const file = this.file;
if (!file) throw new Error('No file selected.');
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
if (this.sent - this.acked >= WINDOW) await new Promise<void>(resolve => { this.wake = resolve; });
this.wake = null;
if (this.closed) return;
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
const buffer = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
if (this.closed) return;
this.sent += buffer.byteLength;
this.dc.send(buffer);
}
if (this.closed) return;
this.setState('awaiting-receipt'); this.control('end'); this.touch();
}
fail(err: unknown) {
if (this.closed) return;
this.close(); this.setState('closed'); this.onError(asError(err));
}
close() {
if (this.closed) return;
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
this.chunks = [];
const writable = this.writable;
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
this.dc.close();
}
}
-11
View File
@@ -1,11 +0,0 @@
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
}
export function asError(value: unknown, fallback = 'Connection failed.'): Error {
return value instanceof Error ? value : new Error(fallback);
}
-199
View File
@@ -1,199 +0,0 @@
import { asError, isRecord, isStringArray } from './validation.ts';
export interface IceOptions {
stunUrl?: string | null;
allowTurn?: boolean;
managedTurn?: boolean;
turnUrl?: string | string[];
username?: string;
credential?: string;
}
export interface NetworkSettings {
stunChoice: 'google' | 'cloudflare' | 'none' | 'custom';
customStun: string;
allowTurn: boolean;
managedTurn: boolean;
turnUrl: string;
username: string;
credential: string;
}
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
export interface Fingerprints { local: string; remote: string }
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
// Manual signaling. Codes are encoded connection details, not encrypted secrets.
export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024;
export const MAX_SIGNAL_LENGTH = 64 * 1024;
export const STUN_PROVIDERS = [
{ id: 'google', label: 'Google', url: 'stun:stun.l.google.com:19302' },
{ id: 'cloudflare', label: 'Cloudflare', url: 'stun:stun.cloudflare.com:3478' },
{ id: 'none', label: 'None (direct connections only)', url: null },
];
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' }: IceOptions = {}): { iceServers: RTCIceServer[] } {
const iceServers: RTCIceServer[] = [];
if (stunUrl) {
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
iceServers.push({ urls: stunUrl });
}
// Credentials and URLs are ignored unless this user explicitly opts in.
if (allowTurn) {
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
}
iceServers.push({ urls: turnUrl, username, credential });
}
return { iceServers };
}
export async function fetchTurnOptions(options: IceOptions, endpoint: string, { signal, fetchImpl = fetch }: { signal?: AbortSignal; fetchImpl?: CredentialFetch } = {}): Promise<IceOptions> {
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
const data: unknown = await response.json();
if (!isRecord(data) || typeof data.expiresAt !== 'number' || !Number.isFinite(data.expiresAt) ||
data.expiresAt <= Date.now() / 1000 + 30 || !Array.isArray(data.iceServers)) {
throw new Error('Missing or expired TURN credentials.');
}
const turn: unknown = data.iceServers.find((server: unknown) => {
if (!isRecord(server)) return false;
const urls: unknown[] = Array.isArray(server.urls) ? server.urls : [server.urls];
return urls.length > 0 && urls.every(url => typeof url === 'string' && /^turns?:/i.test(url));
});
if (!isRecord(turn) || typeof turn.username !== 'string' || typeof turn.credential !== 'string' ||
!(typeof turn.urls === 'string' || isStringArray(turn.urls))) {
throw new Error('Missing or invalid TURN credentials.');
}
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
iceConfiguration(result);
return result;
}
export function createPeerConnection(options: IceOptions) {
return new RTCPeerConnection(iceConfiguration(options));
}
export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: WaitOptions = {}) {
return new Promise<void>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = () => {
clearTimeout(timer);
pc.removeEventListener('icegatheringstatechange', check);
pc.removeEventListener('connectionstatechange', check);
signal?.removeEventListener('abort', aborted);
};
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
const aborted = () => finish(new Error('Connection cancelled.'));
const check = () => {
if (signal?.aborted || pc.connectionState === 'closed') aborted();
else if (pc.iceGatheringState === 'complete') finish();
};
pc.addEventListener('icegatheringstatechange', check);
pc.addEventListener('connectionstatechange', check);
signal?.addEventListener('abort', aborted, { once: true });
timer = setTimeout(() => finish(new Error('Connection gathering timed out. Check the server settings and try again.')), timeout);
check();
});
}
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
throw new Error('Invalid connection description.');
}
const lines = sdp.split(/\r?\n/);
const media = lines.filter(line => line.startsWith('m='));
if (media.length !== 1 || !/^m=application \d+ (?:UDP\/DTLS\/SCTP|DTLS\/SCTP) (?:webrtc-datachannel|\d+)$/.test(media[0])) {
throw new Error('Only a single file data channel is supported.');
}
// Deliberately reject ambiguous fingerprints rather than guessing SDP scope.
const fingerprints = lines.filter(line => line.startsWith('a=fingerprint:'));
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
throw new Error('A single full SHA-256 fingerprint is required.');
}
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
}
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
}
export function getFingerprints(pc: { localDescription: { sdp: string } | null; remoteDescription: { sdp: string } | null }, options?: Pick<IceOptions, 'allowTurn'>): Fingerprints {
return {
local: validateDescription(pc.localDescription?.sdp, options),
remote: validateDescription(pc.remoteDescription?.sdp, options),
};
}
export function encodeSignal(sdp: string) {
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, '');
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
return code;
}
export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTurn'>): string {
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
try {
const clean = text.trim().replace(/\s+/g, '');
const data: unknown = JSON.parse(atob(clean));
if (!isRecord(data) || data.version !== 2) throw new Error('Both people need the current HellCon version.');
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
validateDescription(data.sdp, options);
return data.sdp;
} catch (err) {
if (err instanceof SyntaxError || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
throw err;
}
}
export async function createOfferCode(pc: RTCPeerConnection, options: SignalOptions = {}) {
await pc.setLocalDescription(await pc.createOffer());
await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp);
}
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) {
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) });
await pc.setLocalDescription(await pc.createAnswer());
await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp);
}
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) {
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
}
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
return new Promise<void>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = () => {
clearTimeout(timer);
dc.removeEventListener('bufferedamountlow', check);
dc.removeEventListener('close', check);
dc.removeEventListener('error', failed);
signal?.removeEventListener('abort', failed);
};
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
const failed = () => finish(new Error('Transfer interrupted.'));
const check = () => {
if (signal?.aborted || dc.readyState !== 'open') failed();
else if (dc.bufferedAmount <= MAX_BUFFERED / 2) finish();
};
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
dc.addEventListener('bufferedamountlow', check);
dc.addEventListener('close', check);
dc.addEventListener('error', failed);
signal?.addEventListener('abort', failed, { once: true });
timer = setTimeout(() => finish(new Error('Transfer stalled.')), timeout);
check();
});
}
+638 -196
View File
@@ -1,256 +1,698 @@
:root {
color-scheme: dark;
--bg: #0f1117;
--panel: #181b24;
--border: #2a2f3d;
--accent: #e8452c;
--accent-soft: rgba(232, 69, 44, 0.15);
--text: #e8eaf0;
--muted: #8b91a3;
}
* {
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
*:not(dialog) {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
}
@media (prefers-reduced-motion: no-preference) {
html {
interpolate-size: allow-keywords;
}
}
body {
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
img,
picture,
video,
canvas,
svg {
display: block;
max-width: 100%;
}
input,
button,
textarea,
select {
font: inherit;
}
p,
h1,
h2,
h3,
h4,
h5,
h6 {
overflow-wrap: break-word;
}
p {
text-wrap: pretty;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-wrap: balance;
}
#app {
isolation: isolate;
}
:root {
color-scheme: dark;
font-family: system-ui, sans-serif;
--color-primary: #5865f2;
--color-primary-hover: #4752c4;
--color-on-primary: #fff;
--color-secondary: #eb459e;
/* The secondary is too dark for text on the surfaces, this one keeps 4.5:1 */
--color-secondary-text: #f278b7;
--color-success: #23a559;
--color-bg: #313338;
--color-surface: #2b2d31;
--color-input: #1e1f22;
--color-border: #3f4147;
--color-text: #dbdee1;
--color-text-muted: #949ba4;
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 0.75rem;
--space-4: 1rem;
--space-6: 1.5rem;
--space-8: 2rem;
--text-sm: 0.875rem;
--text-lg: 1.125rem;
--text-xl: 1.25rem;
--radius: 0.5rem;
--shadow: 0 1px 3px rgb(0 0 0 / 0.4), 0 1px 2px rgb(0 0 0 / 0.3);
--transition: 150ms ease;
}
body {
min-height: 100vh;
display: flex;
flex-direction: column;
background: var(--color-bg);
color: var(--color-text);
}
/* Layout */
header,
main,
footer {
max-width: 64rem;
margin-inline: auto;
padding-inline: var(--space-4);
}
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
header {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
align-items: center;
padding-inline: 0.9rem;
gap: var(--space-4);
padding-block: var(--space-6) var(--space-4);
}
.panel {
width: 100%;
max-width: 680px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 12px;
padding: 1.5rem;
header > div:first-child {
display: flex;
align-items: center;
gap: var(--space-3);
}
header h1 {
font-size: var(--text-xl);
}
/* The switches at the end, the own salt below while it's on */
#options {
display: flex;
flex-direction: column;
gap: 0.9rem;
gap: var(--space-2);
}
h1 {
margin: 2rem 0 0.25rem;
font-family: ui-monospace, 'Cascadia Code', monospace;
}
.subtitle {
color: var(--muted);
margin: 0 0 1.5rem;
font-size: 0.9rem;
}
.tabs {
#options > div:first-child {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
flex-wrap: wrap;
justify-content: end;
align-items: center;
gap: var(--space-3);
}
.tabs button {
flex: 1;
main {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
align-items: start;
gap: var(--space-4);
padding-bottom: var(--space-8);
}
button {
background: var(--panel);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.55rem 1rem;
font-size: 0.95rem;
cursor: pointer;
main > p,
main > aside,
main > details {
grid-column: 1 / -1;
}
button:hover:not(:disabled) {
border-color: var(--accent);
/* Note while no STUN server would be used, quiet above the cards */
#no-stun {
font-size: var(--text-sm);
color: var(--color-text-muted);
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
/* Cards */
article,
details {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
article {
display: flex;
flex-direction: column;
gap: var(--space-4);
padding: var(--space-6);
}
article h2 {
font-size: var(--text-lg);
}
section {
display: flex;
flex-direction: column;
align-items: start;
gap: var(--space-2);
padding-top: var(--space-4);
border-top: 1px solid var(--color-border);
}
h3,
article summary {
font-size: var(--text-sm);
font-weight: 600;
}
button:disabled {
opacity: 0.45;
cursor: default;
}
.tabs button.active {
background: var(--accent-soft);
border-color: var(--accent);
color: var(--accent);
font-weight: 600;
}
label.step {
font-size: 0.8rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--muted);
letter-spacing: 0.05em;
color: var(--color-text-muted);
}
label,
section p {
font-size: var(--text-sm);
color: var(--color-text-muted);
}
section p[role='alert'] {
color: var(--color-secondary-text);
}
header label {
color: var(--color-text);
}
/* Forms */
input,
textarea {
width: 100%;
padding: var(--space-2) var(--space-3);
background: var(--color-input);
border: 1px solid var(--color-border);
border-radius: var(--radius);
color: inherit;
transition: border-color var(--transition);
}
input:focus,
textarea:focus {
border-color: var(--color-secondary);
}
/* Like a disabled button, the switch with its label */
input:not([role='switch']):disabled,
label:has([role='switch']:disabled) {
opacity: 0.4;
cursor: not-allowed;
}
label:has([role='switch']:disabled) [role='switch'] {
cursor: inherit;
}
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
input:not([type='checkbox'], [type='file']):focus-visible,
textarea:focus-visible {
outline: none;
}
::placeholder {
color: var(--color-text-muted);
opacity: 0.7;
}
textarea {
width: 100%;
min-height: 90px;
min-height: 5rem;
resize: vertical;
background: var(--bg);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.6rem;
font-family: ui-monospace, monospace;
font-size: 0.75rem;
word-break: break-all;
font-size: var(--text-sm);
}
.dropzone {
border: 2px dashed var(--border);
border-radius: 10px;
padding: 2rem;
button {
padding: var(--space-2) var(--space-4);
border: 1px solid transparent;
border-radius: var(--radius);
background: var(--color-primary);
color: var(--color-on-primary);
font-weight: 500;
cursor: pointer;
transition: background-color var(--transition);
}
button:hover:not(:disabled) {
background: var(--color-primary-hover);
}
button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
:focus-visible {
outline: 2px solid var(--color-secondary);
outline-offset: 2px;
}
[role='group'] {
display: flex;
gap: var(--space-2);
width: 100%;
}
/* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
#send-code,
#receive-code {
color: var(--color-secondary-text);
font-family: ui-monospace, monospace;
font-size: var(--text-lg);
font-weight: 600;
letter-spacing: 0.15em;
}
#send-code {
flex: 1;
padding: var(--space-2) var(--space-3);
background: var(--color-input);
border: 1px solid var(--color-border);
border-radius: var(--radius);
user-select: all;
}
#send-code[data-expired] {
text-decoration: line-through;
user-select: none;
}
/* Copy and Generate, secondary next to the value they are for */
[data-copy] {
padding: var(--space-1) var(--space-3);
background: transparent;
border-color: var(--color-border);
color: var(--color-text);
font-size: var(--text-sm);
}
[data-copy]:hover:not(:disabled) {
background: var(--color-border);
}
/* Manual signaling, folded away below the tracker in each card */
article details {
background: none;
border: none;
border-top: 1px solid var(--color-border);
border-radius: 0;
box-shadow: none;
}
article summary {
padding: var(--space-4) 0 0;
}
article details section {
padding-top: var(--space-2);
border-top: none;
}
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
label:has(> [type='file']),
#incoming {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-1);
padding: var(--space-8) var(--space-4);
background: var(--color-input);
border: 2px dashed var(--color-border);
border-radius: var(--radius);
text-align: center;
color: var(--muted);
transition:
border-color var(--transition),
background-color var(--transition);
}
label:has(> [type='file']):hover,
label[data-dragging] {
border-color: var(--color-primary);
}
label[data-dragging] {
background: color-mix(in srgb, var(--color-primary) 10%, var(--color-input));
}
label:has(> [type='file']:focus-visible) {
outline: 2px solid var(--color-secondary);
outline-offset: 2px;
}
#incoming {
border-style: solid;
font-size: var(--text-sm);
color: var(--color-text-muted);
}
#incoming button {
margin-top: var(--space-2);
}
[type='file'] {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.dropzone.dragover {
border-color: var(--accent);
background: var(--accent-soft);
label strong,
#incoming strong {
color: var(--color-text);
overflow-wrap: anywhere;
}
.progress {
height: 10px;
background: var(--bg);
border-radius: 6px;
/* A dropped folder, refused */
#not-a-file {
color: var(--color-secondary-text);
overflow-wrap: anywhere;
}
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
green once done, muted once stopped, pink for an error. The line below says what. */
[data-phase] {
--bar: var(--color-primary);
display: flex;
flex-direction: column;
gap: var(--space-2);
}
[data-phase='retry'],
[data-phase='error'] {
--bar: var(--color-secondary);
}
[data-phase='done'] {
--bar: var(--color-success);
}
[data-phase='stopped'] {
--bar: var(--color-text-muted);
}
[data-phase] p {
display: flex;
justify-content: space-between;
gap: var(--space-3);
font-size: var(--text-sm);
font-variant-numeric: tabular-nums;
color: var(--color-text-muted);
}
/* The send session's file, above its bar once the user picked another one */
#send-file {
color: var(--color-text);
font-weight: 600;
overflow-wrap: anywhere;
}
/* A block, a flex container has no first letter. Flex items do, they are blocks. */
[data-phase] p[role='alert'] {
display: block;
color: var(--color-secondary-text);
}
[data-phase] p[role='alert']::first-letter,
[data-phase] [role='status'] > :first-child::first-letter {
text-transform: uppercase;
}
/* The track, the progress inside it fills it or, without a value, is the pill */
[data-phase] > div {
height: 0.5rem;
border-radius: 999px;
background: var(--color-input);
overflow: hidden;
}
.progress > div {
progress {
display: block;
width: 100%;
height: 100%;
background: var(--accent);
transition: width 0.15s linear;
appearance: none;
border: none;
background: none;
}
.status {
color: var(--muted);
font-size: 0.85rem;
progress::-webkit-progress-bar {
background: none;
}
.error {
color: #ff6b5e;
font-size: 0.85rem;
progress::-webkit-progress-value {
background: var(--bar);
}
.file-chip {
progress::-moz-progress-bar {
background: var(--bar);
}
progress:indeterminate {
width: 25%;
border-radius: 999px;
background: var(--bar);
animation: pass 2584ms linear infinite;
}
progress:indeterminate::-moz-progress-bar {
background: none;
}
/* Its own width is a quarter of the track's: from just before it to just past it */
@keyframes pass {
from {
translate: -100%;
}
to {
translate: 400%;
}
}
@media (prefers-reduced-motion: reduce) {
progress:indeterminate {
translate: 150%;
animation: none;
}
}
/* Switch, like Pico's role="switch" */
label:has([role='switch']) {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.6rem 0.9rem;
font-size: 0.9rem;
gap: var(--space-2);
cursor: pointer;
}
a.download {
color: var(--accent);
[role='switch'] {
appearance: none;
width: 2.25rem;
height: 1.25rem;
padding: 0;
border-radius: 999px;
background: var(--color-border);
border: none;
cursor: pointer;
position: relative;
transition: background-color var(--transition);
}
[role='switch']::before {
content: '';
position: absolute;
inset: 0.125rem auto 0.125rem 0.125rem;
aspect-ratio: 1;
border-radius: 50%;
background: var(--color-text);
transition: translate var(--transition);
}
[role='switch']:checked {
background: var(--color-success);
}
[role='switch']:checked::before {
translate: 1rem 0;
}
/* Security check callout */
aside {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-4);
padding: var(--space-4) var(--space-6);
background: color-mix(in srgb, var(--color-secondary) 8%, var(--color-surface));
border: 1px solid var(--color-secondary);
border-radius: var(--radius);
}
aside p {
flex: 1 1 100%;
}
/* Monospaced in a grid, so both codes line up byte by byte */
aside dl {
flex: 1 1 auto;
display: grid;
grid-template-columns: auto auto;
justify-content: start;
column-gap: var(--space-3);
}
aside dt {
color: var(--color-text-muted);
}
aside div {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
aside button + button {
background: transparent;
border-color: var(--color-border);
color: var(--color-text);
}
aside button + button:hover {
background: var(--color-border);
}
output {
color: var(--color-secondary-text);
font-family: ui-monospace, monospace;
font-weight: 600;
}
.fingerprint {
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.75rem 0.9rem;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.fp-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
font-size: 0.9rem;
}
.fp-row code {
font-family: ui-monospace, monospace;
color: var(--accent);
letter-spacing: 0.12em;
}
.fingerprint .status {
margin: 0.2rem 0 0;
}
/* Source link, quiet below everything */
footer {
max-width: 680px;
width: 100%;
margin: 1.5rem 0 2.5rem;
padding: 0 0.25rem;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.55;
}
footer p {
margin: 0;
}
.stun-select,
.stun-input {
width: 100%;
background: var(--bg);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.55rem 0.75rem;
font-size: 0.95rem;
font-family: inherit;
}
.stun-input {
font-family: ui-monospace, monospace;
font-size: 0.85rem;
}
.stun-select:focus,
.stun-input:focus {
outline: none;
border-color: var(--accent);
}
p.stun-hint {
margin: -0.35rem 0 0;
font-size: 0.78rem;
}
.network-settings {
display: flex;
flex-direction: column;
gap: 0.7rem;
border: 1px solid var(--border);
border-radius: 8px;
min-width: 0;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: var(--space-2) var(--space-4);
padding-bottom: var(--space-6);
font-size: var(--text-sm);
color: var(--color-text-muted);
}
footer a {
display: inline-flex;
align-items: center;
gap: var(--space-2);
color: var(--color-text-muted);
text-decoration: none;
transition: color var(--transition);
}
footer a:hover {
color: var(--color-text);
}
footer img {
filter: grayscale(1);
opacity: 0.6;
transition: opacity var(--transition);
}
footer a:hover img {
opacity: 0.9;
}
/* Servers */
#servers > div {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
justify-items: start;
gap: var(--space-4);
padding: var(--space-4) var(--space-6) var(--space-6);
border-top: 1px solid var(--color-border);
}
#servers section {
justify-self: stretch;
padding-top: 0;
border-top: none;
}
#servers p {
overflow-wrap: anywhere;
}
[aria-invalid='true'] {
border-color: var(--color-secondary);
}
/* Log */
summary {
padding: var(--space-3) var(--space-6);
font-weight: 600;
cursor: pointer;
}
pre {
max-height: 20rem;
overflow: auto;
padding: var(--space-4) var(--space-6);
border-top: 1px solid var(--color-border);
font-size: var(--text-sm);
color: var(--color-text-muted);
}
.network-settings legend { color: var(--muted); }
.checkbox { display: flex; align-items: start; gap: 0.6rem; }
.fp-row { flex-direction: column; align-items: start; }
.fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; }
.file-chip span { overflow-wrap: anywhere; min-width: 0; }
.incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; }
-89
View File
@@ -1,89 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { iceMiddleware } from '../dev/ice-server.ts';
import { fetchTurnOptions } from '../src/lib/webrtc.ts';
interface Credentials {
expiresAt: number;
iceServers: [{ urls: string }, { urls: string[]; username: string; credential: string }];
}
interface ResponseResult {
status: number;
headers: Record<string, string>;
body?: Credentials;
next?: boolean;
}
function request(handler: ReturnType<typeof iceMiddleware>, { method = 'GET', url = '/api/ice-servers', headers = { host: '127.0.0.1:5173' } }: { method?: string; url?: string; headers?: Record<string, string> } = {}) {
const result: ResponseResult = { status: 200, headers: {} };
handler({ method, url, headers }, {
setHeader(key, value) { result.headers[key] = value; },
writeHead(status, headers) { result.status = status; Object.assign(result.headers, headers); },
end(body) { result.body = body ? JSON.parse(body) : undefined; },
}, () => { result.next = true; });
return result;
}
test('temporary credentials match coturn HMAC, expire in an hour and never expose the secret', () => {
const secret = 'test-only-secret';
const handler = iceMiddleware({ TURN_SECRET: secret });
const first = request(handler), second = request(handler);
assert.equal(first.headers['Cache-Control'], 'no-store');
assert.ok(first.body); assert.ok(second.body);
const { expiresAt, iceServers } = first.body;
const turn = iceServers[1];
assert.ok(Math.abs(expiresAt - Date.now() / 1000 - 3600) < 2);
assert.ok(turn.username.startsWith(`${expiresAt}:`));
assert.notEqual(turn.username, second.body.iceServers[1].username);
assert.equal(turn.credential, createHmac('sha1', secret).update(turn.username).digest('base64'));
assert.deepEqual(turn.urls, ['turn:127.0.0.1:3478?transport=udp', 'turn:127.0.0.1:3478?transport=tcp']);
assert.ok(!JSON.stringify(first.body).includes(secret));
});
test('development endpoint rejects cross-site issuance and unsupported methods', () => {
assert.throws(() => iceMiddleware({}), /TURN_SECRET/);
const handler = iceMiddleware({ TURN_SECRET: 'test' });
assert.equal(request(handler, { method: 'POST' }).status, 405);
assert.equal(request(handler, { headers: { 'sec-fetch-site': 'cross-site' } }).status, 403);
assert.equal(request(handler, { headers: { host: 'localhost', origin: 'http://elsewhere' } }).status, 403);
assert.equal(request(handler, { url: '/other' }).next, true);
});
test('managed credentials require opt-in, refresh each connection, and fail closed', async () => {
let calls = 0;
const handler = iceMiddleware({ TURN_SECRET: 'test' });
const fetchImpl = async () => { calls++; return { ok: true, json: async () => request(handler).body }; };
await fetchTurnOptions({ managedTurn: true }, '/api/ice-servers', { fetchImpl });
await fetchTurnOptions({ allowTurn: true, managedTurn: false }, '/api/ice-servers', { fetchImpl });
assert.equal(calls, 0);
const options = { allowTurn: true, managedTurn: true, stunUrl: null };
const first = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
const second = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
assert.equal(calls, 2);
assert.notEqual(first.username, second.username);
assert.equal(first.stunUrl, null, 'User STUN choice must be preserved');
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: false, json: async () => null }) }), /Could not obtain/);
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: true, json: async () => ({ expiresAt: 1, iceServers: [] }) }) }), /expired/);
const controller = new AbortController(); controller.abort();
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { signal: controller.signal, fetchImpl: async (_url, { signal }) => { signal?.throwIfAborted(); throw new Error('Expected abort'); } }), { name: 'AbortError' });
});
test('managed credentials reject malformed response shapes and non-string credentials', async () => {
const expiresAt = Date.now() / 1000 + 3600;
const turn = { urls: 'turn:localhost:3478', username: 'user', credential: 'password' };
for (const body of [
null,
[],
{ expiresAt, iceServers: {} },
{ expiresAt, iceServers: [null] },
{ expiresAt, iceServers: [{ ...turn, urls: [null] }] },
{ expiresAt, iceServers: [{ ...turn, urls: [] }] },
{ expiresAt, iceServers: [{ ...turn, username: 123 }] },
{ expiresAt, iceServers: [{ ...turn, credential: {} }] },
{ expiresAt, iceServers: [{ ...turn, urls: 'turn:bad host' }] },
]) {
await assert.rejects(fetchTurnOptions({ allowTurn: true, managedTurn: true }, '/api/ice-servers', {
fetchImpl: async () => ({ ok: true, json: async () => body }),
}), /credentials|TURN opt-in/);
}
});
-227
View File
@@ -1,227 +0,0 @@
import test, { type TestContext } from 'node:test';
import type { TransferChannel, TransferOptions, TransferResult } from '../src/lib/transfer.ts';
import assert from 'node:assert/strict';
import { Transfer, MEMORY_LIMIT, FILE_LIMIT, validateMetadata } from '../src/lib/transfer.ts';
import { CHUNK_SIZE, MAX_BUFFERED } from '../src/lib/webrtc.ts';
class Channel extends EventTarget implements TransferChannel {
binaryType: BinaryType = 'arraybuffer';
bufferedAmountLowThreshold = 0;
peer: Channel | null = null;
onopen: TransferChannel['onopen'] = null;
onmessage: TransferChannel['onmessage'] = null;
onclose: TransferChannel['onclose'] = null;
onerror: (() => void) | null = null;
readyState: RTCDataChannelState = 'open';
bufferedAmount = 0;
frames: (string | ArrayBuffer)[] = [];
send(data: string | ArrayBuffer) {
if (this.readyState !== 'open') throw new Error('closed');
this.frames.push(data);
queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data })));
}
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
}
const tick = () => new Promise<void>(resolve => setImmediate(resolve));
async function until(check: () => boolean) {
for (let i = 0; i < 500; i++) { if (check()) return; await tick(); }
assert.fail('Condition did not become true');
}
const message = (transfer: Transfer, type: string, data: Record<string, unknown> = {}) => transfer.enqueue(JSON.stringify({ v: 2, type, ...data }));
const meta = (size = 1) => ({ name: 'example.txt', size, mime: 'text/plain' });
function receiver(t: TestContext, options: TransferOptions = {}) {
const dc = new Channel();
const errors: string[] = [];
const r = new Transfer(dc, { onError: err => errors.push(err.message), ...options });
t.after(() => r.close());
return { r, dc, errors };
}
async function prepared(t: TestContext, size = 1, options: TransferOptions = {}) {
const result = receiver(t, options);
result.r.verify(); message(result.r, 'ready'); message(result.r, 'meta', meta(size));
await result.r.queue;
assert.equal(result.r.state, 'choose-storage');
return result;
}
function pair(t: TestContext, size = CHUNK_SIZE * 80 + 3, receiverOptions: TransferOptions = {}) {
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
const source = new Uint8Array(size); source.fill(123);
const file = new File([source], 'payload.bin');
const errors: string[] = [];
const sender = new Transfer(a, { file, onError: err => errors.push(err.message) });
const receiver = new Transfer(b, { onError: err => errors.push(err.message), ...receiverOptions });
t.after(() => { sender.close(); receiver.close(); });
return { sender, receiver, a, b, source, errors };
}
test('no filename or contents before both explicit verification confirmations', async t => {
const { sender, receiver, a } = pair(t);
await tick(); assert.equal(a.frames.length, 0);
sender.verify(); await tick();
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready']);
receiver.verify(); await until(() => receiver.state === 'choose-storage');
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready', 'meta']);
assert.equal(sender.sent, 0);
});
test('verified, accepted memory transfer preserves bytes and requires receipt ACK', async t => {
let result: TransferResult | undefined;
const { sender, receiver, source, errors } = pair(t, undefined, { onComplete: value => { result = value; } });
sender.verify(); receiver.verify();
await until(() => receiver.state === 'choose-storage'); receiver.accept();
await until(() => sender.state === 'done');
assert.deepEqual(errors, []);
assert.ok(result?.blob);
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), source);
assert.equal(sender.acked, source.length);
assert.equal(result.blob.type, 'application/octet-stream');
});
test('empty file still requires acceptance and completion ACK', async t => {
const { sender, receiver } = pair(t, 0);
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
assert.equal(sender.state, 'waiting-accept');
receiver.accept(); await until(() => sender.state === 'done');
});
test('disk transfer waits for storage close before acknowledging completion', async t => {
let release: (() => void) | undefined, saved = 0;
const { sender, receiver, source } = pair(t);
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
receiver.accept({ async write(bytes) { saved += bytes.byteLength; }, close() { return new Promise<void>(resolve => { release = resolve; }); }, async abort() {} });
await until(() => receiver.state === 'saving');
assert.equal(sender.state, 'awaiting-receipt'); assert.equal(saved, source.length);
assert.ok(release); release(); await until(() => sender.state === 'done');
});
test('slow storage bounds the sender to its acknowledged window', async t => {
let release: (() => void) | undefined;
const { sender, receiver } = pair(t);
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
receiver.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
await until(() => sender.sent === MAX_BUFFERED);
await tick(); assert.equal(sender.acked, 0); assert.equal(sender.sent, MAX_BUFFERED);
receiver.close(); sender.close(); release?.();
});
for (const [name, input] of [
['malformed JSON', '{broken'],
['null JSON', 'null'],
['binary data before verification', new ArrayBuffer(1)],
['oversized binary message', new ArrayBuffer(CHUNK_SIZE + 1)],
['oversized control message', ' '.repeat(2049)],
['metadata before verification', JSON.stringify({ v: 2, type: 'meta', ...meta() })],
['unsupported message object', {}],
]) {
test(`rejects ${name}`, async t => {
const { r, errors } = receiver(t); r.enqueue(input); await r.queue;
assert.equal(r.closed, true); assert.equal(errors.length, 1);
});
}
test('rejects duplicate metadata without retaining bytes from another file', async t => {
const { r } = await prepared(t); r.accept(); r.enqueue(new ArrayBuffer(1));
message(r, 'meta', meta()); await r.queue;
assert.equal(r.closed, true); assert.equal(r.chunks.length, 0);
});
test('rejects excess bytes and premature end', async t => {
const first = await prepared(t); first.r.accept(); first.r.enqueue(new ArrayBuffer(2)); await first.r.queue;
assert.equal(first.r.closed, true);
const second = await prepared(t, 2); second.r.accept(); second.r.enqueue(new ArrayBuffer(1)); message(second.r, 'end'); await second.r.queue;
assert.equal(second.r.closed, true);
});
test('completed files cannot be extended by later frames', async t => {
let completes = 0;
const { r } = await prepared(t, 1, { onComplete: () => completes++ });
r.accept(); r.enqueue(new ArrayBuffer(1)); message(r, 'end'); await r.queue;
assert.equal(r.state, 'done'); r.enqueue(new ArrayBuffer(1)); await r.queue;
assert.equal(r.closed, true); assert.equal(completes, 1);
});
test('post-completion transport errors preserve the received file (Firefox shutdown)', async t => {
let result: TransferResult | undefined;
const { r, dc, errors } = await prepared(t, 1, { onComplete: value => { result = value; } });
r.accept(); r.enqueue(Uint8Array.of(123).buffer); message(r, 'end'); await r.queue;
assert.equal(r.state, 'done');
dc.onerror?.();
assert.equal(r.state, 'done'); assert.equal(r.closed, true);
assert.deepEqual(errors, []);
assert.ok(result?.blob);
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), Uint8Array.of(123));
});
test('transport errors before receipt completion remain fatal', async t => {
const { r, dc, errors } = await prepared(t, 1);
r.accept(); r.enqueue(new ArrayBuffer(1)); await r.queue;
dc.onerror?.();
assert.equal(r.state, 'closed'); assert.equal(r.chunks.length, 0);
assert.deepEqual(errors, ['Data channel failed.']);
});
test('memory limit requires an explicit disk destination for larger files', async t => {
const { r } = await prepared(t, MEMORY_LIMIT + 1);
assert.throws(() => r.accept(), /direct-to-disk/);
assert.equal(r.state, 'choose-storage');
});
test('metadata rejects invalid sizes, misleading names and invalid types', () => {
for (const size of [-1, 0.5, '10', NaN, Infinity, FILE_LIMIT + 1]) assert.throws(() => validateMetadata({ ...meta(), size }));
for (const name of ['', '../secret', 'a\\b', 'bad\u202efile.exe', 'a'.repeat(256)]) assert.throws(() => validateMetadata({ ...meta(), name }));
assert.throws(() => validateMetadata({ ...meta(), mime: {} }));
});
test('cancellation aborts pending disk writes and drops retained buffers', async t => {
let aborted = false;
let release: (() => void) | undefined;
const { r } = await prepared(t);
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { aborted = true; release?.(); } });
r.enqueue(new ArrayBuffer(1)); await tick(); r.close(); await r.queue;
assert.equal(aborted, true); assert.equal(r.chunks.length, 0); assert.equal(r.received, 0);
});
test('peer flooding exceeds bounded queue and aborts storage', async t => {
let release: (() => void) | undefined;
const { r } = await prepared(t, MEMORY_LIMIT);
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
r.enqueue(new ArrayBuffer(CHUNK_SIZE)); await tick();
for (let i = 0; i < 130; i++) r.enqueue(new ArrayBuffer(CHUNK_SIZE));
assert.equal(r.closed, true); release?.(); await r.queue;
});
test('stalled transfers time out rather than reporting completion', async t => {
const { r, errors } = await prepared(t, 1, { timeout: 10 });
r.accept(); await new Promise<void>(resolve => setTimeout(resolve, 30));
assert.equal(r.closed, true); assert.match(errors[0], /timed out/);
});
test('storage failure never sends successful receipt', async t => {
const { r, dc } = await prepared(t);
r.accept({ async write() { throw new Error('Disk full'); }, async close() {}, async abort() {} });
r.enqueue(new ArrayBuffer(1)); message(r, 'end'); await r.queue;
assert.equal(r.closed, true); assert.equal(dc.frames.some(frame => typeof frame === 'string' && JSON.parse(frame).type === 'complete'), false);
});
test('tiny chunks cannot bypass the memory cap through per-chunk overhead', async t => {
const { r, errors } = await prepared(t, CHUNK_SIZE * 2);
r.accept(); r.enqueue(new ArrayBuffer(1)); await r.queue;
assert.equal(r.closed, true); assert.match(errors[0], /chunk size/);
});
test('forged completion or invalid byte acknowledgments cannot report success', async t => {
const first = pair(t);
first.sender.verify(); first.receiver.verify();
await until(() => first.receiver.state === 'choose-storage');
message(first.sender, 'complete', { bytes: first.source.length }); await first.sender.queue;
assert.equal(first.sender.state, 'closed');
const second = pair(t);
second.sender.verify(); second.receiver.verify();
await until(() => second.receiver.state === 'choose-storage');
// Accept without allowing the real receiver to process file data, then forge an ACK.
second.b.onmessage = null;
message(second.sender, 'accept');
await until(() => second.sender.sent >= CHUNK_SIZE);
message(second.sender, 'ack', { bytes: 1 }); await second.sender.queue;
assert.equal(second.sender.state, 'closed');
});
-64
View File
@@ -1,64 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { iceConfiguration, validateDescription, getFingerprints, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts';
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':');
const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
test('TURN is absent by default and dormant credentials cannot enable it', () => {
assert.deepEqual(iceConfiguration(), { iceServers: [] });
const settings = { stunUrl: 'stun:example.com:3478', turnUrl: 'turn:relay.example', username: 'user', credential: 'secret' };
assert.equal(iceConfiguration(settings).iceServers.length, 1);
assert.equal(iceConfiguration({ ...settings, allowTurn: true }).iceServers.length, 2);
assert.throws(() => iceConfiguration({ stunUrl: 'turn:relay.example' }));
assert.throws(() => iceConfiguration({ allowTurn: true }));
});
test('remote relay candidates require local explicit opt-in', () => {
const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n';
assert.throws(() => decodeSignal(encodeSignal(relayed)), /explicitly enable TURN/);
assert.equal(decodeSignal(encodeSignal(relayed), { allowTurn: true }), relayed);
});
test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
const expected = fingerprint.toUpperCase().replaceAll(':', ' ');
assert.equal(validateDescription(sdp), expected);
assert.deepEqual(getFingerprints({ localDescription: { sdp }, remoteDescription: { sdp } }), { local: expected, remote: expected });
assert.throws(() => validateDescription(sdp + `a=fingerprint:sha-256 ${fingerprint}\r\n`));
assert.throws(() => validateDescription(sdp.replace(fingerprint, 'AA:BB:CC:DD:EE')));
assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n'));
});
test('signals round-trip but reject legacy, malformed and oversized codes', () => {
assert.equal(decodeSignal(encodeSignal(sdp)), sdp);
assert.throws(() => decodeSignal(btoa(sdp)));
assert.throws(() => decodeSignal('bad!'));
assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1)));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 1, sdp }))));
});
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }
test('ICE gathering waits for completion, rejects timeout, and supports cancellation', async () => {
const pc = new Peer();
const completed = waitForIceComplete(pc, { timeout: 100 });
pc.iceGatheringState = 'complete'; pc.dispatchEvent(new Event('icegatheringstatechange')); await completed;
await assert.rejects(waitForIceComplete(new Peer(), { timeout: 5 }), /timed out/);
const controller = new AbortController();
const cancelled = waitForIceComplete(new Peer(), { signal: controller.signal }); controller.abort();
await assert.rejects(cancelled, /cancelled/);
});
test('buffer wait resolves when already drained and rejects close or cancellation', async () => {
const channel = new class extends EventTarget {
readyState: RTCDataChannelState = 'open';
bufferedAmount = 0;
bufferedAmountLowThreshold = 0;
}();
await waitForBufferDrain(channel);
channel.bufferedAmount = MAX_BUFFERED + 1;
const wait = waitForBufferDrain(channel); channel.readyState = 'closed'; channel.dispatchEvent(new Event('close'));
await assert.rejects(wait, /interrupted/);
channel.readyState = 'open'; const controller = new AbortController();
const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort();
await assert.rejects(cancelled, /interrupted/);
});
+10 -9
View File
@@ -1,19 +1,20 @@
{
"compilerOptions": {
"target": "ES2023",
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["node", "vite/client"],
"moduleResolution": "bundler",
"types": ["vite/client"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"erasableSyntaxOnly": true,
"skipLibCheck": true
"skipLibCheck": true,
"allowJs": true,
"noEmit": true
},
"include": ["src/**/*.ts", "src/**/*.vue", "dev/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "vite.config.ts"]
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "playwright.config.ts", "e2e.spec.ts"]
}
+26 -14
View File
@@ -1,18 +1,30 @@
import { defineConfig, loadEnv } from 'vite';
/// <reference types="vitest/config" />
import vue from '@vitejs/plugin-vue';
import { iceMiddleware } from './dev/ice-server.ts';
import { defineConfig } from 'vite';
// base './' so the built app can be served from any static path (or opened from a subdirectory)
export default defineConfig(({ mode }) => {
const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env };
return {
base: './',
server: { host: '127.0.0.1' },
plugins: [vue(), {
name: 'local-turn-credentials',
configureServer(server) {
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
const DEV_STYLE_SRC = "style-src 'self'";
export default defineConfig({
plugins: [
vue(),
// index.html's Content-Security-Policy allows no inline styles, the dev server injects the CSS
// through JavaScript. A nonce lets only those style elements through, so the dev server enforces
// the same policy as the production build, which links the CSS as files.
{
name: 'dev-csp',
apply: 'serve',
config: () => ({ html: { cspNonce: 'dev' } }),
transformIndexHtml(html) {
if (!html.includes(DEV_STYLE_SRC)) throw new Error(`dev-csp: index.html has no "${DEV_STYLE_SRC}"`);
return html.replace(DEV_STYLE_SRC, `${DEV_STYLE_SRC} 'nonce-dev'`);
},
}],
};
},
],
// The dev server would inline small images like gitea.svg as data: URLs, which index.html's
// Content-Security-Policy blocks. The production build links them as files either way.
build: { assetsInlineLimit: 0 },
// Relative links, so the build works under any path, not only at the root of a host.
base: './',
// Playwright runs e2e.spec.ts and backend/, which Vitest would pick up too.
test: { include: ['src/**/*.test.ts'] },
});