Compare commits
13
Commits
2e47b55901
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c47047ddd | ||
|
|
1b2696b6b4 | ||
|
|
ac4d496a48 | ||
|
|
44a8a72261 | ||
|
|
870d55b44f | ||
|
|
af0a8c9fee | ||
|
|
7f4811485a | ||
|
|
b102e55495 | ||
|
|
ae1e3bef9b | ||
|
|
ae871a2647 | ||
|
|
8f82700736 | ||
|
|
f53d39ae69 | ||
|
|
aa61efcc10 |
No files matched your search
@@ -14,6 +14,10 @@ size limit: the file goes directly to the other person and is never stored on a
|
||||
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
|
||||
@@ -32,15 +36,15 @@ to the encryption keys of this very connection. Someone in between, or anyone el
|
||||
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
|
||||
short codes: **You** and **Peer**. Compare them with the other person over a channel you already
|
||||
trust, ideally a call or in person:
|
||||
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 few seconds to really compare them.
|
||||
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.
|
||||
@@ -63,8 +67,11 @@ On the receiving side, HellCon hands the incoming data to the browser's own down
|
||||
it arrives. That's why files larger than your memory work too, and why the download shows up in
|
||||
your browser's download list.
|
||||
|
||||
There is 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.
|
||||
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.
|
||||
|
||||
## Privacy
|
||||
|
||||
@@ -73,7 +80,9 @@ networks, a direct connection may not be possible.
|
||||
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.
|
||||
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).
|
||||
@@ -109,18 +118,56 @@ Then serve the `dist/` folder, with these requirements:
|
||||
- **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`.
|
||||
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 first two keep other sites from framing HellCon and laying their own page over its buttons,
|
||||
`X-Frame-Options` for older browsers.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Not planned
|
||||
|
||||
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.
|
||||
|
||||
- **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.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -2,13 +2,6 @@
|
||||
|
||||
## Ideas
|
||||
|
||||
- Unstick a wrong salt: while a tracker share or search runs, the salt is locked, and a receiver
|
||||
told "Check the code and the salt" can't change it for up to 6 minutes. The receiver doesn't need
|
||||
the lock: like the code field, the salt could stay editable and count from the next Receive
|
||||
(`saltLocked` only for `side === 'send'`). The sender does, the code shown must match the salt
|
||||
shown: a Stop button next to the valid code would end the share, unlock the salt and also let a
|
||||
share be withdrawn early. Changing the salt itself shouldn't end a share, a stray click would.
|
||||
|
||||
- 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.
|
||||
@@ -17,13 +10,18 @@
|
||||
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.
|
||||
|
||||
- Version the protocol for 1.0: put a version into the key derivation, e.g. `hellcon/1 <salt>` as
|
||||
the PBKDF2 salt in `secrets`. Until then any change to it silently breaks sharing between
|
||||
deployments on different versions, the receiver only sees "No sender with this code". Open how a
|
||||
mismatch would be reported, e.g. by trying the previous version's swarm too.
|
||||
- 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
|
||||
|
||||
@@ -7,3 +7,8 @@ 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
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
FROM node:26.12.1-alpine3.23
|
||||
FROM node:26.13.1-alpine3.23
|
||||
WORKDIR /app
|
||||
RUN npm install --no-save --omit=dev ws@8.22.0
|
||||
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"]
|
||||
@@ -18,6 +18,12 @@ services:
|
||||
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]
|
||||
|
||||
+164
-17
@@ -1,8 +1,10 @@
|
||||
// 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.
|
||||
// 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().
|
||||
@@ -24,12 +26,36 @@ const MAX_MESSAGE = 16 * 1024;
|
||||
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.
|
||||
@@ -37,19 +63,51 @@ 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';
|
||||
|
||||
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
|
||||
// its own anyway. IPv6 counts by /64: a single host usually has a whole one, every address in it
|
||||
// would get MAX_PER_IP of its own. IPv4, also mapped to IPv6, counts as it is.
|
||||
// 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 ip = req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
||||
if (!ip?.includes(':') || ip.includes('.')) return ip;
|
||||
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) {
|
||||
@@ -62,16 +120,61 @@ function clientIp(req) {
|
||||
.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.
|
||||
// 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.bufferedAmount + bytes <= MAX_QUEUED) return true;
|
||||
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) {
|
||||
@@ -88,6 +191,9 @@ function reject(peer, reason) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -101,6 +207,7 @@ function announce(peer, msg) {
|
||||
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;
|
||||
@@ -145,8 +252,20 @@ function announce(peer, msg) {
|
||||
}
|
||||
}
|
||||
|
||||
function open(ws) {
|
||||
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
|
||||
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.
|
||||
@@ -167,6 +286,8 @@ function open(ws) {
|
||||
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);
|
||||
@@ -181,7 +302,22 @@ function open(ws) {
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
|
||||
export const server = createServer((_, res) => res.writeHead(404).end());
|
||||
// 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.
|
||||
@@ -189,16 +325,27 @@ server.on('upgrade', (req, socket, head) => {
|
||||
const ip = clientIp(req);
|
||||
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
|
||||
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
|
||||
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
||||
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++;
|
||||
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
||||
used.open++;
|
||||
used.connects++;
|
||||
socket.once('close', () => {
|
||||
connections--;
|
||||
const left = perIp.get(ip) - 1;
|
||||
if (left) perIp.set(ip, left);
|
||||
else perIp.delete(ip);
|
||||
used.open--;
|
||||
});
|
||||
wss.handleUpgrade(req, socket, head, 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);
|
||||
+165
-3
@@ -7,6 +7,7 @@ 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 = [];
|
||||
@@ -18,11 +19,23 @@ let tests = 0;
|
||||
test.beforeAll(async () => {
|
||||
process.env.PORT = '0';
|
||||
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
|
||||
const { server } = await import('./tracker.mjs');
|
||||
// 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}`;
|
||||
});
|
||||
@@ -33,14 +46,29 @@ test.afterEach(async () => {
|
||||
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 } = {}) {
|
||||
function open({ origin = ORIGIN, xff = ip } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': ip } });
|
||||
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', () => {
|
||||
@@ -278,6 +306,51 @@ test('limits the signaling forwarded per connection', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -310,6 +383,42 @@ test('drops a peer that stops reading', async () => {
|
||||
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 });
|
||||
@@ -334,6 +443,59 @@ test('counts IPv6 by /64, however it is written', async () => {
|
||||
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');
|
||||
|
||||
+61
-3
@@ -1,10 +1,13 @@
|
||||
{
|
||||
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
"files": { "includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg"] },
|
||||
"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" }
|
||||
@@ -13,8 +16,63 @@
|
||||
"rules": {
|
||||
"preset": "recommended",
|
||||
"nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" },
|
||||
"style": { "noNonNullAssertion": "off", "noDescendingSpecificity": "off" },
|
||||
"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" } } } }
|
||||
]
|
||||
}
|
||||
+382
-823
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,11 @@
|
||||
<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</title>
|
||||
</head>
|
||||
|
||||
+15
-12
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hellcon",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "1.0.2",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -11,25 +11,28 @@
|
||||
"typecheck": "vue-tsc",
|
||||
"lint": "biome check",
|
||||
"format": "biome check --write",
|
||||
"test": "playwright test",
|
||||
"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.44"
|
||||
"vue": "^3.5.45"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.5.15",
|
||||
"@playwright/test": "^1.64.1",
|
||||
"@types/node": "^26.6.5",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"@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.5",
|
||||
"vue-tsc": "^3.3.13",
|
||||
"ws": "8.22.0"
|
||||
"vite": "^8.3.8",
|
||||
"vitest": "^5.1.0",
|
||||
"vue-tsc": "^3.3.14",
|
||||
"ws": "8.23.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=26.12.1"
|
||||
"node": ">=26.13.1"
|
||||
},
|
||||
"packageManager": "pnpm@12.14.0"
|
||||
"packageManager": "pnpm@12.16.1"
|
||||
}
|
||||
@@ -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/**' });
|
||||
Generated
+639
-274
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
minimumReleaseAgeExclude:
|
||||
- ws@8.23.0
|
||||
+36
-11
@@ -1,14 +1,37 @@
|
||||
// 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/core.ts, it sees no other requests.
|
||||
// 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 open(id, { name, size }, port) {
|
||||
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 };
|
||||
@@ -22,7 +45,7 @@ function open(id, { name, size }, port) {
|
||||
const chunk = download.chunks.shift();
|
||||
if (chunk) {
|
||||
download.read += chunk.byteLength;
|
||||
// Every MiB, src/core.ts forwards it to the sender for its flow control window.
|
||||
// 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);
|
||||
@@ -30,18 +53,19 @@ function open(id, { name, size }, port) {
|
||||
return controller.enqueue(chunk);
|
||||
}
|
||||
controller.close();
|
||||
downloads.delete(id);
|
||||
forget(id);
|
||||
port.postMessage('finished');
|
||||
},
|
||||
// The user cancelled the download.
|
||||
cancel: () => {
|
||||
downloads.delete(id);
|
||||
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(
|
||||
@@ -57,17 +81,18 @@ function open(id, { name, size }, port) {
|
||||
port.postMessage('ready');
|
||||
}
|
||||
|
||||
// The page posts 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.
|
||||
// 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] }) => {
|
||||
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/core.ts.
|
||||
if (data.ping) return;
|
||||
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));
|
||||
downloads.delete(data.id);
|
||||
forget(data.id);
|
||||
download.port.postMessage('failed');
|
||||
} else {
|
||||
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
|
||||
@@ -77,7 +102,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => {
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const id = new URL(event.request.url).pathname.split('/').pop();
|
||||
// download/ itself is the empty page src/core.ts keeps open to hold this worker during a transfer.
|
||||
// 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' } }),
|
||||
|
||||
+118
-16
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue';
|
||||
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
|
||||
import {
|
||||
answerOffer,
|
||||
type Check,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
formatTime,
|
||||
type Incoming,
|
||||
type Phase,
|
||||
PROTOCOL,
|
||||
type ReceiveEvents,
|
||||
randomCode,
|
||||
receiveViaTracker,
|
||||
@@ -46,9 +47,23 @@ function isStun(url: string) {
|
||||
return stunChecks.get(url)!;
|
||||
}
|
||||
|
||||
// Every # starts a fragment, which WebSocket rejects even when empty.
|
||||
const isTracker = (url: string) =>
|
||||
URL.canParse(url) && ['ws:', 'wss:'].includes(new URL(url).protocol) && !url.includes('#');
|
||||
// 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) {
|
||||
@@ -91,7 +106,12 @@ const receiveCode = ref('');
|
||||
|
||||
const check = ref<Check>();
|
||||
const confirmed = ref(false);
|
||||
const log = ref<string[]>([]);
|
||||
// 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 }>();
|
||||
@@ -100,7 +120,12 @@ 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) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
|
||||
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;
|
||||
@@ -217,15 +242,35 @@ async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
file.value = (event.target as HTMLInputElement).files?.[0];
|
||||
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;
|
||||
file.value = event.dataTransfer?.files[0] ?? file.value;
|
||||
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) {
|
||||
@@ -277,15 +322,69 @@ function onReceive() {
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
|
||||
}
|
||||
|
||||
// The salt stays as it is while a tracker share or search runs: it found or waits in the swarm of the
|
||||
// salt it started with, another one shown would be the wrong one to give the receiver.
|
||||
const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stopped'].includes(phase.value!));
|
||||
// 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>
|
||||
<header>
|
||||
<div>
|
||||
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
||||
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
|
||||
<h1>HellCon</h1>
|
||||
</div>
|
||||
<div id="options">
|
||||
@@ -353,12 +452,13 @@ const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stoppe
|
||||
@dragleave="dragging = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<input type="file" @change="onPick" />
|
||||
<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>
|
||||
@@ -510,7 +610,8 @@ const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stoppe
|
||||
<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 #: {{ trackers.invalid.join(', ') }}
|
||||
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>
|
||||
@@ -519,14 +620,15 @@ const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stoppe
|
||||
|
||||
<details>
|
||||
<summary>Log</summary>
|
||||
<pre id="log">{{ log.join('\n') }}</pre>
|
||||
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
|
||||
</details>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||
<img src="/gitea.svg" alt="" width="20" height="20" />
|
||||
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
|
||||
Source code
|
||||
</a>
|
||||
<span>Protocol {{ PROTOCOL }}</span>
|
||||
</footer>
|
||||
</template>
|
||||
+1772
File diff suppressed because it is too large.
Load diff
+234
-216
@@ -1,3 +1,5 @@
|
||||
import { type Download, downloadsReady, startDownload } from './download';
|
||||
|
||||
export const DEFAULT_TRACKERS = [
|
||||
'wss://tracker.pagequit.net',
|
||||
'wss://tracker.webtorrent.dev',
|
||||
@@ -11,6 +13,10 @@ export const DEFAULT_STUN_SERVERS = [
|
||||
'stun:stun.nextcloud.com:443',
|
||||
];
|
||||
|
||||
// App.vue uses the settings and their defaults, PROTOCOL, randomCode, formatTime, the types and the
|
||||
// sessions at the end. src/core.test.ts also tests the other exports on their own, biome.json keeps them to it:
|
||||
// a new one goes on its list there.
|
||||
|
||||
// Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody.
|
||||
// Read whenever a connection or tracker socket is created, so changes apply to the next one.
|
||||
export const settings = {
|
||||
@@ -19,41 +25,56 @@ export const settings = {
|
||||
trackers: [...DEFAULT_TRACKERS],
|
||||
};
|
||||
|
||||
const CHUNK_SIZE = 16 * 1024;
|
||||
const MAX_BUFFERED = 1024 * 1024;
|
||||
export const CHUNK_SIZE = 16 * 1024;
|
||||
export const MAX_BUFFERED = 1024 * 1024;
|
||||
// The receiving side can't pause a data channel, so it reports how much the download manager has
|
||||
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM.
|
||||
const WINDOW = 8 * 1024 * 1024;
|
||||
// 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.
|
||||
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;
|
||||
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM. The
|
||||
// receiver holds the sender to it and CHUNK_SIZE, raising either takes a new PROTOCOL.
|
||||
export const WINDOW = 8 * 1024 * 1024;
|
||||
const ICE_GRACE = 300;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
// A STUN server that reports no public address by then gets passed over, see stunServer.
|
||||
// A STUN server that reports no public address by then gets passed over, see stunChoice.
|
||||
const PROBE_TIMEOUT = 2000;
|
||||
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
|
||||
const TRACKER_TIMEOUT = 10_000;
|
||||
export const TRACKER_TIMEOUT = 10_000;
|
||||
// A tracker relays one sealed SDP of a few KiB at a time, a larger message isn't parsed. The browser
|
||||
// has received it by then, nothing limits that: this only spares parsing and decrypting it.
|
||||
export const MAX_TRACKER_MESSAGE = 64 * 1024;
|
||||
// A tracker sends a few messages a minute, replies to announcements and the other side's SDP. Beyond
|
||||
// MAX_TRACKER_MESSAGES per MESSAGE_WINDOW the rest is dropped, a tracker can't keep the page busy.
|
||||
export const MAX_TRACKER_MESSAGES = 20;
|
||||
export const MESSAGE_WINDOW = 10_000;
|
||||
// What a tracker makes a socket log, each line once and at most this many: it can't fill the log.
|
||||
export const TRACKER_NOTES = 10;
|
||||
// A tracker peer that got an answer but never opens the data channel gives up its turn after this,
|
||||
// e.g. one whose SDP has no usable candidates: Chromium never even fails its connection. The manual
|
||||
// sender gives up on the answer after it as well.
|
||||
const CONNECT_TIMEOUT = 30_000;
|
||||
export const CONNECT_TIMEOUT = 30_000;
|
||||
// A share, or a receiver looking for one, gives up after this without a download: nobody announces
|
||||
// all day for a code nobody uses. Until then both announce again on the interval the tracker names,
|
||||
// else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names.
|
||||
// The manual receiver waits this long for the sender to connect, it has to get the answer first.
|
||||
export const TRACKER_WAIT = 6 * 60_000;
|
||||
const MIN_INTERVAL = 30_000;
|
||||
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
|
||||
const PBKDF2_ITERATIONS = 600_000;
|
||||
export const MIN_INTERVAL = 30_000;
|
||||
// OWASP's recommendation for PBKDF2-SHA-256. Changing it takes a new PROTOCOL.
|
||||
export const PBKDF2_ITERATIONS = 600_000;
|
||||
// Goes into the key derivation, see secrets: sides on different versions end up in different swarms
|
||||
// and never meet, the receiver only finds no sender. The manual exchange has no derivation, the data
|
||||
// channel's label carries it there and the side it reaches checks it. The page shows it, so the two
|
||||
// can compare. Every change that breaks sharing between versions takes a new one: the code and its
|
||||
// salt, the derivation, the signaling, the data channel's messages and its flow control. A fork that
|
||||
// changes any of them takes a name of its own, two forks would otherwise share a version that means
|
||||
// different things.
|
||||
export const PROTOCOL = 'hellcon/1';
|
||||
// A tracker peer that connects but proves no code gives up its turn after this. Signing takes
|
||||
// milliseconds, a peer that knows the code is never near it.
|
||||
const PROOF_TIMEOUT = 10_000;
|
||||
export const PROOF_TIMEOUT = 10_000;
|
||||
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
|
||||
const MAX_NAME = 1024;
|
||||
export const MAX_NAME = 1024;
|
||||
// Controls and line separators in an offered name could fake log lines, bidi controls disguise its
|
||||
// extension: invoice\u202Efdp.exe shows as invoiceexe.pdf. They go before the name is shown, logged
|
||||
// or saved.
|
||||
const HIDDEN = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu;
|
||||
|
||||
export type Check = {
|
||||
local: string;
|
||||
@@ -101,7 +122,7 @@ export type ReceiveEvents = Events & {
|
||||
|
||||
// Closes it once the session ends, right away if it already did. Closing it earlier lets go of it, else
|
||||
// the session would keep every connection a rejected or failed peer left behind until it ends.
|
||||
function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
|
||||
export function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
|
||||
const closeResource = resource.close.bind(resource);
|
||||
// Without the abort event, WebSocket.close() would take it for a close code and throw.
|
||||
const close = () => closeResource();
|
||||
@@ -115,14 +136,14 @@ function own<T extends { close: () => void }>(signal: AbortSignal, resource: T)
|
||||
}
|
||||
|
||||
// Closing everything fires events of its own, none of them reaches the caller after the abort.
|
||||
function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
|
||||
export function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
|
||||
) as T;
|
||||
}
|
||||
|
||||
// Runs expire after ms unless closed before, cleared with the session.
|
||||
function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
|
||||
export function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
|
||||
const timer = setTimeout(() => {
|
||||
owned.close();
|
||||
expire();
|
||||
@@ -158,7 +179,18 @@ async function probe(url: string, stop: AbortSignal) {
|
||||
}
|
||||
}
|
||||
|
||||
// Probes list in order from start on, the ones before start last, see stunServer.
|
||||
// Each connection uses one STUN server, so only that one learns the address: the first in the list
|
||||
// that reports one. It stays for the page's lifetime, unless a connection gets no address from it,
|
||||
// then the next connection probes on from the server after it. A changed list starts over. None, or
|
||||
// none reporting an address, means connections without STUN. A device with a public address of its
|
||||
// own gets none reported (browsers drop it as redundant) and probes them all for every connection.
|
||||
// The page has one, see stun, a test makes its own with a probe of its own.
|
||||
export function stunChoice(answers = probe) {
|
||||
let current: ReturnType<typeof probeFrom> | undefined;
|
||||
// Where the next probe of the list with key starts, if not at its first server.
|
||||
let resume: { key: string; at: number } | undefined;
|
||||
|
||||
// Probes list in order from start on, the ones before start last.
|
||||
function probeFrom(list: string[], start: number) {
|
||||
const key = list.join('\n');
|
||||
const stop = new AbortController();
|
||||
@@ -169,7 +201,7 @@ function probeFrom(list: string[], start: number) {
|
||||
for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) {
|
||||
// No further server is contacted once nobody waits, STUN was turned off or the list changed.
|
||||
if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return;
|
||||
if (await probe(list[at]!, stop.signal)) return list[at];
|
||||
if (await answers(list[at]!, stop.signal)) return list[at];
|
||||
}
|
||||
})().finally(() => (settled = true));
|
||||
const choice = {
|
||||
@@ -199,40 +231,36 @@ function probeFrom(list: string[], start: number) {
|
||||
};
|
||||
// E.g. offline, the next connection probes again.
|
||||
void server.then((url) => {
|
||||
if (!url && stun === choice) stun = undefined;
|
||||
if (!url && current === choice) current = undefined;
|
||||
});
|
||||
return choice;
|
||||
}
|
||||
|
||||
let stun: ReturnType<typeof probeFrom> | undefined;
|
||||
// Where the next probe of the list with key starts, if not at its first server.
|
||||
let resume: { key: string; at: number } | undefined;
|
||||
|
||||
// Each connection uses one STUN server, so only that one learns the address: the first in the list
|
||||
// that reports one. It stays for the page's lifetime, unless a connection gets no address from it,
|
||||
// then the next connection probes on from the server after it. A changed list starts over. None, or
|
||||
// none reporting an address, means connections without STUN. A device with a public address of its
|
||||
// own gets none reported (browsers drop it as redundant) and probes them all for every connection.
|
||||
function stunServer(signal: AbortSignal) {
|
||||
return {
|
||||
// The server for a connection of the session with signal, if any.
|
||||
server(signal: AbortSignal) {
|
||||
if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined);
|
||||
const key = settings.stunServers.join('\n');
|
||||
if (stun?.key !== key || stun.stopped) {
|
||||
stun = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
|
||||
if (current?.key !== key || current.stopped) {
|
||||
current = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
|
||||
resume = undefined;
|
||||
}
|
||||
return stun.wait(signal);
|
||||
return current.wait(signal);
|
||||
},
|
||||
// A connection got no public address from url.
|
||||
async failed(url: string) {
|
||||
const choice = current;
|
||||
if (!choice || (await choice.server) !== url || current !== choice) return;
|
||||
resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length };
|
||||
current = undefined;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// A connection got no public address from url.
|
||||
async function stunFailed(url: string) {
|
||||
const choice = stun;
|
||||
if (!choice || (await choice.server) !== url || stun !== choice) return;
|
||||
resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length };
|
||||
stun = undefined;
|
||||
}
|
||||
const stun = stunChoice();
|
||||
|
||||
async function createPeerConnection(signal: AbortSignal) {
|
||||
const server = await stunServer(signal);
|
||||
const server = await stun.server(signal);
|
||||
return own(signal, new RTCPeerConnection({ iceServers: server ? [{ urls: server }] : [] }));
|
||||
}
|
||||
|
||||
@@ -241,7 +269,7 @@ async function createPeerConnection(signal: AbortSignal) {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above
|
||||
type Message = Record<string, any>;
|
||||
|
||||
function parse(data: unknown): Message | undefined {
|
||||
export function parse(data: unknown): Message | undefined {
|
||||
if (typeof data !== 'string') return;
|
||||
try {
|
||||
const message = JSON.parse(data);
|
||||
@@ -250,7 +278,7 @@ function parse(data: unknown): Message | undefined {
|
||||
}
|
||||
|
||||
// The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored.
|
||||
function decode(code: string, type: 'offer' | 'answer') {
|
||||
export function decode(code: string, type: 'offer' | 'answer') {
|
||||
try {
|
||||
return { type, sdp: atob(code.replace(/\s/g, '')) };
|
||||
} catch {
|
||||
@@ -262,7 +290,7 @@ function randomBinary(length: number) {
|
||||
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
|
||||
}
|
||||
|
||||
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
export const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
// The largest multiple of the alphabet's length a byte holds. The bytes above would make the first
|
||||
// characters likelier, they are dropped.
|
||||
const CODE_LIMIT = 256 - (256 % CODE_CHARS.length);
|
||||
@@ -285,14 +313,14 @@ export const formatTime = (time: number) =>
|
||||
// so the same one comes back every ~6 hours. The receiver takes the window with that character nearest
|
||||
// its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts
|
||||
// TRACKER_WAIT from the click whenever in its window that was.
|
||||
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
|
||||
const SALT_WINDOW = 6 * 60_000;
|
||||
const CODE_LENGTH = 11;
|
||||
// Its own constant, not TRACKER_WAIT: changing it takes a new PROTOCOL.
|
||||
export const SALT_WINDOW = 6 * 60_000;
|
||||
export const CODE_LENGTH = 11;
|
||||
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
|
||||
|
||||
// The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo,
|
||||
// not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share.
|
||||
function trackerSalt(at: number, own?: string) {
|
||||
export function trackerSalt(at: number, own?: string) {
|
||||
const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16);
|
||||
if (own === undefined) return salt;
|
||||
if (!own.trim()) throw new Error('the own salt is empty');
|
||||
@@ -300,14 +328,14 @@ function trackerSalt(at: number, own?: string) {
|
||||
}
|
||||
|
||||
// A sender's new code and its salt.
|
||||
function newCode(own?: string) {
|
||||
export function newCode(own?: string) {
|
||||
const at = clockWindow(Date.now());
|
||||
return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) };
|
||||
}
|
||||
|
||||
// The salt of the code a receiver got, its window from half the characters before the clock's to half
|
||||
// after. Anything else can't be a code, a typo gets told right away instead of searched for.
|
||||
function codeSalt(code: string, own?: string) {
|
||||
export function codeSalt(code: string, own?: string) {
|
||||
if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char)))
|
||||
throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`);
|
||||
const now = clockWindow(Date.now());
|
||||
@@ -324,15 +352,17 @@ function codeSalt(code: string, own?: string) {
|
||||
// clock's salt limits a table to the shares of one window, for 62¹⁰ codes it takes over a million GPU
|
||||
// years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one
|
||||
// system can be other bytes than on the next. HKDF splits the result, the public info_hash tells
|
||||
// nothing about the keys: one seals the signaling, see seal, one proves the connection.
|
||||
async function secrets(code: string, salt: string) {
|
||||
// nothing about the keys: one seals the signaling, see seal, one proves the connection. The PROTOCOL
|
||||
// goes in front of the salt, each version gets swarms and keys of its own. The proof's HMAC key takes
|
||||
// the hash's block size without a length given, 64 bytes.
|
||||
export async function secrets(code: string, salt: string) {
|
||||
const text = new TextEncoder();
|
||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
hash: 'SHA-256',
|
||||
salt: text.encode(`hellcon ${salt.normalize('NFC')}`),
|
||||
salt: text.encode(`${PROTOCOL} ${salt.normalize('NFC')}`),
|
||||
iterations: PBKDF2_ITERATIONS,
|
||||
},
|
||||
password,
|
||||
@@ -356,7 +386,7 @@ async function secrets(code: string, salt: string) {
|
||||
// the swarm without the code learn the addresses in it, and nobody answers what they can't open. The
|
||||
// type is sealed along, an offer doesn't pass for an answer. Base64 of IV and ciphertext, in the
|
||||
// sdp field, so trackers relay it like any other.
|
||||
async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
|
||||
export async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
|
||||
const text = new TextEncoder();
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) };
|
||||
@@ -365,7 +395,7 @@ async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
|
||||
}
|
||||
|
||||
// The SDP, unless it wasn't sealed with the code as that type.
|
||||
async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) {
|
||||
export async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) {
|
||||
// atob throws on what isn't base64, decrypt on anything else.
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0));
|
||||
@@ -411,13 +441,13 @@ async function gatherIce(pc: RTCPeerConnection) {
|
||||
});
|
||||
});
|
||||
const [server] = pc.getConfiguration().iceServers ?? [];
|
||||
if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!);
|
||||
if (server && !reported && pc.signalingState !== 'closed') void stun.failed([server.urls].flat()[0]!);
|
||||
}
|
||||
|
||||
// Why pc didn't connect, if a missing public address explains it: a side without one from STUN offers
|
||||
// only local addresses, enough on the same network or VPN. peer names the other side. A device with
|
||||
// a public address of its own offers none either, see stunServer, so it's a hint, not a diagnosis.
|
||||
function stunHint(pc: RTCPeerConnection, peer: string) {
|
||||
// a public address of its own offers none either, see stunChoice, so it's a hint, not a diagnosis.
|
||||
export function stunHint(pc: RTCPeerConnection, peer: string) {
|
||||
const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? '');
|
||||
const local = offersPublic(pc.localDescription);
|
||||
const remote = offersPublic(pc.remoteDescription);
|
||||
@@ -436,31 +466,46 @@ const BLOCKED = 'a network in between, e.g. a VPN or firewall, may block direct
|
||||
|
||||
const host = (url: string) => URL.parse(url)?.host || url;
|
||||
|
||||
// Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can
|
||||
// brute force with matching certificates. My local code must equal the peer's remote code and vice
|
||||
// versa, otherwise someone interposed on the signaling.
|
||||
function securityCheck(pc: RTCPeerConnection) {
|
||||
const short = (sdp = '') =>
|
||||
sdp
|
||||
.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]
|
||||
?.toUpperCase()
|
||||
.split(':')
|
||||
.slice(0, 8)
|
||||
.join(' ') ?? '?';
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
// Every fingerprint the SDP names, in full: one added beside the real one changes the result too.
|
||||
// Browsers may move them between session and media level, so each counts once.
|
||||
const fingerprints = (sdp: string) =>
|
||||
[...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort();
|
||||
// Browsers may move them between session and media level, so each counts once. Any a=fingerprint
|
||||
// counts, also one hidden in another line: one the browser ignores only makes the result differ,
|
||||
// one missed that the browser uses would let an interposer through. So nothing depends on how a
|
||||
// browser splits lines.
|
||||
export const fingerprints = (sdp: string) =>
|
||||
[
|
||||
...new Set(
|
||||
[...sdp.matchAll(/a=fingerprint:([^\n]*)/gi)].map(([, fingerprint]) =>
|
||||
fingerprint!.trim().replace(/\s+/g, ' ').toLowerCase(),
|
||||
),
|
||||
),
|
||||
].sort();
|
||||
|
||||
// Anti-MITM check of the manual exchange: the first 16 bytes of a SHA-256 over all DTLS
|
||||
// certificate fingerprints of each side. An interposer can try one cheaply, it only has to vary a
|
||||
// line the browser ignores, so it takes that many to be out of its reach. My local code must equal
|
||||
// the peer's remote code and vice versa, otherwise someone interposed on the signaling. All of them
|
||||
// count, like in prove: one certificate may be named by several hash functions, and a browser may
|
||||
// accept a certificate by any of them. Without one on either side there is nothing to check:
|
||||
// undefined.
|
||||
export async function securityCheck(pc: RTCPeerConnection) {
|
||||
const short = async (sdp = '') => {
|
||||
const list = fingerprints(sdp);
|
||||
if (!list.length) return;
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(list)));
|
||||
return Array.from(new Uint8Array(digest, 0, 16), (byte) => byte.toString(16).padStart(2, '0'))
|
||||
.join(' ')
|
||||
.toUpperCase();
|
||||
};
|
||||
const [local, remote] = await Promise.all([short(pc.localDescription?.sdp), short(pc.remoteDescription?.sdp)]);
|
||||
if (local && remote) return { local, remote };
|
||||
}
|
||||
|
||||
// The security check of tracker signaling, resolves once the peer proved the code. Each side signs its
|
||||
// role, its SDP type, and the fingerprints of both certificates as it sees them. The peer checks that
|
||||
// against its own view. An interposer has its own certificate towards each side and can't sign for it
|
||||
// without the code, neither can a peer that found the swarm some other way. One that sends no proof
|
||||
// within PROOF_TIMEOUT or a wrong one ends the connection.
|
||||
function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
|
||||
export function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
|
||||
const local = pc.localDescription!;
|
||||
const remote = pc.remoteDescription!;
|
||||
const statement = (type: string, own: string, peer: string) =>
|
||||
@@ -502,7 +547,7 @@ function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, e
|
||||
// pass, a failed check, a peer that left or end closes the connection and calls next: tracker
|
||||
// signaling goes on with another peer. Without next, as in the manual exchange, the session is over
|
||||
// and the reason is an error. From start on, sendFile and receiveFile handle a loss.
|
||||
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
||||
export type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
||||
|
||||
function connected(
|
||||
pc: RTCPeerConnection,
|
||||
@@ -516,7 +561,6 @@ function connected(
|
||||
events.log(`connected via ${via}`);
|
||||
events.log('waiting for the security check');
|
||||
if (key) events.status('start', 'Connected, checking the code');
|
||||
else events.status('wait', `Compare the security codes above with the ${peer}`);
|
||||
let done = false;
|
||||
const end = (reason: string) => {
|
||||
if (done) return;
|
||||
@@ -535,8 +579,15 @@ function connected(
|
||||
return {
|
||||
checked: key
|
||||
? prove(pc, channel, key, end).then(() => events.log('security check passed'))
|
||||
: new Promise((resolve) =>
|
||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||
: securityCheck(pc).then(
|
||||
(codes) =>
|
||||
new Promise<void>((resolve) => {
|
||||
// The peer may have left while the codes were computed.
|
||||
if (done) return;
|
||||
if (!codes) return end('no certificate to check');
|
||||
events.check({ ...codes, confirm: resolve, reject: () => end('security check failed') });
|
||||
events.status('wait', `Compare the security codes above with the ${peer}`);
|
||||
}),
|
||||
),
|
||||
start: () => (done = true),
|
||||
end,
|
||||
@@ -548,7 +599,7 @@ function connected(
|
||||
// { done } once the download manager read the last byte, or { error } when its download was
|
||||
// cancelled or failed. Any other message, or one out of turn, is ignored. Every way out of the
|
||||
// transfer closes the connection.
|
||||
async function sendFile(
|
||||
export async function sendFile(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
file: File,
|
||||
@@ -584,7 +635,7 @@ async function sendFile(
|
||||
events.progress(file.size, file.size);
|
||||
stop();
|
||||
} else if (typeof message?.error === 'string') {
|
||||
stop(`receiver stopped: ${message.error.slice(0, 200)}`);
|
||||
stop(`receiver stopped: ${message.error.replace(HIDDEN, '').slice(0, 200)}`);
|
||||
}
|
||||
wake();
|
||||
};
|
||||
@@ -632,7 +683,9 @@ async function sendFile(
|
||||
.slice(offset, offset + CHUNK_SIZE)
|
||||
.arrayBuffer()
|
||||
.catch(() => undefined);
|
||||
if (!chunk) return stop(`could not read ${file.name} anymore`);
|
||||
// A browser may read a file that shrank meanwhile short instead of failing.
|
||||
if (chunk?.byteLength !== Math.min(CHUNK_SIZE, file.size - offset))
|
||||
return stop(`could not read ${file.name} anymore`);
|
||||
if (!open()) return;
|
||||
channel.send(chunk);
|
||||
}
|
||||
@@ -640,63 +693,19 @@ async function sendFile(
|
||||
if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest');
|
||||
}
|
||||
|
||||
// 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.
|
||||
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.
|
||||
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 };
|
||||
}
|
||||
|
||||
// Accepts nothing until checked resolved, then tells the sender with { ok }. Its file is offered to
|
||||
// the user, chunks are accepted only once they started the download. Nothing the sender sends is
|
||||
// trusted: a malformed offer ends the connection, more bytes than offered or beyond the window fail
|
||||
// the download. Once it ended, the connection closes.
|
||||
function receiveFile(
|
||||
// the download. Once it ended, the connection closes. startDownload saves it, see src/download.ts.
|
||||
export function receiveFile(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
events: ReceiveEvents,
|
||||
handshake: Handshake,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const id = crypto.randomUUID();
|
||||
const frames: HTMLIFrameElement[] = [];
|
||||
let meta: { name: string; size: number } | undefined;
|
||||
let saving: Download | undefined;
|
||||
let received = 0;
|
||||
// By the download manager. The rest of received is held in this page and the worker.
|
||||
let read = 0;
|
||||
@@ -704,86 +713,50 @@ function receiveFile(
|
||||
let downloading = false;
|
||||
let complete = false;
|
||||
let ended = false;
|
||||
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
|
||||
let worker: Promise<ServiceWorker | undefined> = Promise.resolve(undefined);
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
||||
// To the sender, see sendFile.
|
||||
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
|
||||
// A data channel closes only after sending what it buffered, so the last reply still arrives.
|
||||
channel.addEventListener('close', () => pc.close());
|
||||
|
||||
let keepalive: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
// Releases the worker, so a waiting update can take over. A finished download keeps its own frame
|
||||
// for DOWNLOAD_GRACE, that one doesn't hold the worker.
|
||||
function release(finished = false) {
|
||||
clearInterval(keepalive);
|
||||
const [hold, download] = frames;
|
||||
hold?.remove();
|
||||
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
|
||||
else download?.remove();
|
||||
}
|
||||
|
||||
// The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the
|
||||
// download running instead of failing it.
|
||||
function fail(reason: string) {
|
||||
if (ended) return;
|
||||
saving?.fail(reason);
|
||||
failed(reason);
|
||||
}
|
||||
|
||||
// Also when the download failed on its own, no telling it then.
|
||||
function failed(reason: string) {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
post({ error: reason });
|
||||
reply({ error: reason });
|
||||
channel.close();
|
||||
events.error(`download failed: ${reason}`);
|
||||
}
|
||||
|
||||
function startDownload() {
|
||||
worker = holdWorker().then(
|
||||
({ frame, worker }) => {
|
||||
frames.push(frame);
|
||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
||||
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state !== 'redundant') return;
|
||||
fail('service worker stopped');
|
||||
release();
|
||||
});
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.onmessage = ({ data }) => {
|
||||
if (typeof data === 'number') {
|
||||
read = data;
|
||||
events.progress(read, meta!.size);
|
||||
return reply({ read });
|
||||
}
|
||||
if (data === 'ready' && !ended) {
|
||||
// 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 (data === 'failed') fail('the service worker refused it');
|
||||
if (data === 'finished') {
|
||||
function startSaving(file: { name: string; size: number }) {
|
||||
saving = startDownload(file, {
|
||||
read: (bytes) => {
|
||||
read = bytes;
|
||||
events.progress(read, file.size);
|
||||
reply({ read });
|
||||
},
|
||||
finished: () => {
|
||||
events.log('download complete');
|
||||
events.status('done', 'Download complete');
|
||||
events.progress(meta!.size, meta!.size);
|
||||
events.progress(file.size, file.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
ended = true;
|
||||
channel.close();
|
||||
},
|
||||
cancelled: () => {
|
||||
events.log('download cancelled');
|
||||
events.status('stopped', 'Download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
channel.close();
|
||||
release(data === 'finished');
|
||||
};
|
||||
worker.postMessage({ id, ...meta }, [port2]);
|
||||
return worker;
|
||||
},
|
||||
(error) => void fail(String(error)),
|
||||
);
|
||||
failed,
|
||||
});
|
||||
}
|
||||
|
||||
void handshake.checked.then(() => {
|
||||
@@ -795,7 +768,7 @@ function receiveFile(
|
||||
|
||||
function receivedAll() {
|
||||
complete = true;
|
||||
post({ done: true });
|
||||
saving!.end();
|
||||
events.log('received');
|
||||
}
|
||||
|
||||
@@ -809,7 +782,7 @@ function receiveFile(
|
||||
events.log(`receiving ${meta!.name}`);
|
||||
events.status('transfer', 'Receiving');
|
||||
events.progress(0, meta!.size);
|
||||
startDownload();
|
||||
startSaving(meta!);
|
||||
reply({ start: true });
|
||||
if (!meta!.size) receivedAll();
|
||||
}
|
||||
@@ -823,16 +796,16 @@ function receiveFile(
|
||||
if (typeof name !== 'string' || name.length > MAX_NAME || !Number.isSafeInteger(size) || size < 0) {
|
||||
return handshake.end('the sender offered no valid file');
|
||||
}
|
||||
meta = { name, size };
|
||||
events.log(`offered ${name} (${size} bytes)`);
|
||||
meta = { name: name.replace(HIDDEN, ''), size };
|
||||
events.log(`offered ${meta.name} (${size} bytes)`);
|
||||
events.status('wait', 'Click Download to save the file');
|
||||
events.incoming({ name, size, download });
|
||||
events.incoming({ ...meta, download });
|
||||
} else if (downloading && !complete) {
|
||||
received += data.byteLength;
|
||||
if (received > meta!.size) return fail('the sender sent more than it offered');
|
||||
// sendFile never has more than WINDOW unread plus the chunk it just sent.
|
||||
if (received - read > WINDOW + CHUNK_SIZE) return fail('the sender ignored the flow control');
|
||||
post({ chunk: data }, [data]);
|
||||
saving!.write(data);
|
||||
if (received === meta!.size) receivedAll();
|
||||
}
|
||||
};
|
||||
@@ -882,7 +855,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the offer');
|
||||
const pc = await createPeerConnection(signal);
|
||||
const channel = pc.createDataChannel('file');
|
||||
const channel = pc.createDataChannel(PROTOCOL);
|
||||
channel.onopen = () =>
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', 'receiver', events), signal);
|
||||
const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver');
|
||||
@@ -918,6 +891,11 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
// The sender's file channel, anything more is none of ours.
|
||||
if (opened) return;
|
||||
opened = true;
|
||||
if (channel.label !== PROTOCOL) {
|
||||
events.log(`the sender's protocol: ${JSON.stringify(channel.label.replace(HIDDEN, '').slice(0, 100))}`);
|
||||
pc.close();
|
||||
return events.error(`the sender runs another protocol, both pages have to show protocol ${PROTOCOL}`);
|
||||
}
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', 'sender', events), signal);
|
||||
};
|
||||
const wait = failUnconnected(pc, () => opened, events, signal, 'sender');
|
||||
@@ -935,10 +913,12 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
|
||||
// A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason
|
||||
// before anything else rejects the announcement, the tracker is no use then and its socket closes, a
|
||||
// later one only concerns that message and is logged. message may be async, the next message doesn't
|
||||
// wait for it. lost runs once it closed without close() being called: unreachable, lost, rejected or
|
||||
// without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names.
|
||||
function trackerSocket(
|
||||
// later one only concerns that message and is noted. A message over MAX_TRACKER_MESSAGE rejects it the
|
||||
// same way, a later one is noted and dropped. note logs what the tracker made the page do, see
|
||||
// TRACKER_NOTES. message may be async, the next message doesn't wait for it. lost runs once it closed
|
||||
// without close() being called: unreachable, lost, rejected or without an answer within
|
||||
// TRACKER_TIMEOUT. again announces once more, on the first interval it names.
|
||||
export function trackerSocket(
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
events: Events,
|
||||
@@ -946,10 +926,27 @@ function trackerSocket(
|
||||
lost: () => void,
|
||||
again: () => void,
|
||||
) {
|
||||
const ws = new WebSocket(url);
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(url);
|
||||
} catch (error) {
|
||||
// Chromium refuses e.g. ws: on an https page right away, Firefox only closes the socket. Lost all
|
||||
// the same, once the caller has it.
|
||||
ws = Object.assign(new EventTarget(), { close: () => {} }) as unknown as WebSocket;
|
||||
queueMicrotask(() => end(`${url} refused: ${error instanceof Error ? error.message : error}`));
|
||||
}
|
||||
let opened = false;
|
||||
let accepted = false;
|
||||
let closed = false;
|
||||
// Messages in the current MESSAGE_WINDOW, since windowStart.
|
||||
let windowStart = Date.now();
|
||||
let count = 0;
|
||||
const noted = new Set<string>();
|
||||
const note = (line: string) => {
|
||||
if (noted.has(line) || noted.size > TRACKER_NOTES) return;
|
||||
noted.add(line);
|
||||
events.log(noted.size > TRACKER_NOTES ? `${url}: more of it, no longer logged` : line);
|
||||
};
|
||||
let reannounce: ReturnType<typeof setInterval> | undefined;
|
||||
const end = (reason: string) => {
|
||||
if (closed) return;
|
||||
@@ -965,6 +962,7 @@ function trackerSocket(
|
||||
// What the tracker answered, if it rejected the announcement.
|
||||
rejected: undefined as string | undefined,
|
||||
alive: () => !closed,
|
||||
note,
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
@@ -975,6 +973,15 @@ function trackerSocket(
|
||||
});
|
||||
ws.addEventListener('open', () => (opened = true));
|
||||
ws.addEventListener('message', ({ data }) => {
|
||||
const now = Date.now();
|
||||
if (now - windowStart >= MESSAGE_WINDOW) {
|
||||
windowStart = now;
|
||||
count = 0;
|
||||
}
|
||||
if (++count > MAX_TRACKER_MESSAGES) return note(`${url} sends too much, dropping some of it`);
|
||||
if (typeof data === 'string' && data.length > MAX_TRACKER_MESSAGE) {
|
||||
return reject(`${url}: message over ${MAX_TRACKER_MESSAGE / 1024} KiB`);
|
||||
}
|
||||
const msg = parse(data);
|
||||
const failure = msg?.['failure reason'];
|
||||
if (typeof failure !== 'string') {
|
||||
@@ -987,10 +994,14 @@ function trackerSocket(
|
||||
}
|
||||
return void message(msg);
|
||||
}
|
||||
if (accepted) return events.log(`${url}: ${failure}`);
|
||||
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
|
||||
end(`rejected by ${tracker.rejected}`);
|
||||
reject(`${url}: ${failure.replace(HIDDEN, '').slice(0, 200)}`);
|
||||
});
|
||||
// A problem with the tracker's message: the end before acceptance, after it only that message's.
|
||||
const reject = (reason: string) => {
|
||||
if (accepted) return note(reason);
|
||||
tracker.rejected = reason;
|
||||
end(`rejected by ${reason}`);
|
||||
};
|
||||
ws.addEventListener('close', () => end(opened ? `lost ${url}` : `${url} unreachable`));
|
||||
return tracker;
|
||||
}
|
||||
@@ -998,7 +1009,7 @@ function trackerSocket(
|
||||
type Tracker = ReturnType<typeof trackerSocket>;
|
||||
|
||||
// Once none of the trackers is left: what the user can do about it, and why if any rejected.
|
||||
function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
export function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
const rejected = trackers.flatMap((tracker) => tracker?.rejected ?? []);
|
||||
const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable';
|
||||
return `${reason}, check the list under Servers and try again`;
|
||||
@@ -1105,6 +1116,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
if (settled) return;
|
||||
// Only a fork that kept the name derives these keys.
|
||||
if (channel.label !== PROTOCOL) return giveUp(`receiver via ${url} runs another protocol`);
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
const handshake = connected(pc, channel, url, 'receiver', events, next, key);
|
||||
@@ -1154,9 +1167,13 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
|
||||
// Meanwhile the share may have been used up, expired or ended, its tracker closed then.
|
||||
if (signal.aborted || !tracker.alive()) return;
|
||||
if (sdp === undefined) return events.log(`offer without the code via ${url}`);
|
||||
if (sdp === undefined) return tracker.note(`offer without the code via ${url}`);
|
||||
const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||
// A lost tracker would take no answer, a receiver that came by it looks on the next one.
|
||||
if (busy)
|
||||
waiting = async () => {
|
||||
if (tracker.alive()) await answer(tracker.ws, url, offer);
|
||||
};
|
||||
else void answer(tracker.ws, url, offer);
|
||||
},
|
||||
() => {
|
||||
@@ -1174,7 +1191,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
trackers.push(tracker);
|
||||
}
|
||||
|
||||
join(0);
|
||||
// Ended while the key was derived.
|
||||
if (!signal.aborted) join(0);
|
||||
return { code, until };
|
||||
}
|
||||
|
||||
@@ -1223,7 +1241,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
const nobody = () =>
|
||||
hint
|
||||
? `no sender connected until ${formatTime(until)}: ${hint}`
|
||||
: `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`;
|
||||
: `no sender answered until ${formatTime(until)}, check that both pages show protocol ${PROTOCOL}${ownSalt === undefined ? '' : ' and you use the same salt'} or ask the sender for a new code`;
|
||||
// Without a sender connected the search is over, every offer goes.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1268,7 +1286,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
entry.pc = pc;
|
||||
// Meanwhile the download may have started or the search ended.
|
||||
if (signal.aborted || started || expired) return pc.close();
|
||||
const channel = pc.createDataChannel('file');
|
||||
const channel = pc.createDataChannel(PROTOCOL);
|
||||
const offerId = randomBinary(20);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
// Unless another offer is connected, next replaces this one then.
|
||||
@@ -1337,7 +1355,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
if (none)
|
||||
events.status(
|
||||
'retry',
|
||||
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'}, still looking`,
|
||||
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'} and that both pages show protocol ${PROTOCOL}, still looking`,
|
||||
);
|
||||
else if (failure) events.status('retry', `${failure}. Looking again`);
|
||||
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
||||
@@ -1350,7 +1368,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
// Only one answer per offer, a replacement opens its own socket. Meanwhile it may have
|
||||
// come, or the search ended, its socket closed then.
|
||||
if (pc.signalingState === 'closed' || !tracker.alive()) return;
|
||||
if (answer === undefined) return events.log(`answer without the code via ${url}`);
|
||||
if (answer === undefined) return tracker.note(`answer without the code via ${url}`);
|
||||
events.log(`answer via ${url}`);
|
||||
attempts++;
|
||||
noSender = false;
|
||||
|
||||
+165
@@ -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));
|
||||
},
|
||||
};
|
||||
}
|
||||
+13
-1
@@ -411,6 +411,12 @@ label strong,
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
@@ -616,14 +622,20 @@ output {
|
||||
/* Source link, quiet below everything */
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
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);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition);
|
||||
|
||||
+1
-1
@@ -16,5 +16,5 @@
|
||||
"allowJs": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"]
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "playwright.config.ts", "e2e.spec.ts"]
|
||||
}
|
||||
+25
-1
@@ -1,6 +1,30 @@
|
||||
/// <reference types="vitest/config" />
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
const DEV_STYLE_SRC = "style-src 'self'";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
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'] },
|
||||
});
|
||||
Reference in new issue
Block a user