Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb69569b51 | ||
|
|
338d4d2532 | ||
|
|
c6145b8919 | ||
|
|
707248f36b |
No files matched your search
@@ -6,10 +6,10 @@ size limit: the file goes directly to the other person and is never stored on a
|
|||||||
## How to send a file
|
## How to send a file
|
||||||
|
|
||||||
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
||||||
an 8 character code. Tell it to the receiver, it works for 6 minutes.
|
an 8 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
|
||||||
|
get the file, so give it to nobody else.
|
||||||
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
||||||
3. **Both:** compare the security check (see below) and click **Codes match**.
|
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
|
||||||
4. **Receiver:** you now see the file's name and size. Click **Download** to save it.
|
|
||||||
|
|
||||||
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
||||||
tab was doing.
|
tab was doing.
|
||||||
@@ -20,12 +20,20 @@ If you'd rather not use a tracker, open **Manual** on both sides. The sender cre
|
|||||||
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
||||||
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
||||||
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
||||||
you're sending to.
|
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
|
||||||
|
|
||||||
## The security check
|
## The security check
|
||||||
|
|
||||||
Once connected, both sides see two short codes: **You** and **Peer**. Compare them with the other
|
Before anything is transferred, both sides make sure they are connected directly to each other and
|
||||||
person over a channel you already trust, ideally a call or in person:
|
not to someone who placed themselves in between.
|
||||||
|
|
||||||
|
With the code this happens by itself: each side proves to the other that it knows the code, tied
|
||||||
|
to the encryption keys of this very connection. Someone in between, or anyone else who doesn't
|
||||||
|
know the code, can't do that, and HellCon drops the connection and waits for the right one.
|
||||||
|
|
||||||
|
The manual exchange has no code, so there you compare yourselves. Once connected, both sides see two
|
||||||
|
short 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 **You** must be their **Peer**, and
|
||||||
- your **Peer** must be their **You**.
|
- your **Peer** must be their **You**.
|
||||||
@@ -44,7 +52,9 @@ the browsers need two things:
|
|||||||
|
|
||||||
- **Finding each other.** The code puts both browsers into the same group on a public
|
- **Finding each other.** The code puts both browsers into the same group on a public
|
||||||
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
|
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
|
||||||
forth. It never sees the file. With the manual exchange you play the tracker yourself.
|
forth. They are encrypted with the code, so the tracker can't read them, and neither can anyone
|
||||||
|
else in the group without the code. It never sees the file. With the manual exchange you play the
|
||||||
|
tracker yourself.
|
||||||
- **Reaching each other.** Most devices sit behind a router and don't know their public address.
|
- **Reaching each other.** Most devices sit behind a router and don't know their public address.
|
||||||
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
|
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
|
||||||
only on the same network or over a VPN.
|
only on the same network or over a VPN.
|
||||||
@@ -60,7 +70,8 @@ networks, a direct connection may not be possible.
|
|||||||
|
|
||||||
- The file only goes to the person you connected with.
|
- The file only goes to the person you connected with.
|
||||||
- That person learns your IP address, as with any direct connection. The tracker and the STUN
|
- That person learns your IP address, as with any direct connection. The tracker and the STUN
|
||||||
servers see it too.
|
servers see it too, from the request itself. Nobody without the code learns it through the
|
||||||
|
tracker.
|
||||||
- Settings (STUN on or off, your server lists) are kept in your browser only.
|
- Settings (STUN on or off, your server lists) are kept in your browser only.
|
||||||
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
|
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
|
||||||
host your own (below).
|
host your own (below).
|
||||||
|
|||||||
@@ -1,5 +1,60 @@
|
|||||||
# TODO
|
# TODO
|
||||||
|
|
||||||
|
## Server at pagequit.net, to decide
|
||||||
|
|
||||||
|
### Review of the coturn setup (STUN only, host network)
|
||||||
|
|
||||||
|
- Good as it is: `stun-only`, `no-tcp`, `no-tls`, `no-software-attribute`, CPU, memory and process
|
||||||
|
limits with swap off, and log rotation. Host networking is right for STUN, so Docker's NAT can't
|
||||||
|
change the source address the clients get back. Listening on IPv4 only matches DNS:
|
||||||
|
`stun.pagequit.net` has an A record and no AAAA.
|
||||||
|
- `coturn/coturn:latest` is the only unpinned version. Pin `coturn/coturn:4.18.0` (2026-09-08).
|
||||||
|
- Add `no-cli`. On the host network, coturn's admin CLI would otherwise listen on the host's
|
||||||
|
127.0.0.1:5766 if it's enabled.
|
||||||
|
- Add `no-stun-backward-compatibility`. Browsers only use the current STUN protocol, so the old
|
||||||
|
RFC 3489 requests and their extra MAPPED-ADDRESS can go, which also makes responses smaller for
|
||||||
|
reflection attacks.
|
||||||
|
- Check that the logs hold no client addresses: send a STUN request, then
|
||||||
|
`docker compose logs coturn | grep <your IP>`. Logging each request is off by default and
|
||||||
|
`log-binding` turns it on, so it should stay empty. Otherwise up to 20 MB of addresses stay around.
|
||||||
|
- Missing compared to the tracker draft: `cap_drop: [ALL]` and
|
||||||
|
`security_opt: [no-new-privileges:true]`. `read_only: true` is worth trying too, but coturn may
|
||||||
|
need a writable `/var/run` or `/var/lib/coturn` (`tmpfs`).
|
||||||
|
- coturn doesn't rate limit STUN requests. A response is about as big as the request, so it's a weak
|
||||||
|
amplifier. If it gets abused, an nftables `limit` on the UDP port would help.
|
||||||
|
|
||||||
|
### Compared to the plan so far
|
||||||
|
|
||||||
|
- Caddy and coturn don't share a Docker network, coturn runs on the host network. The tracker joins
|
||||||
|
Caddy's network (its name is in Caddy's compose file), coturn stays as it is.
|
||||||
|
- Copy coturn's limits to the tracker, with smaller values: `cpus`, `mem_limit` equal to
|
||||||
|
`memswap_limit`, `pids_limit`, and the same `json-file` log rotation.
|
||||||
|
- Pin every version, coturn and the tracker alike.
|
||||||
|
|
||||||
|
### Decisions
|
||||||
|
|
||||||
|
1. **Which tracker.** Stock `bittorrent-tracker@11.2.3` behind Caddy works: tested locally with a
|
||||||
|
real transfer from Chromium to Firefox, and it logs nothing with `--quiet`. A review found it too
|
||||||
|
open to run unchanged:
|
||||||
|
- it forwards any data and accepts messages up to 100 MiB
|
||||||
|
- `scrape` lists all swarms even with `--no-stats`
|
||||||
|
- it has no rate, byte or connection limits
|
||||||
|
- it accepts any Origin
|
||||||
|
|
||||||
|
The recommendation is an own tracker for the WebTorrent subset HellCon uses, so the client stays
|
||||||
|
unchanged and the public trackers keep working as fallbacks. Node 26 and `ws`, one file of about
|
||||||
|
250 lines, enforcing:
|
||||||
|
- an Origin allowlist and messages of at most 16 KiB
|
||||||
|
- only `announce`, one offer per announce, and answers only to offers it delivered, once
|
||||||
|
- per connection: a message rate, about 64 KiB of forwarded data, and at most 7 minutes
|
||||||
|
- connections per IP (from `X-Forwarded-For`), total connections and peers per swarm capped
|
||||||
|
- empty swarms removed, nothing logged
|
||||||
|
|
||||||
|
Then decide where it lives: `tracker/` in this repo (new files, every fork gets it) or a separate
|
||||||
|
repository.
|
||||||
|
2. **After deploying:** put `wss://tracker.pagequit.net` first in `DEFAULT_TRACKERS` and keep the
|
||||||
|
public trackers as fallbacks.
|
||||||
|
|
||||||
## Ideas
|
## Ideas
|
||||||
|
|
||||||
- Resume interrupted transfers: the receiver already reports how much the download manager has
|
- Resume interrupted transfers: the receiver already reports how much the download manager has
|
||||||
|
|||||||
+378
-66
@@ -1,4 +1,4 @@
|
|||||||
import { createHash, randomBytes } from 'node:crypto';
|
import { createCipheriv, createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
|
||||||
import { createSocket, type Socket } from 'node:dgram';
|
import { createSocket, type Socket } from 'node:dgram';
|
||||||
import { createReadStream } from 'node:fs';
|
import { createReadStream } from 'node:fs';
|
||||||
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
|
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
|
||||||
@@ -28,9 +28,10 @@ const SIZE = 5_000_000;
|
|||||||
const LARGE_SIZE = 2.5 * 2 ** 30;
|
const LARGE_SIZE = 2.5 * 2 ** 30;
|
||||||
// Big enough that the transfer still runs while a test cancels or disconnects.
|
// Big enough that the transfer still runs while a test cancels or disconnects.
|
||||||
const RUNNING_SIZE = 100_000_000;
|
const RUNNING_SIZE = 100_000_000;
|
||||||
// WINDOW, CHUNK_SIZE and ICE_TIMEOUT in src/core.ts.
|
// WINDOW, CHUNK_SIZE, ICE_TIMEOUT and PROOF_TIMEOUT in src/core.ts.
|
||||||
const WINDOW = 8 * 2 ** 20;
|
const WINDOW = 8 * 2 ** 20;
|
||||||
const ICE_TIMEOUT = 5000;
|
const ICE_TIMEOUT = 5000;
|
||||||
|
const PROOF_TIMEOUT = 10_000;
|
||||||
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
||||||
const HELD_SIZE = 3 * WINDOW;
|
const HELD_SIZE = 3 * WINDOW;
|
||||||
// What the fake STUN server reports as public address, reserved for documentation.
|
// What the fake STUN server reports as public address, reserved for documentation.
|
||||||
@@ -190,15 +191,16 @@ function trackPeers() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
|
// The page's peer connections that aren't closed. The app's own check of the STUN servers closes its own.
|
||||||
async function expectClosed(page: Page) {
|
const openPeers = (page: Page) =>
|
||||||
const peers = () =>
|
|
||||||
page.evaluate(
|
page.evaluate(
|
||||||
() =>
|
() =>
|
||||||
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed')
|
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
|
||||||
.length,
|
|
||||||
);
|
);
|
||||||
await expect.poll(peers).toBe(0);
|
|
||||||
|
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
|
||||||
|
async function expectClosed(page: Page) {
|
||||||
|
await expect.poll(() => openPeers(page)).toBe(0);
|
||||||
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,10 +303,12 @@ async function withLogs(sender: Page, receiver: Page, fn: () => Promise<void>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connects and verifies that both sides show the same security check, swapped.
|
// Connects and verifies that both sides show the same security check, swapped. Over a tracker the
|
||||||
|
// code proves the connection, nobody sees one.
|
||||||
async function connect(mode: string, sender: Page, receiver: Page, source: string) {
|
async function connect(mode: string, sender: Page, receiver: Page, source: string) {
|
||||||
await sender.setInputFiles('input[type=file]', source);
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
await MODES[mode]!(sender, receiver);
|
await MODES[mode]!(sender, receiver);
|
||||||
|
if (mode === 'tracker') return proven(sender, receiver);
|
||||||
|
|
||||||
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
|
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
|
||||||
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, {
|
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, {
|
||||||
@@ -324,14 +328,24 @@ const downloadStarts = (receiver: Page) =>
|
|||||||
.waitForEvent('download', { timeout: test.info().timeout })
|
.waitForEvent('download', { timeout: test.info().timeout })
|
||||||
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
|
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
|
||||||
|
|
||||||
// Connects, confirms the security check on both sides and starts the download.
|
// Both sides passed the security check of tracker signaling, without showing one.
|
||||||
|
async function proven(sender: Page, receiver: Page) {
|
||||||
|
for (const page of [sender, receiver]) {
|
||||||
|
await expect(page.locator('#log')).toContainText('security check passed', { timeout: 45_000 });
|
||||||
|
await expect(page.locator('#check-local')).toHaveCount(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connects, confirms the security check on both sides unless the code proved it, and starts the download.
|
||||||
async function start(mode: string, sender: Page, receiver: Page, source: string) {
|
async function start(mode: string, sender: Page, receiver: Page, source: string) {
|
||||||
await connect(mode, sender, receiver, source);
|
await connect(mode, sender, receiver, source);
|
||||||
const started = downloadStarts(receiver);
|
const started = downloadStarts(receiver);
|
||||||
|
if (mode !== 'tracker') {
|
||||||
await sender.click('#confirm');
|
await sender.click('#confirm');
|
||||||
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
|
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
|
||||||
await expect(receiver.locator('#log')).not.toContainText('receiving');
|
await expect(receiver.locator('#log')).not.toContainText('receiving');
|
||||||
await receiver.click('#confirm');
|
await receiver.click('#confirm');
|
||||||
|
}
|
||||||
// Offered, but nothing is sent before the user asks for it.
|
// Offered, but nothing is sent before the user asks for it.
|
||||||
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
|
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
|
||||||
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
||||||
@@ -624,6 +638,98 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Sealing keeps a man in the middle without the code out (see the next test), the proofs hold even
|
||||||
|
// against one that opens and seals the signaling. They are genuine, made with the right key, only
|
||||||
|
// the fingerprints they cover give the man in the middle away. Whoever verifies first ends its
|
||||||
|
// connection, the other side may never get the proof then, but neither passes.
|
||||||
|
test(`check: ${name} both sides reject a man in the middle that relays the proofs`, async () => {
|
||||||
|
const [sender, receiver, middle] = await Promise.all([open(name), open(name), open(name, { init: middleman })]);
|
||||||
|
const [toSender, toReceiver] = await Promise.all([announces(sender), announces(receiver)]);
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
for (const page of [sender, receiver]) await page.uncheck('#stun');
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
|
await receiver.fill('#receive-code', code);
|
||||||
|
await receiver.click('#receive');
|
||||||
|
await interpose(middle, code, toSender, toReceiver);
|
||||||
|
|
||||||
|
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 15_000 });
|
||||||
|
await expect(receiver.locator('#log')).toContainText('looking again', { timeout: 15_000 });
|
||||||
|
expect(await relayed(middle)).toBeGreaterThan(0);
|
||||||
|
expect(`${await log(sender)}${await log(receiver)}`).toContain(
|
||||||
|
'security check failed, the peer does not know the code',
|
||||||
|
);
|
||||||
|
for (const page of [sender, receiver]) {
|
||||||
|
expect(await log(page)).not.toContain('security check passed');
|
||||||
|
await expect(page.locator('#check-local')).toHaveCount(0);
|
||||||
|
}
|
||||||
|
expect(await log(sender)).not.toContain('offered');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test(`check: ${name} sender rejects its own proof sent back`, async () => {
|
||||||
|
const [sender, middle] = await Promise.all([open(name), open(name, { init: middleman })]);
|
||||||
|
const toSender = await announces(sender);
|
||||||
|
|
||||||
|
await withLogs(sender, sender, async () => {
|
||||||
|
await sender.uncheck('#stun');
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
await interpose(middle, (await sender.locator('#send-code').textContent())!, toSender);
|
||||||
|
|
||||||
|
await expect(sender.locator('#log')).toContainText('security check failed, the peer does not know the code', {
|
||||||
|
timeout: 15_000,
|
||||||
|
});
|
||||||
|
expect(await relayed(middle)).toBe(1);
|
||||||
|
expect(await log(sender)).not.toContain('security check passed');
|
||||||
|
expect(await log(sender)).not.toContain('offered');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// A tracker sees all signaling, without the code it can read none of it nor get anything answered:
|
||||||
|
// not a well-formed SDP of its own, not the receiver's sealed offer passed off as an answer.
|
||||||
|
test(`check: ${name} a man in the middle without the code learns no address and connects nobody`, async () => {
|
||||||
|
const [sender, receiver, middle] = await Promise.all([open(name), open(name), open(name, { init: middleman })]);
|
||||||
|
const [toSender, toReceiver] = await Promise.all([announces(sender), announces(receiver)]);
|
||||||
|
const binary = () => randomBytes(20).toString('latin1');
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||||
|
await receiver.click('#receive');
|
||||||
|
|
||||||
|
const { msg, ws } = await first(toReceiver, (msg) => msg.offers);
|
||||||
|
const [{ offer, offer_id }] = msg.offers;
|
||||||
|
expect(offer.sdp).not.toContain('a=fingerprint');
|
||||||
|
expect(offer.sdp).not.toContain('candidate');
|
||||||
|
type Hosting = { middle: Middle };
|
||||||
|
const own = await middle.evaluate(() => (window as unknown as Hosting).middle.offer(true));
|
||||||
|
const answer = await middle.evaluate((sdp) => (window as unknown as Hosting).middle.answer(sdp), own);
|
||||||
|
for (const sdp of [answer, offer.sdp]) {
|
||||||
|
const reply = {
|
||||||
|
action: 'announce',
|
||||||
|
info_hash: msg.info_hash,
|
||||||
|
peer_id: binary(),
|
||||||
|
offer_id,
|
||||||
|
answer: { type: 'answer', sdp },
|
||||||
|
};
|
||||||
|
ws.send(JSON.stringify(reply));
|
||||||
|
}
|
||||||
|
const started = await first(toSender, (msg) => msg.event === 'started');
|
||||||
|
const forged = { action: 'announce', info_hash: started.msg.info_hash, peer_id: binary(), offer_id: binary() };
|
||||||
|
started.ws.send(JSON.stringify({ ...forged, offer: { type: 'offer', sdp: own } }));
|
||||||
|
|
||||||
|
await expect.poll(async () => (await log(receiver))!.match(/answer without the code/g)?.length ?? 0).toBe(2);
|
||||||
|
await expect(sender.locator('#log')).toContainText('offer without the code');
|
||||||
|
expect(await log(receiver)).not.toContain('answer via');
|
||||||
|
expect(toSender.some(({ msg }) => msg.answer)).toBe(false);
|
||||||
|
expect(await openPeers(sender)).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test(`protocol: ${name} receiver refuses an offer that isn't a file`, async () => {
|
test(`protocol: ${name} receiver refuses an offer that isn't a file`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||||
const source = await payload(randomBytes(SIZE));
|
const source = await payload(randomBytes(SIZE));
|
||||||
@@ -697,10 +803,8 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
|
|
||||||
await receiver.fill('#receive-code', code);
|
await receiver.fill('#receive-code', code);
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
await proven(sender, receiver);
|
||||||
const started = downloadStarts(receiver);
|
const started = downloadStarts(receiver);
|
||||||
await sender.click('#confirm');
|
|
||||||
await receiver.click('#confirm');
|
|
||||||
await receiver.click('#download');
|
await receiver.click('#download');
|
||||||
const { download } = await started;
|
const { download } = await started;
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
expect(await hash(await download.path())).toBe(await hash(source));
|
||||||
@@ -717,7 +821,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await sender.setInputFiles('input[type=file]', source);
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
await MODES.tracker!(sender, receiver);
|
await MODES.tracker!(sender, receiver);
|
||||||
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
await proven(sender, receiver);
|
||||||
await Promise.all([sender, receiver].map((page) => page.clock.fastForward('06:00')));
|
await Promise.all([sender, receiver].map((page) => page.clock.fastForward('06:00')));
|
||||||
for (const page of [sender, receiver]) {
|
for (const page of [sender, receiver]) {
|
||||||
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
||||||
@@ -725,8 +829,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
|
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
|
||||||
|
|
||||||
const started = downloadStarts(receiver);
|
const started = downloadStarts(receiver);
|
||||||
await sender.click('#confirm');
|
|
||||||
await receiver.click('#confirm');
|
|
||||||
await receiver.click('#download');
|
await receiver.click('#download');
|
||||||
const { download } = await started;
|
const { download } = await started;
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
expect(await hash(await download.path())).toBe(await hash(source));
|
||||||
@@ -761,7 +863,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Anyone with the code can send offers no browser can parse, as many as they like. The share lets
|
// Anyone with the code can send offers no browser can parse, as many as they like. The share lets
|
||||||
// go of each one's connection and keeps using the tracker.
|
// go of each one's connection and keeps using the tracker. Without the code they get no connection.
|
||||||
test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
|
test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
|
||||||
const sender = await open(name, { init: countAbortListeners });
|
const sender = await open(name, { init: countAbortListeners });
|
||||||
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
||||||
@@ -772,13 +874,17 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await withLogs(sender, sender, async () => {
|
await withLogs(sender, sender, async () => {
|
||||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
await sender.click('#share');
|
await sender.click('#share');
|
||||||
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
await expect.poll(() => trackers.sockets.length).toBe(2);
|
await expect.poll(() => trackers.sockets.length).toBe(2);
|
||||||
for (let offers = 1; offers <= 25; offers++) {
|
for (let offers = 1; offers <= 25; offers++) {
|
||||||
trackers.sockets[0]!.send(garbageOffer());
|
trackers.sockets[0]!.send(garbageOffer(code));
|
||||||
await expect.poll(unusable).toBe(offers);
|
await expect.poll(unusable).toBe(offers);
|
||||||
// Once it accepted the announcement, a failure only concerns that one message.
|
// Once it accepted the announcement, a failure only concerns that one message.
|
||||||
if (offers === 1) trackers.sockets[0]!.send(JSON.stringify({ 'failure reason': 'slow down' }));
|
if (offers === 1) trackers.sockets[0]!.send(JSON.stringify({ 'failure reason': 'slow down' }));
|
||||||
}
|
}
|
||||||
|
for (let offers = 0; offers < 5; offers++) trackers.sockets[1]!.send(garbageOffer());
|
||||||
|
await expect.poll(async () => (await log(sender))!.match(/offer without the code/g)?.length ?? 0).toBe(5);
|
||||||
|
expect(await unusable()).toBe(25);
|
||||||
await expect(sender.locator('#log')).toContainText(': slow down');
|
await expect(sender.locator('#log')).toContainText(': slow down');
|
||||||
await expect(sender.locator('#log')).not.toContainText('rejected by');
|
await expect(sender.locator('#log')).not.toContainText('rejected by');
|
||||||
await expect(sender.locator('#send-error')).toHaveCount(0);
|
await expect(sender.locator('#send-error')).toHaveCount(0);
|
||||||
@@ -881,26 +987,58 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
|
// Opening an offer takes a moment, the share may expire meanwhile. Expired is expired, that offer
|
||||||
test(`live check: ${name} sender shares on after a mismatch`, async () => {
|
// gets no turn either.
|
||||||
|
test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => {
|
||||||
|
const sender = await open(name, { init: holdDecrypts });
|
||||||
|
await sender.clock.install();
|
||||||
|
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
||||||
|
const decrypts = () =>
|
||||||
|
sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts);
|
||||||
|
|
||||||
|
await withLogs(sender, sender, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
|
await expect.poll(() => trackers.sockets.length).toBe(2);
|
||||||
|
trackers.sockets[0]!.send(garbageOffer(code));
|
||||||
|
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
|
||||||
|
await sender.clock.fastForward('06:00');
|
||||||
|
await expect(sender.locator('#send-error')).toHaveText(
|
||||||
|
'nobody received the file within 6 minutes, share it again',
|
||||||
|
);
|
||||||
|
|
||||||
|
await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts());
|
||||||
|
// The handler goes on right after the decryption, before anything else the page does.
|
||||||
|
await expect.poll(decrypts).toEqual({ held: 0, done: 1 });
|
||||||
|
expect(await log(sender)).not.toContain('offer via');
|
||||||
|
await expectClosed(sender);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// A peer that found the swarm without the code, here one that announces another code on the
|
||||||
|
// sender's info_hash. Its offer isn't sealed with the code, the sender doesn't even answer it.
|
||||||
|
test(`live check: ${name} sender shares on after a peer without the code`, async () => {
|
||||||
const [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
|
const [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
|
||||||
const source = await payload(randomBytes(SIZE));
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await connect('tracker', sender, intruder, source);
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
await sender.click('#share');
|
||||||
await receiver.click('#receive');
|
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
|
||||||
await expect(receiver.locator('#log')).toContainText('looking on');
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
await sender.click('#reject');
|
await intrude(intruder, swarm(code));
|
||||||
|
await intruder.fill('#receive-code', 'notthecode');
|
||||||
|
await intruder.click('#receive');
|
||||||
|
await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 });
|
||||||
await intruder.context().close();
|
await intruder.context().close();
|
||||||
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
expect(await log(sender)).not.toContain('connected');
|
||||||
|
expect(await openPeers(sender)).toBe(0);
|
||||||
|
|
||||||
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
await receiver.fill('#receive-code', code);
|
||||||
await expect(sender.locator('#check-local')).toHaveText((await receiver.locator('#check-remote').textContent())!);
|
await receiver.click('#receive');
|
||||||
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
|
await proven(sender, receiver);
|
||||||
const started = downloadStarts(receiver);
|
const started = downloadStarts(receiver);
|
||||||
await sender.click('#confirm');
|
|
||||||
await receiver.click('#confirm');
|
|
||||||
await receiver.click('#download');
|
await receiver.click('#download');
|
||||||
const { download } = await started;
|
const { download } = await started;
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
expect(await hash(await download.path())).toBe(await hash(source));
|
||||||
@@ -908,34 +1046,22 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`live check: ${name} both sides go on after the receiver rejected`, async () => {
|
test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]);
|
||||||
|
await sender.clock.install();
|
||||||
const source = await payload(randomBytes(SIZE));
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await connect('tracker', sender, receiver, source);
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
const first = await receiver.locator('#check-local').textContent();
|
await MODES.tracker!(sender, receiver);
|
||||||
// Retrying still has to work for a side that already confirmed.
|
// The sender's proof still reaches the receiver.
|
||||||
await sender.click('#confirm');
|
await expect(receiver.locator('#log')).toContainText('security check passed', { timeout: 45_000 });
|
||||||
await receiver.click('#reject');
|
await expect(sender.locator('#log')).toContainText('waiting for the security check');
|
||||||
await expect(receiver.locator('#log')).toContainText('looking again');
|
await sender.clock.fastForward(PROOF_TIMEOUT);
|
||||||
// The sender notices the receiver left, Chromium only once the connection counts as failed.
|
await expect(sender.locator('#log')).toContainText('the peer proved no code');
|
||||||
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
|
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
||||||
|
expect(await log(sender)).not.toContain('offered');
|
||||||
await expect(receiver.locator('#check-local')).toHaveText(
|
await expect(sender.locator('#send-error')).toHaveCount(0);
|
||||||
new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`),
|
|
||||||
{
|
|
||||||
timeout: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
|
|
||||||
const started = downloadStarts(receiver);
|
|
||||||
await sender.click('#confirm');
|
|
||||||
await receiver.click('#confirm');
|
|
||||||
await receiver.click('#download');
|
|
||||||
const { download } = await started;
|
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
|
||||||
await expect(sender.locator('#log')).toContainText('delivered');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -957,7 +1083,167 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// What a broken or hostile receiver could announce for the code: an offer no browser can parse.
|
// Makes the page a tracker intruder: it announces its offers on the info_hash hash instead of its own,
|
||||||
|
// on TRACKER only and just the first offer. A later one could still take the sender's turn after the
|
||||||
|
// test closed the page.
|
||||||
|
async function intrude(page: Page, hash: string) {
|
||||||
|
let offered = false;
|
||||||
|
await page.routeWebSocket(/^wss:/, (ws) => {
|
||||||
|
if (!ws.url().startsWith(TRACKER)) return ws.close();
|
||||||
|
const server = ws.connectToServer();
|
||||||
|
ws.onMessage((data) => {
|
||||||
|
const msg = JSON.parse(String(data));
|
||||||
|
if (msg.offers && offered) return;
|
||||||
|
offered ||= !!msg.offers;
|
||||||
|
server.send(JSON.stringify({ ...msg, info_hash: hash }));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init script: the page never sends a proof of the code, everything else as usual. It runs in the
|
||||||
|
// hidden frames too, only the app's own window counts.
|
||||||
|
function withholdProof() {
|
||||||
|
if (window !== window.top) return;
|
||||||
|
const send = RTCDataChannel.prototype.send as (this: RTCDataChannel, data: unknown) => void;
|
||||||
|
RTCDataChannel.prototype.send = function (this: RTCDataChannel, data: unknown) {
|
||||||
|
if (typeof data === 'string' && data.includes('"proof"')) return;
|
||||||
|
send.call(this, data);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type Middle = {
|
||||||
|
// Proofs that passed through.
|
||||||
|
relayed: number;
|
||||||
|
answer: (sdp: string) => Promise<string>;
|
||||||
|
offer: (reflect: boolean) => Promise<string>;
|
||||||
|
accept: (sdp: string) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Init script for a man in the middle, driven by interpose: it answers the receiver's offer and
|
||||||
|
// offers to the sender itself, with its own certificate towards each, and relays every message
|
||||||
|
// between the two. With reflect it only connects to the sender and sends everything back. It runs
|
||||||
|
// in the hidden frames too, only the app's own window counts.
|
||||||
|
function middleman() {
|
||||||
|
if (window !== window.top) return;
|
||||||
|
type Side = 'sender' | 'receiver';
|
||||||
|
const channels: Partial<Record<Side, RTCDataChannel>> = {};
|
||||||
|
// What waits for that side's channel to open.
|
||||||
|
const queues: Record<Side, string[]> = { sender: [], receiver: [] };
|
||||||
|
const flush = (side: Side) => {
|
||||||
|
const channel = channels[side];
|
||||||
|
while (channel?.readyState === 'open' && queues[side].length) channel.send(queues[side].shift()!);
|
||||||
|
};
|
||||||
|
const attach = (side: Side, channel: RTCDataChannel, to: Side) => {
|
||||||
|
channels[side] = channel;
|
||||||
|
channel.addEventListener('message', ({ data }) => {
|
||||||
|
if (String(data).includes('"proof"')) middle.relayed++;
|
||||||
|
queues[to].push(data);
|
||||||
|
flush(to);
|
||||||
|
});
|
||||||
|
channel.addEventListener('open', () => flush(side));
|
||||||
|
flush(side);
|
||||||
|
};
|
||||||
|
const describe = async (pc: RTCPeerConnection) => {
|
||||||
|
await pc.setLocalDescription();
|
||||||
|
while (pc.iceGatheringState !== 'complete') {
|
||||||
|
await new Promise((resolve) => pc.addEventListener('icegatheringstatechange', resolve, { once: true }));
|
||||||
|
}
|
||||||
|
return pc.localDescription!.sdp;
|
||||||
|
};
|
||||||
|
let toSender: RTCPeerConnection;
|
||||||
|
const middle: Middle = {
|
||||||
|
relayed: 0,
|
||||||
|
async answer(sdp) {
|
||||||
|
const pc = new RTCPeerConnection();
|
||||||
|
pc.ondatachannel = ({ channel }) => attach('receiver', channel, 'sender');
|
||||||
|
await pc.setRemoteDescription({ type: 'offer', sdp });
|
||||||
|
return describe(pc);
|
||||||
|
},
|
||||||
|
offer(reflect) {
|
||||||
|
toSender = new RTCPeerConnection();
|
||||||
|
attach('sender', toSender.createDataChannel('file'), reflect ? 'sender' : 'receiver');
|
||||||
|
return describe(toSender);
|
||||||
|
},
|
||||||
|
accept: (sdp) => toSender.setRemoteDescription({ type: 'answer', sdp }),
|
||||||
|
};
|
||||||
|
(window as unknown as { middle: Middle }).middle = middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
const relayed = (page: Page) => page.evaluate(() => (window as unknown as { middle: Middle }).middle.relayed);
|
||||||
|
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: raw tracker messages, the test reads nested fields as it needs them
|
||||||
|
type Announce = { msg: Record<string, any>; ws: WebSocketRoute };
|
||||||
|
|
||||||
|
// Mocks the page's trackers and keeps what it announces, with the socket to answer on.
|
||||||
|
async function announces(page: Page) {
|
||||||
|
const announced: Announce[] = [];
|
||||||
|
await mockTrackers(page, (msg, ws) => {
|
||||||
|
announced.push({ msg, ws });
|
||||||
|
return { action: 'announce', interval: 120, info_hash: msg.info_hash };
|
||||||
|
});
|
||||||
|
return announced;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The first announcement that matches, once there is one.
|
||||||
|
async function first(announced: Announce[], match: (msg: Announce['msg']) => unknown) {
|
||||||
|
await expect.poll(() => announced.some(({ msg }) => match(msg))).toBe(true);
|
||||||
|
return announced.find(({ msg }) => match(msg))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Puts the middleman page between the sender and the receiver on their mocked trackers, as a tracker
|
||||||
|
// that knows the code could: it opens and seals the signaling, only the proofs can give it away.
|
||||||
|
// Without a receiver it reflects, see middleman.
|
||||||
|
async function interpose(middle: Page, code: string, toSender: Announce[], toReceiver?: Announce[]) {
|
||||||
|
const binary = () => randomBytes(20).toString('latin1');
|
||||||
|
const peerId = binary();
|
||||||
|
type Hosting = { middle: Middle };
|
||||||
|
|
||||||
|
if (toReceiver) {
|
||||||
|
const { msg, ws } = await first(toReceiver, (msg) => msg.offers);
|
||||||
|
const [{ offer, offer_id }] = msg.offers;
|
||||||
|
const sdp = await middle.evaluate(
|
||||||
|
(sdp) => (window as unknown as Hosting).middle.answer(sdp),
|
||||||
|
unseal(code, 'offer', offer.sdp),
|
||||||
|
);
|
||||||
|
const answer = { type: 'answer', sdp: seal(code, 'answer', sdp) };
|
||||||
|
ws.send(JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id, answer }));
|
||||||
|
}
|
||||||
|
const { msg, ws } = await first(toSender, (msg) => msg.event === 'started');
|
||||||
|
const sdp = await middle.evaluate((reflect) => (window as unknown as Hosting).middle.offer(reflect), !toReceiver);
|
||||||
|
const offer = { type: 'offer', sdp: seal(code, 'offer', sdp) };
|
||||||
|
ws.send(JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id: binary(), offer }));
|
||||||
|
const { msg: reply } = await first(toSender, (msg) => msg.answer);
|
||||||
|
await middle.evaluate(
|
||||||
|
(sdp) => (window as unknown as Hosting).middle.accept(sdp),
|
||||||
|
unseal(code, 'answer', reply.answer.sdp),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// What secrets in src/core.ts derives from the code for info, PBKDF2 once per code.
|
||||||
|
const masters = new Map<string, Buffer>();
|
||||||
|
function secret(code: string, info: string, length: number) {
|
||||||
|
if (!masters.has(code)) masters.set(code, pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'));
|
||||||
|
return Buffer.from(hkdfSync('sha256', masters.get(code)!, '', info, length));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The code's info_hash.
|
||||||
|
const swarm = (code: string) => secret(code, 'swarm', 20).toString('latin1');
|
||||||
|
|
||||||
|
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code.
|
||||||
|
function seal(code: string, type: 'offer' | 'answer', sdp: string) {
|
||||||
|
const iv = randomBytes(12);
|
||||||
|
const cipher = createCipheriv('aes-256-gcm', secret(code, 'signaling', 32), iv).setAAD(Buffer.from(type));
|
||||||
|
return Buffer.concat([iv, cipher.update(sdp), cipher.final(), cipher.getAuthTag()]).toString('base64');
|
||||||
|
}
|
||||||
|
|
||||||
|
function unseal(code: string, type: 'offer' | 'answer', sealed: string) {
|
||||||
|
const bytes = Buffer.from(sealed, 'base64');
|
||||||
|
const decipher = createDecipheriv('aes-256-gcm', secret(code, 'signaling', 32), bytes.subarray(0, 12));
|
||||||
|
decipher.setAAD(Buffer.from(type)).setAuthTag(bytes.subarray(-16));
|
||||||
|
return Buffer.concat([decipher.update(bytes.subarray(12, -16)), decipher.final()]).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a broken or hostile receiver could announce with the code: an offer no browser can parse.
|
||||||
async function announceGarbage(code: string) {
|
async function announceGarbage(code: string) {
|
||||||
const ws = new WebSocket(TRACKER);
|
const ws = new WebSocket(TRACKER);
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
@@ -968,40 +1254,40 @@ async function announceGarbage(code: string) {
|
|||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
action: 'announce',
|
action: 'announce',
|
||||||
info_hash: binary(createHash('sha1').update(`hellcon:${code}`).digest()),
|
info_hash: swarm(code),
|
||||||
peer_id: binary(randomBytes(20)),
|
peer_id: binary(randomBytes(20)),
|
||||||
numwant: 1,
|
numwant: 1,
|
||||||
uploaded: 0,
|
uploaded: 0,
|
||||||
downloaded: 0,
|
downloaded: 0,
|
||||||
left: 1,
|
left: 1,
|
||||||
event: 'started',
|
event: 'started',
|
||||||
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: 'garbage' } }],
|
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: seal(code, 'offer', 'garbage') } }],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return ws;
|
return ws;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stands in for every tracker the page connects to from now on: reply answers each message the page
|
// Stands in for every tracker the page connects to from now on: reply answers each message the page
|
||||||
// sends. The sockets let a test send what a tracker relays from other peers, open counts those the
|
// sends, on the socket it came from. The sockets let a test send what a tracker relays from other
|
||||||
// page didn't close yet. They don't show up in sockets.
|
// peers, open counts those the page didn't close yet. They don't show up in sockets.
|
||||||
async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>) => object) {
|
async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>, ws: WebSocketRoute) => object) {
|
||||||
const trackers = { sockets: [] as WebSocketRoute[], open: 0 };
|
const trackers = { sockets: [] as WebSocketRoute[], open: 0 };
|
||||||
await page.routeWebSocket(/^wss:/, (ws) => {
|
await page.routeWebSocket(/^wss:/, (ws) => {
|
||||||
trackers.sockets.push(ws);
|
trackers.sockets.push(ws);
|
||||||
trackers.open++;
|
trackers.open++;
|
||||||
ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data))))));
|
ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data)), ws))));
|
||||||
ws.onClose(() => trackers.open--);
|
ws.onClose(() => trackers.open--);
|
||||||
});
|
});
|
||||||
return trackers;
|
return trackers;
|
||||||
}
|
}
|
||||||
|
|
||||||
// What a tracker relays from a receiver: an offer no browser can parse.
|
// What a tracker relays from a receiver: an offer no browser can parse, sealed with code if given.
|
||||||
const garbageOffer = () =>
|
const garbageOffer = (code?: string) =>
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
action: 'announce',
|
action: 'announce',
|
||||||
peer_id: randomBytes(20).toString('latin1'),
|
peer_id: randomBytes(20).toString('latin1'),
|
||||||
offer_id: randomBytes(20).toString('latin1'),
|
offer_id: randomBytes(20).toString('latin1'),
|
||||||
offer: { type: 'offer', sdp: 'garbage' },
|
offer: { type: 'offer', sdp: code ? seal(code, 'offer', 'garbage') : 'garbage' },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal
|
// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal
|
||||||
@@ -1023,6 +1309,32 @@ function countAbortListeners() {
|
|||||||
(window as unknown as { abortListeners: () => number }).abortListeners = () => listeners.size;
|
(window as unknown as { abortListeners: () => number }).abortListeners = () => listeners.size;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Init script: holds every decryption back until window.releaseDecrypts(), as if it took that long.
|
||||||
|
// window.decrypts counts those held and those done. It runs in the hidden frames too, only the app's
|
||||||
|
// own window counts.
|
||||||
|
function holdDecrypts() {
|
||||||
|
if (window !== window.top) return;
|
||||||
|
const decrypts = { held: 0, done: 0 };
|
||||||
|
const waiting: (() => void)[] = [];
|
||||||
|
const decrypt = crypto.subtle.decrypt.bind(crypto.subtle);
|
||||||
|
crypto.subtle.decrypt = (...args) =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
decrypts.held++;
|
||||||
|
waiting.push(() =>
|
||||||
|
decrypt(...args).then((result) => {
|
||||||
|
decrypts.done++;
|
||||||
|
resolve(result);
|
||||||
|
}, reject),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const page = window as unknown as { decrypts: typeof decrypts; releaseDecrypts: () => void };
|
||||||
|
page.decrypts = decrypts;
|
||||||
|
page.releaseDecrypts = () => {
|
||||||
|
decrypts.held = 0;
|
||||||
|
for (const release of waiting.splice(0)) release();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry.
|
// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry.
|
||||||
// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own
|
// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own
|
||||||
// window counts.
|
// window counts.
|
||||||
|
|||||||
+148
-36
@@ -33,6 +33,11 @@ const CONNECT_TIMEOUT = 30_000;
|
|||||||
// else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names.
|
// else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names.
|
||||||
export const TRACKER_WAIT = 6 * 60_000;
|
export const TRACKER_WAIT = 6 * 60_000;
|
||||||
const MIN_INTERVAL = 30_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;
|
||||||
|
// 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;
|
||||||
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
|
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
|
||||||
const MAX_NAME = 1024;
|
const MAX_NAME = 1024;
|
||||||
|
|
||||||
@@ -48,7 +53,8 @@ export type Events = {
|
|||||||
log: (message: string) => void;
|
log: (message: string) => void;
|
||||||
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||||
error: (message: string) => void;
|
error: (message: string) => void;
|
||||||
// Called on both sides once connected, and without a check when it ended undecided.
|
// Called on both sides once connected by the manual exchange, and without a check when it ended
|
||||||
|
// undecided. Tracker signaling has the code to prove the connection, nobody has to compare anything.
|
||||||
check: (check?: Check) => void;
|
check: (check?: Check) => void;
|
||||||
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
|
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
|
||||||
// the transfer starts.
|
// the transfer starts.
|
||||||
@@ -141,10 +147,54 @@ function randomCode() {
|
|||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
|
// The code is all both sides share. It gives the tracker swarm, identified by a 20 byte info_hash,
|
||||||
async function infoHash(code: string) {
|
// and the key that proves the connection, see prove. Whoever sees the swarms, a tracker or anyone
|
||||||
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
// scraping one, can test a guessed code against all of them at once. PBKDF2 makes every guess cost
|
||||||
return String.fromCharCode(...new Uint8Array(digest));
|
// what a share pays once (~50 ms), so a GPU gets through a vanishing part of the 62⁸ codes within
|
||||||
|
// TRACKER_WAIT. The salt is fixed, both sides only know the code. 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) {
|
||||||
|
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'), iterations: PBKDF2_ITERATIONS },
|
||||||
|
password,
|
||||||
|
256,
|
||||||
|
);
|
||||||
|
const master = await crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']);
|
||||||
|
const expand = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: text.encode(info) });
|
||||||
|
const hash = await crypto.subtle.deriveBits(expand('swarm'), master, 160);
|
||||||
|
const key = await crypto.subtle.deriveKey(expand('proof'), master, { name: 'HMAC', hash: 'SHA-256' }, false, [
|
||||||
|
'sign',
|
||||||
|
'verify',
|
||||||
|
]);
|
||||||
|
const sealing = await crypto.subtle.deriveKey(expand('signaling'), master, { name: 'AES-GCM', length: 256 }, false, [
|
||||||
|
'encrypt',
|
||||||
|
'decrypt',
|
||||||
|
]);
|
||||||
|
return { hash: String.fromCharCode(...new Uint8Array(hash)), key, sealing };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tracker signaling carries the SDP sealed with the code: neither the trackers nor a peer that found
|
||||||
|
// 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) {
|
||||||
|
const text = new TextEncoder();
|
||||||
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||||
|
const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) };
|
||||||
|
const sealed = await crypto.subtle.encrypt(params, key, text.encode(sdp));
|
||||||
|
return btoa(String.fromCharCode(...iv, ...new Uint8Array(sealed)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The SDP, unless it wasn't sealed with the code as that type.
|
||||||
|
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));
|
||||||
|
const params = { name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: new TextEncoder().encode(type) };
|
||||||
|
return new TextDecoder().decode(await crypto.subtle.decrypt(params, key, bytes.subarray(12)));
|
||||||
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||||
@@ -195,11 +245,58 @@ function securityCheck(pc: RTCPeerConnection) {
|
|||||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||||
}
|
}
|
||||||
|
|
||||||
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
|
// Every fingerprint the SDP names, in full: one added beside the real one changes the result too.
|
||||||
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
|
// Browsers may move them between session and media level, so each counts once.
|
||||||
// needs both confirmations, a rejected check, a peer that left or end closes the connection and calls
|
const fingerprints = (sdp: string) =>
|
||||||
// next: tracker signaling goes on with another peer. Without next, as in the manual exchange, the
|
[...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort();
|
||||||
// session is over and the reason is an error. From start on, sendFile and receiveFile handle a loss.
|
|
||||||
|
// 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) {
|
||||||
|
const local = pc.localDescription!;
|
||||||
|
const remote = pc.remoteDescription!;
|
||||||
|
const statement = (type: string, own: string, peer: string) =>
|
||||||
|
new TextEncoder().encode(JSON.stringify([type, fingerprints(own), fingerprints(peer)]));
|
||||||
|
const send = async () => {
|
||||||
|
const proof = await crypto.subtle.sign('HMAC', key, statement(local.type, local.sdp, remote.sdp));
|
||||||
|
if (channel.readyState !== 'open') return;
|
||||||
|
channel.send(JSON.stringify({ proof: btoa(String.fromCharCode(...new Uint8Array(proof))) }));
|
||||||
|
};
|
||||||
|
if (channel.readyState === 'open') void send();
|
||||||
|
else channel.addEventListener('open', () => void send(), { once: true });
|
||||||
|
|
||||||
|
return new Promise<void>((resolve) => {
|
||||||
|
const timeout = setTimeout(() => end('the peer proved no code'), PROOF_TIMEOUT);
|
||||||
|
const check = async (event: MessageEvent) => {
|
||||||
|
const proof = parse(event.data)?.proof;
|
||||||
|
if (typeof proof !== 'string') return;
|
||||||
|
// Registered before sendFile and receiveFile, which must not see it: Chromium can verify before
|
||||||
|
// the next listener runs, the receiver would take the proof for the sender's offer then.
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
channel.removeEventListener('message', check);
|
||||||
|
clearTimeout(timeout);
|
||||||
|
// atob throws on what isn't base64.
|
||||||
|
let valid = false;
|
||||||
|
try {
|
||||||
|
const signature = Uint8Array.from(atob(proof), (char) => char.charCodeAt(0));
|
||||||
|
valid = await crypto.subtle.verify('HMAC', key, signature, statement(remote.type, remote.sdp, local.sdp));
|
||||||
|
} catch {}
|
||||||
|
if (valid) resolve();
|
||||||
|
else end('security check failed, the peer does not know the code');
|
||||||
|
};
|
||||||
|
channel.addEventListener('message', check);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// checked resolves once the security check passed: by the user confirming the codes, or with a key
|
||||||
|
// once the peer proved the code. Both sides wait for it: the sender sends nothing to a man in the
|
||||||
|
// middle, the receiver accepts no file from one. Until the transfer starts, which needs both sides to
|
||||||
|
// 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 };
|
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
||||||
|
|
||||||
function connected(
|
function connected(
|
||||||
@@ -208,6 +305,7 @@ function connected(
|
|||||||
via: string,
|
via: string,
|
||||||
events: Events,
|
events: Events,
|
||||||
next?: () => void,
|
next?: () => void,
|
||||||
|
key?: CryptoKey,
|
||||||
): Handshake {
|
): Handshake {
|
||||||
events.log(`connected via ${via}`);
|
events.log(`connected via ${via}`);
|
||||||
events.log('waiting for the security check');
|
events.log('waiting for the security check');
|
||||||
@@ -227,7 +325,9 @@ function connected(
|
|||||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
checked: new Promise((resolve) =>
|
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') }),
|
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||||
),
|
),
|
||||||
start: () => (done = true),
|
start: () => (done = true),
|
||||||
@@ -585,13 +685,14 @@ 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
|
// 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
|
// 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. lost runs once it closed without close() being
|
// later one only concerns that message and is logged. message may be async, the next message doesn't
|
||||||
// called: unreachable, lost or rejected. again announces once more, on the first interval it names.
|
// wait for it. lost runs once it closed without close() being called: unreachable, lost or rejected.
|
||||||
|
// again announces once more, on the first interval it names.
|
||||||
function trackerSocket(
|
function trackerSocket(
|
||||||
url: string,
|
url: string,
|
||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
events: Events,
|
events: Events,
|
||||||
message: (msg: Message) => void,
|
message: (msg: Message) => void | Promise<void>,
|
||||||
lost: () => void,
|
lost: () => void,
|
||||||
again: () => void,
|
again: () => void,
|
||||||
) {
|
) {
|
||||||
@@ -632,7 +733,7 @@ function trackerSocket(
|
|||||||
if (!reannounce && !closed && typeof msg.interval === 'number') {
|
if (!reannounce && !closed && typeof msg.interval === 'number') {
|
||||||
reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000)));
|
reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000)));
|
||||||
}
|
}
|
||||||
return message(msg);
|
return void message(msg);
|
||||||
}
|
}
|
||||||
if (accepted) return events.log(`${url}: ${failure}`);
|
if (accepted) return events.log(`${url}: ${failure}`);
|
||||||
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
|
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
|
||||||
@@ -652,14 +753,15 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
||||||
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
|
// time. An offer not sealed with the code gets no turn, a peer that found the swarm without it doesn't
|
||||||
// the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be
|
// even learn the sender's address. Until a receiver proved the code, the next one gets its turn: an
|
||||||
// answered or never connects. Once the download started the share is used up, the trackers go. After
|
// offer that can't be answered, never connects or proves nothing doesn't end the share. Once the
|
||||||
// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn.
|
// download started the share is used up, the trackers go. After TRACKER_WAIT they go as well, a
|
||||||
|
// receiver connected by then still gets its turn.
|
||||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
const code = randomCode();
|
const code = randomCode();
|
||||||
const hash = await infoHash(code);
|
const { hash, key, sealing } = await secrets(code);
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
const trackers: Tracker[] = [];
|
const trackers: Tracker[] = [];
|
||||||
let busy = false;
|
let busy = false;
|
||||||
@@ -715,7 +817,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
const handshake = connected(pc, channel, url, events, next);
|
const handshake = connected(pc, channel, url, events, next, key);
|
||||||
const start = () => {
|
const start = () => {
|
||||||
handshake.start();
|
handshake.start();
|
||||||
shared = true;
|
shared = true;
|
||||||
@@ -728,10 +830,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
pc.addEventListener('connectionstatechange', () => {
|
pc.addEventListener('connectionstatechange', () => {
|
||||||
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
||||||
});
|
});
|
||||||
|
let sdp: string;
|
||||||
try {
|
try {
|
||||||
await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp });
|
await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp });
|
||||||
await pc.setLocalDescription();
|
await pc.setLocalDescription();
|
||||||
await gatherIce(pc);
|
await gatherIce(pc);
|
||||||
|
sdp = await seal(sealing, 'answer', pc.localDescription!.sdp);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return giveUp(`unusable offer via ${url}: ${error}`);
|
return giveUp(`unusable offer via ${url}: ${error}`);
|
||||||
}
|
}
|
||||||
@@ -740,7 +844,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
left: 0,
|
left: 0,
|
||||||
to_peer_id: msg.peer_id,
|
to_peer_id: msg.peer_id,
|
||||||
offer_id: msg.offer_id,
|
offer_id: msg.offer_id,
|
||||||
answer: pc.localDescription,
|
answer: { type: 'answer', sdp },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -749,11 +853,15 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
url,
|
url,
|
||||||
signal,
|
signal,
|
||||||
events,
|
events,
|
||||||
(msg) => {
|
async (msg) => {
|
||||||
// What a tracker relays from a receiver, anything else is ignored.
|
// What a tracker relays from a receiver, anything else is ignored.
|
||||||
if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return;
|
if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return;
|
||||||
if (typeof msg.offer_id !== 'string') return;
|
if (typeof msg.offer_id !== 'string') return;
|
||||||
const offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
|
||||||
|
// Meanwhile the share may have been used up, expired or ended, its trackers closed then.
|
||||||
|
if (signal.aborted || !tracker.alive()) return;
|
||||||
|
if (sdp === undefined) return events.log(`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);
|
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||||
else void answer(tracker.ws, url, offer);
|
else void answer(tracker.ws, url, offer);
|
||||||
},
|
},
|
||||||
@@ -772,13 +880,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
|
|
||||||
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
|
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
|
||||||
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
|
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
|
||||||
// queued one of them. An answer that can't be used or never connects is replaced right away. Once the
|
// queued one of them. An answer not sealed with the code is ignored, the offer waits for the real one.
|
||||||
// download started, every other offer and tracker socket goes. After TRACKER_WAIT no offer is made or
|
// One that can't be used or never connects is replaced right away. Once the download started, every
|
||||||
// kept any more, a sender connected by then still gets its turn.
|
// other offer and tracker socket goes. After TRACKER_WAIT no offer is made or kept any more, a sender
|
||||||
|
// connected by then still gets its turn.
|
||||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
await downloadsReady();
|
await downloadsReady();
|
||||||
const hash = await infoHash(code.trim());
|
const { hash, key, sealing } = await secrets(code.trim());
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
||||||
@@ -832,7 +941,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
if (isConnected || started) return pc.close();
|
if (isConnected || started) return pc.close();
|
||||||
isConnected = true;
|
isConnected = true;
|
||||||
const handshake = connected(pc, channel, url, events, next);
|
const handshake = connected(pc, channel, url, events, next, key);
|
||||||
const start = () => {
|
const start = () => {
|
||||||
handshake.start();
|
handshake.start();
|
||||||
started = true;
|
started = true;
|
||||||
@@ -851,7 +960,8 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
|
|
||||||
pc.setLocalDescription()
|
pc.setLocalDescription()
|
||||||
.then(() => gatherIce(pc))
|
.then(() => gatherIce(pc))
|
||||||
.then(() => {
|
.then(() => seal(sealing, 'offer', pc.localDescription!.sdp))
|
||||||
|
.then((sdp) => {
|
||||||
if (pc.signalingState === 'closed' || expired) return;
|
if (pc.signalingState === 'closed' || expired) return;
|
||||||
// Again with the same offer on the interval, a busy sender may have dropped it meanwhile.
|
// Again with the same offer on the interval, a busy sender may have dropped it meanwhile.
|
||||||
const hello = (event?: string) =>
|
const hello = (event?: string) =>
|
||||||
@@ -859,21 +969,23 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
left: 1,
|
left: 1,
|
||||||
numwant: 1,
|
numwant: 1,
|
||||||
event,
|
event,
|
||||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
offers: [{ offer_id: offerId, offer: { type: 'offer', sdp } }],
|
||||||
});
|
});
|
||||||
const tracker = trackerSocket(
|
const tracker = trackerSocket(
|
||||||
url,
|
url,
|
||||||
signal,
|
signal,
|
||||||
events,
|
events,
|
||||||
(msg) => {
|
async (msg) => {
|
||||||
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
|
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
|
||||||
|
const answer = await unseal(sealing, 'answer', msg.answer.sdp);
|
||||||
|
// 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}`);
|
||||||
events.log(`answer via ${url}`);
|
events.log(`answer via ${url}`);
|
||||||
// Only one answer per offer, a replacement opens its own socket.
|
|
||||||
tracker.close();
|
tracker.close();
|
||||||
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
|
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
|
||||||
pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() =>
|
pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
|
||||||
retry(`unusable answer via ${url}`),
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
entry.lost = true;
|
entry.lost = true;
|
||||||
|
|||||||
Reference in new issue
Block a user