Compare commits
4
Commits
85ccdbfc03
...
a35bd71ca7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a35bd71ca7 | ||
|
|
0df1dd4f70 | ||
|
|
2abd0b504d | ||
|
|
bacc15baaf |
No files matched your search
@@ -1 +1,102 @@
|
|||||||
# HellCon
|
# HellCon
|
||||||
|
|
||||||
|
Send a file straight from one browser to another. No account, no upload, no app to install, and no
|
||||||
|
size limit: the file goes directly to the other person and is never stored on a server.
|
||||||
|
|
||||||
|
## How to send a file
|
||||||
|
|
||||||
|
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.
|
||||||
|
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
||||||
|
3. **Both:** compare the security check (see below) and click **Codes match**.
|
||||||
|
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
|
||||||
|
tab was doing.
|
||||||
|
|
||||||
|
### Without a tracker
|
||||||
|
|
||||||
|
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
|
||||||
|
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
||||||
|
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
||||||
|
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
||||||
|
you're sending to.
|
||||||
|
|
||||||
|
## The security check
|
||||||
|
|
||||||
|
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 **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.
|
||||||
|
|
||||||
|
The codes are taken from the encryption keys of the connection. Someone in between would need their
|
||||||
|
own keys, which show up as different codes.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
The file travels over a direct, encrypted WebRTC connection between the two browsers. To set that up,
|
||||||
|
the browsers need two things:
|
||||||
|
|
||||||
|
- **Finding each other.** The code puts both browsers into the same group on a public
|
||||||
|
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
|
||||||
|
forth. It never sees the file. With the manual exchange you play the tracker yourself.
|
||||||
|
- **Reaching each other.** Most devices sit behind a router and don't know their public address.
|
||||||
|
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
|
||||||
|
only on the same network or over a VPN.
|
||||||
|
|
||||||
|
On the receiving side, HellCon hands the incoming data to the browser's own download manager while
|
||||||
|
it arrives. That's why files larger than your memory work too, and why the download shows up in
|
||||||
|
your browser's download list.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Privacy
|
||||||
|
|
||||||
|
- 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
|
||||||
|
servers see it too.
|
||||||
|
- 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,
|
||||||
|
host your own (below).
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
|
||||||
|
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
|
||||||
|
brings back the original lists. Both sides must use at least one tracker in common to find each
|
||||||
|
other.
|
||||||
|
|
||||||
|
## Host your own
|
||||||
|
|
||||||
|
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm install
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
|
||||||
|
work, and HellCon tells you so.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT, see [LICENSE](LICENSE).
|
||||||
+577
-161
@@ -1,25 +1,56 @@
|
|||||||
import { createHash, randomBytes } from 'node:crypto';
|
import { createHash, randomBytes } from 'node:crypto';
|
||||||
|
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';
|
||||||
import { chromium, expect, firefox, test, type Browser, type BrowserType, type Page } from '@playwright/test';
|
import { networkInterfaces } from 'node:os';
|
||||||
import { createServer, type ViteDevServer } from 'vite';
|
import {
|
||||||
|
chromium,
|
||||||
|
expect,
|
||||||
|
firefox,
|
||||||
|
test,
|
||||||
|
type Browser,
|
||||||
|
type BrowserContext,
|
||||||
|
type BrowserType,
|
||||||
|
type Page,
|
||||||
|
type WebSocket as PageSocket,
|
||||||
|
type WebSocketRoute,
|
||||||
|
} from '@playwright/test';
|
||||||
|
import { build, createServer, preview, type ViteDevServer } from 'vite';
|
||||||
|
|
||||||
// Runs against the real public trackers and STUN servers, the defaults in src/main.ts.
|
|
||||||
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
|
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
|
||||||
|
// Chromium needs a permission for the copy buttons, Firefox lets the click do it and rejects the name.
|
||||||
|
const PERMISSIONS: Record<string, string[]> = { chromium: ['clipboard-write'], firefox: [] };
|
||||||
|
// The live tests use the public trackers and STUN servers, the defaults in src/core.ts.
|
||||||
|
const TRACKER = 'wss://tracker.webtorrent.dev';
|
||||||
const SIZE = 5_000_000;
|
const SIZE = 5_000_000;
|
||||||
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
|
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
|
||||||
// staging could store in incognito-like contexts.
|
// staging could store in incognito-like contexts.
|
||||||
const LARGE_SIZE = 2.5 * 2 ** 30;
|
const LARGE_SIZE = 2.5 * 2 ** 30;
|
||||||
// Big enough that the transfer still runs while a test updates sw.js, 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 in src/main.ts.
|
// WINDOW, CHUNK_SIZE and ICE_TIMEOUT in src/core.ts.
|
||||||
const WINDOW = 8 * 2 ** 20;
|
const WINDOW = 8 * 2 ** 20;
|
||||||
|
const ICE_TIMEOUT = 5000;
|
||||||
|
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
||||||
|
const HELD_SIZE = 3 * WINDOW;
|
||||||
|
// What the fake STUN server reports as public address, reserved for documentation.
|
||||||
|
const PUBLIC_ADDRESS = '203.0.113.5';
|
||||||
|
// Where the browsers reach the fake STUN server. Firefox sends nothing to a loopback one, and the
|
||||||
|
// browsers gather from the network interfaces anyway, without one no test connects.
|
||||||
|
const LOCAL_ADDRESS =
|
||||||
|
Object.values(networkInterfaces())
|
||||||
|
.flat()
|
||||||
|
.find((address) => address?.family === 'IPv4' && !address.internal)?.address ?? '127.0.0.1';
|
||||||
|
|
||||||
// Each mode connects a sender page that already picked a file to a receiver page.
|
// Each mode connects a sender page that already picked a file to a receiver page.
|
||||||
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
||||||
async manual(sender, receiver) {
|
async manual(sender, receiver) {
|
||||||
|
await sender.click('#send-manual summary');
|
||||||
await sender.click('#create-offer');
|
await sender.click('#create-offer');
|
||||||
await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
|
await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
|
||||||
|
await sender.click('#copy-offer');
|
||||||
|
await expect(sender.locator('#copy-offer')).toHaveText('Copied');
|
||||||
|
await receiver.click('#receive-manual summary');
|
||||||
await receiver.fill('#offer-input', await sender.inputValue('#offer'));
|
await receiver.fill('#offer-input', await sender.inputValue('#offer'));
|
||||||
await receiver.click('#create-answer');
|
await receiver.click('#create-answer');
|
||||||
await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 });
|
await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 });
|
||||||
@@ -34,21 +65,11 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
|||||||
expect(Buffer.from(code, 'base64').toString()).not.toContain('typ srflx');
|
expect(Buffer.from(code, 'base64').toString()).not.toContain('typ srflx');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 192.0.2.1 is reserved for documentation and never answers, without the early stop in
|
|
||||||
// gatherIce Chromium would wait 40 s per side, with only the hard timeout still 10 s.
|
|
||||||
async 'dead-stun'(sender, receiver) {
|
|
||||||
for (const page of [sender, receiver]) {
|
|
||||||
await page.click('#servers summary');
|
|
||||||
const servers = await page.inputValue('#stun-servers');
|
|
||||||
await page.fill('#stun-servers', `${servers}\nstun:192.0.2.1:3478`);
|
|
||||||
}
|
|
||||||
const start = Date.now();
|
|
||||||
await MODES.manual!(sender, receiver);
|
|
||||||
expect(Date.now() - start).toBeLessThan(4000);
|
|
||||||
},
|
|
||||||
async tracker(sender, receiver) {
|
async tracker(sender, receiver) {
|
||||||
await sender.click('#share');
|
await sender.click('#share');
|
||||||
await expect(sender.locator('#send-code')).toHaveText(/^\d{8}$/);
|
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{8}$/);
|
||||||
|
await sender.click('#copy-send-code');
|
||||||
|
await expect(sender.locator('#copy-send-code')).toHaveText('Copied');
|
||||||
await expect(sender.locator('#log')).toContainText('waiting on');
|
await expect(sender.locator('#log')).toContainText('waiting on');
|
||||||
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
@@ -57,9 +78,16 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
|||||||
|
|
||||||
let server: ViteDevServer;
|
let server: ViteDevServer;
|
||||||
let url: string;
|
let url: string;
|
||||||
const browsers: Browser[] = [];
|
let stun: Socket;
|
||||||
// Appended to sw.js, so raising it makes the browser see an update, like a deploy.
|
// Appended to sw.js, so raising it makes the browser see an update, like a deploy.
|
||||||
let swVersion = 0;
|
let swVersion = 0;
|
||||||
|
// Launched once per worker on first use. Every test gets fresh contexts, closed right after it.
|
||||||
|
const browsers: Record<string, Promise<Browser>> = {};
|
||||||
|
let contexts: BrowserContext[] = [];
|
||||||
|
// Uncaught errors in the test's pages, they fail it even if everything else passed.
|
||||||
|
let errors: string[] = [];
|
||||||
|
// Tracker sockets per page, the dev server's own one left out.
|
||||||
|
const sockets = new Map<Page, PageSocket[]>();
|
||||||
|
|
||||||
test.describe.configure({ mode: 'parallel' });
|
test.describe.configure({ mode: 'parallel' });
|
||||||
test.setTimeout(60_000);
|
test.setTimeout(60_000);
|
||||||
@@ -82,24 +110,62 @@ test.beforeAll(async () => {
|
|||||||
});
|
});
|
||||||
await server.listen();
|
await server.listen();
|
||||||
url = server.resolvedUrls!.local[0]!;
|
url = server.resolvedUrls!.local[0]!;
|
||||||
|
stun = await fakeStun();
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterEach(async () => {
|
||||||
|
await Promise.all(contexts.map((context) => context.close()));
|
||||||
|
contexts = [];
|
||||||
|
sockets.clear();
|
||||||
|
const uncaught = errors;
|
||||||
|
errors = [];
|
||||||
|
expect(uncaught).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test.afterAll(async () => {
|
test.afterAll(async () => {
|
||||||
await Promise.all(browsers.map((browser) => browser.close()));
|
await Promise.all(Object.values(browsers).map(async (browser) => (await browser).close()));
|
||||||
await server.close();
|
await server.close();
|
||||||
|
stun.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
// init runs in the page before the app.
|
// init runs in the page before the app. base is the app's URL, the dev server's by default.
|
||||||
async function open(name: string, sockets: string[], init?: () => void) {
|
async function open(name: string, { init, base = url }: { init?: () => void; base?: string } = {}) {
|
||||||
const browser = await BROWSERS[name]!.launch();
|
const browser = await (browsers[name] ??= BROWSERS[name]!.launch());
|
||||||
browsers.push(browser);
|
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
|
||||||
const page = await (await browser.newContext()).newPage();
|
contexts.push(context);
|
||||||
page.on('websocket', (ws) => sockets.push(ws.url()));
|
const page = await context.newPage();
|
||||||
|
const trackers: PageSocket[] = [];
|
||||||
|
sockets.set(page, trackers);
|
||||||
|
page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws));
|
||||||
|
page.on('pageerror', (error) => errors.push(`${name}: ${error.message}`));
|
||||||
|
await page.addInitScript(trackPeers);
|
||||||
if (init) await page.addInitScript(init);
|
if (init) await page.addInitScript(init);
|
||||||
await page.goto(url);
|
await page.goto(base);
|
||||||
return page;
|
return page;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Answers every STUN binding request with PUBLIC_ADDRESS, instantly and without network access.
|
||||||
|
async function fakeStun() {
|
||||||
|
const socket = createSocket('udp4');
|
||||||
|
socket.on('message', (request, from) => {
|
||||||
|
if (request.length < 20 || request.readUInt16BE(0) !== 0x0001) return;
|
||||||
|
const response = Buffer.alloc(32);
|
||||||
|
// Binding success with the request's cookie and transaction id, then XOR-MAPPED-ADDRESS.
|
||||||
|
response.writeUInt16BE(0x0101, 0);
|
||||||
|
response.writeUInt16BE(12, 2);
|
||||||
|
request.copy(response, 4, 4, 20);
|
||||||
|
response.writeUInt16BE(0x0020, 20);
|
||||||
|
response.writeUInt16BE(8, 22);
|
||||||
|
response.writeUInt16BE(0x0001, 24);
|
||||||
|
response.writeUInt16BE(from.port ^ 0x2112, 26);
|
||||||
|
const address = PUBLIC_ADDRESS.split('.').reduce((value, byte) => value * 256 + Number(byte), 0);
|
||||||
|
response.writeUInt32BE((address ^ 0x2112a442) >>> 0, 28);
|
||||||
|
socket.send(response, from.port, from.address);
|
||||||
|
});
|
||||||
|
await new Promise<void>((resolve) => socket.bind(0, LOCAL_ADDRESS, resolve));
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
async function hash(path: string) {
|
async function hash(path: string) {
|
||||||
const sha = createHash('sha256');
|
const sha = createHash('sha256');
|
||||||
for await (const chunk of createReadStream(path)) sha.update(chunk);
|
for await (const chunk of createReadStream(path)) sha.update(chunk);
|
||||||
@@ -108,6 +174,31 @@ async function hash(path: string) {
|
|||||||
|
|
||||||
const log = (page: Page) => page.locator('#log').textContent();
|
const log = (page: Page) => page.locator('#log').textContent();
|
||||||
|
|
||||||
|
// Init script for every page: keeps its peer connections in window.peers, so a test can check that
|
||||||
|
// they were closed. It runs in the hidden frames too, only the app's own window counts.
|
||||||
|
function trackPeers() {
|
||||||
|
if (window !== window.top) return;
|
||||||
|
const page = window as unknown as { peers: RTCPeerConnection[] };
|
||||||
|
page.peers = [];
|
||||||
|
const PeerConnection = RTCPeerConnection;
|
||||||
|
window.RTCPeerConnection = class extends PeerConnection {
|
||||||
|
constructor(config?: RTCConfiguration) {
|
||||||
|
super(config);
|
||||||
|
page.peers.push(this);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
|
||||||
|
async function expectClosed(page: Page) {
|
||||||
|
const peers = () =>
|
||||||
|
page.evaluate(() =>
|
||||||
|
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
|
||||||
|
);
|
||||||
|
await expect.poll(peers).toBe(0);
|
||||||
|
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
// Init script for a receiver: holds back its { read } reports to the sender until release(), as if
|
// Init script for a receiver: holds back its { read } reports to the sender until release(), as if
|
||||||
// the download manager read nothing, and counts the bytes that arrive. It runs in the hidden frames
|
// the download manager read nothing, and counts the bytes that arrive. It runs in the hidden frames
|
||||||
// too, only the app's own window counts.
|
// too, only the app's own window counts.
|
||||||
@@ -138,9 +229,10 @@ function holdReads() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init script for a sender: keeps its data channels in window.channels, so a test can send on them
|
// Init script: keeps the page's data channels in window.channels, its own and the peer's, so a test
|
||||||
// like a peer that skips the security check.
|
// can send on them like a peer that skips the security check or breaks the protocol.
|
||||||
function recordChannels() {
|
function recordChannels() {
|
||||||
|
if (window !== window.top) return;
|
||||||
const page = window as unknown as { channels: RTCDataChannel[] };
|
const page = window as unknown as { channels: RTCDataChannel[] };
|
||||||
page.channels = [];
|
page.channels = [];
|
||||||
const create = RTCPeerConnection.prototype.createDataChannel;
|
const create = RTCPeerConnection.prototype.createDataChannel;
|
||||||
@@ -149,8 +241,25 @@ function recordChannels() {
|
|||||||
page.channels.push(channel);
|
page.channels.push(channel);
|
||||||
return channel;
|
return channel;
|
||||||
};
|
};
|
||||||
|
const PeerConnection = RTCPeerConnection;
|
||||||
|
window.RTCPeerConnection = class extends PeerConnection {
|
||||||
|
constructor(config?: RTCConfiguration) {
|
||||||
|
super(config);
|
||||||
|
this.addEventListener('datachannel', ({ channel }) => page.channels.push(channel));
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends on the page's first data channel, past the app: strings as they are, a number as that many bytes.
|
||||||
|
const inject = (page: Page, ...messages: (string | number)[]) =>
|
||||||
|
page.evaluate((messages) => {
|
||||||
|
const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels;
|
||||||
|
for (const message of messages) {
|
||||||
|
if (typeof message === 'string') channel!.send(message);
|
||||||
|
else channel!.send(new Uint8Array(message));
|
||||||
|
}
|
||||||
|
}, messages);
|
||||||
|
|
||||||
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
|
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
|
||||||
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
|
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
|
||||||
|
|
||||||
@@ -202,14 +311,14 @@ async function connect(mode: string, sender: Page, receiver: Page, source: strin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolves with the download, which starts on its own as soon as the file is announced, and the
|
// Resolves with the download, which starts once the receiver clicked Download, and the receiver log
|
||||||
// receiver log at that moment.
|
// at that moment.
|
||||||
const downloadStarts = (receiver: Page) =>
|
const downloadStarts = (receiver: Page) =>
|
||||||
receiver
|
receiver
|
||||||
.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 and confirms the security check on both sides.
|
// Connects, confirms the security check on both sides 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);
|
||||||
@@ -217,6 +326,11 @@ async function start(mode: string, sender: Page, receiver: Page, source: string)
|
|||||||
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.
|
||||||
|
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
|
||||||
|
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
||||||
|
await expect(receiver.locator('#log')).not.toContainText('receiving');
|
||||||
|
await receiver.click('#download');
|
||||||
return started;
|
return started;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,34 +353,63 @@ async function transfer(
|
|||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
expect(await hash(await download.path())).toBe(await hash(source));
|
||||||
await expect(receiver.locator('#log')).toContainText('download complete');
|
await expect(receiver.locator('#log')).toContainText('download complete');
|
||||||
await expect(sender.locator('#log')).toContainText('delivered');
|
await expect(sender.locator('#log')).toContainText('delivered');
|
||||||
|
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||||
|
await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100);
|
||||||
// Removed hidden pages release the service worker for updates.
|
// Removed hidden pages release the service worker for updates.
|
||||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
|
await expectClosed(sender);
|
||||||
|
await expectClosed(receiver);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const mode of Object.keys(MODES)) {
|
// A file in the test's output directory.
|
||||||
for (const from of Object.keys(BROWSERS)) {
|
async function payload(content: Buffer, name = 'payload.bin') {
|
||||||
for (const to of Object.keys(BROWSERS)) {
|
const source = test.info().outputPath(name);
|
||||||
test(`${mode}: ${from} sends to ${to}`, async () => {
|
await writeFile(source, content);
|
||||||
const sockets: string[] = [];
|
return source;
|
||||||
const [sender, receiver] = await Promise.all([open(from, sockets), open(to, sockets)]);
|
}
|
||||||
const source = test.info().outputPath('payload.bin');
|
|
||||||
await writeFile(source, randomBytes(SIZE));
|
|
||||||
|
|
||||||
await transfer(mode, sender, receiver, source, SIZE);
|
// Interoperability and data integrity between every pair, with no server involved.
|
||||||
if (mode !== 'tracker') {
|
for (const from of Object.keys(BROWSERS)) {
|
||||||
expect(sockets.filter((socket) => !socket.startsWith(url.replace('http', 'ws')))).toEqual([]);
|
for (const to of Object.keys(BROWSERS)) {
|
||||||
}
|
test(`offline: ${from} sends to ${to}`, async () => {
|
||||||
});
|
const [sender, receiver] = await Promise.all([open(from), open(to)]);
|
||||||
}
|
await transfer('offline', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||||
|
for (const page of [sender, receiver]) expect(sockets.get(page)).toEqual([]);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Through the public STUN servers and trackers. The signaling doesn't depend on the browser pair, one
|
||||||
|
// pairing each way is enough.
|
||||||
|
for (const mode of ['manual', 'tracker']) {
|
||||||
|
for (const [from, to] of [['chromium', 'firefox'], ['firefox', 'chromium']] as const) {
|
||||||
|
test(`live ${mode}: ${from} sends to ${to}`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(from), open(to)]);
|
||||||
|
await transfer(mode, sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||||
|
if (mode === 'manual') for (const page of [sender, receiver]) expect(sockets.get(page)).toEqual([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('build: chromium sends to firefox from the production build', async () => {
|
||||||
|
const outDir = test.info().outputPath('dist');
|
||||||
|
await build({ logLevel: 'silent', build: { outDir, emptyOutDir: true } });
|
||||||
|
const site = await preview({ logLevel: 'silent', build: { outDir }, preview: { port: 0 } });
|
||||||
|
try {
|
||||||
|
const base = site.resolvedUrls!.local[0]!;
|
||||||
|
const [sender, receiver] = await Promise.all([open('chromium', { base }), open('firefox', { base })]);
|
||||||
|
await transfer('offline', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||||
|
} finally {
|
||||||
|
await site.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
for (const name of Object.keys(BROWSERS)) {
|
for (const name of Object.keys(BROWSERS)) {
|
||||||
test(`servers: ${name} skips invalid lines and keeps the lists over a reload`, async () => {
|
test(`servers: ${name} skips invalid lines and keeps the lists over a reload`, async () => {
|
||||||
const page = await open(name, []);
|
const page = await open(name);
|
||||||
const core = () =>
|
const core = () =>
|
||||||
page.evaluate((path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]), '/src/main.ts');
|
page.evaluate((path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]), '/src/core.ts');
|
||||||
await page.click('#servers summary');
|
await page.click('#servers summary');
|
||||||
// Both would make the constructors throw.
|
// Both would make the constructors throw.
|
||||||
await page.fill('#stun-servers', 'stun:stun.example:99999');
|
await page.fill('#stun-servers', 'stun:stun.example:99999');
|
||||||
@@ -280,198 +423,466 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example');
|
await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example');
|
||||||
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
||||||
|
|
||||||
|
await page.fill('#receive-code', 'code');
|
||||||
await page.fill('#trackers', '');
|
await page.fill('#trackers', '');
|
||||||
await expect(page.locator('#receive')).toBeDisabled();
|
await expect(page.locator('#receive')).toBeDisabled();
|
||||||
await page.click('#reset-servers');
|
await page.click('#reset-servers');
|
||||||
await expect(page.locator('#receive')).toBeEnabled();
|
await expect(page.locator('#receive')).toBeEnabled();
|
||||||
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
|
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
for (const name of Object.keys(BROWSERS)) {
|
// 192.0.2.1 is reserved for documentation and never answers. Without the early stop in gatherIce
|
||||||
|
// Chromium would wait 40 s for it, with only the hard timeout still ICE_TIMEOUT.
|
||||||
|
test(`gather: ${name} stops at the first STUN answer`, async () => {
|
||||||
|
const page = await open(name);
|
||||||
|
await page.click('#servers summary');
|
||||||
|
await page.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}\nstun:192.0.2.1:3478`);
|
||||||
|
await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1)));
|
||||||
|
await page.click('#send-manual summary');
|
||||||
|
const start = Date.now();
|
||||||
|
await page.click('#create-offer');
|
||||||
|
await expect(page.locator('#offer')).toHaveValue(/.+/);
|
||||||
|
expect(Date.now() - start).toBeLessThan(ICE_TIMEOUT / 2);
|
||||||
|
expect(Buffer.from(await page.inputValue('#offer'), 'base64').toString()).toContain(`${PUBLIC_ADDRESS} `);
|
||||||
|
});
|
||||||
|
|
||||||
test(`update: ${name} receives after sw.js changed`, async () => {
|
test(`update: ${name} receives after sw.js changed`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(randomBytes(SIZE));
|
||||||
await writeFile(source, randomBytes(SIZE));
|
|
||||||
|
|
||||||
await updateWorker(receiver);
|
await updateWorker(receiver);
|
||||||
await expect.poll(() => updated(receiver)).toBe(true);
|
await expect.poll(() => updated(receiver)).toBe(true);
|
||||||
await transfer('offline', sender!, receiver!, source, SIZE);
|
await transfer('offline', sender, receiver, source, SIZE);
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`update: ${name} keeps a running download when sw.js changes`, async () => {
|
test(`update: ${name} keeps a running download when sw.js changes`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(randomBytes(HELD_SIZE));
|
||||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
|
||||||
|
|
||||||
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
|
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
|
||||||
// Paused at the window, so the transfer is guaranteed to still run during the update.
|
// Paused at the window, so the transfer is guaranteed to still run during the update.
|
||||||
await expect.poll(() => received(receiver!)).toBe(WINDOW);
|
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||||
await updateWorker(receiver!);
|
await updateWorker(receiver);
|
||||||
// The update has to wait instead of replacing the worker that feeds the download.
|
// The update has to wait instead of replacing the worker that feeds the download.
|
||||||
await expect
|
await expect
|
||||||
.poll(() => receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting))
|
.poll(() => receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting))
|
||||||
.toBe(true);
|
.toBe(true);
|
||||||
expect(await updated(receiver!)).toBe(false);
|
expect(await updated(receiver)).toBe(false);
|
||||||
await release(receiver!);
|
await release(receiver);
|
||||||
});
|
});
|
||||||
// Released once the download is complete, so the update takes over.
|
// Released once the download is complete, so the update takes over.
|
||||||
await expect.poll(() => updated(receiver)).toBe(true);
|
await expect.poll(() => updated(receiver)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
|
test(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(Buffer.alloc(RUNNING_SIZE));
|
||||||
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
|
|
||||||
|
|
||||||
await withLogs(sender!, receiver!, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
const { download } = await start('offline', sender!, receiver!, source);
|
const { download } = await start('offline', sender, receiver, source);
|
||||||
await download.cancel();
|
await download.cancel();
|
||||||
// A transfer that already finished would report no failure.
|
// A transfer that already finished would report no failure.
|
||||||
expect(await download.failure()).toBe('canceled');
|
expect(await download.failure()).toBe('canceled');
|
||||||
await expect(receiver!.locator('#log')).toContainText('download cancelled');
|
await expect(receiver.locator('#log')).toContainText('download cancelled');
|
||||||
await expect(receiver!.locator('iframe')).toHaveCount(0);
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
expect(await log(receiver!)).not.toContain('download complete');
|
expect(await log(receiver)).not.toContain('download complete');
|
||||||
// The window keeps the sender from having sent everything before it hears about the cancel.
|
// The window keeps the sender from having sent everything before it hears about the cancel.
|
||||||
await expect(sender!.locator('#log')).toContainText('receiver stopped: download cancelled');
|
await expect(sender.locator('#send-error')).toHaveText('receiver stopped: download cancelled');
|
||||||
expect(await log(sender!)).not.toMatch(/ sent$/m);
|
expect(await log(sender)).not.toMatch(/ sent$/m);
|
||||||
|
await expectClosed(sender);
|
||||||
|
await expectClosed(receiver);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`flow: ${name} sender waits while the download manager reads nothing`, async () => {
|
// Proves the sender's window: the receiver only holds back its { read } reports, its download
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
|
// manager still reads. Memory bounds of a really slow disk are beyond what a test can observe.
|
||||||
const source = test.info().outputPath('payload.bin');
|
test(`flow: ${name} sender waits while the receiver reports no reads`, async () => {
|
||||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
|
||||||
|
const source = await payload(randomBytes(HELD_SIZE));
|
||||||
|
|
||||||
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
|
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
|
||||||
await expect.poll(() => received(receiver!)).toBe(WINDOW);
|
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||||
// Proving that nothing more comes needs a moment, the sender fills the window in milliseconds.
|
// Proving that nothing more comes needs a moment, the sender fills the window in milliseconds.
|
||||||
await receiver!.waitForTimeout(1000);
|
await receiver.waitForTimeout(1000);
|
||||||
expect(await received(receiver!)).toBe(WINDOW);
|
expect(await received(receiver)).toBe(WINDOW);
|
||||||
await release(receiver!);
|
await release(receiver);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test(`progress: ${name} follows the shared file, not a later pick`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
const source = await payload(randomBytes(100_000));
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await start('offline', sender, receiver, source);
|
||||||
|
await expect(sender.locator('#log')).toContainText('delivered');
|
||||||
|
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(200_000) };
|
||||||
|
await sender.setInputFiles('input[type=file]', other);
|
||||||
|
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The edges of the chunking and the window, and a name the Content-Disposition header has to encode.
|
||||||
|
for (const [what, file, size] of [
|
||||||
|
['an empty file', 'empty.bin', 0],
|
||||||
|
// Firefox would save a % as _.
|
||||||
|
['a file one byte past the window', "l'été (1) 🚀.bin", WINDOW + 1],
|
||||||
|
] as const) {
|
||||||
|
test(`boundary: ${name} sends ${what}`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
await transfer('offline', sender, receiver, await payload(randomBytes(size), file), size);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share, Receive and the manual exchange each start a session, a new one ends the one before.
|
||||||
|
test(`session: ${name} a new operation ends the previous one`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
const source = await payload(randomBytes(100_000));
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
for (const page of [sender, receiver]) await page.uncheck('#stun');
|
||||||
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
|
await sender.click('#share');
|
||||||
|
await expect(sender.locator('#send-code')).toHaveText(/.+/);
|
||||||
|
const first = await sender.locator('#send-code').textContent();
|
||||||
|
await sender.click('#share');
|
||||||
|
await expect(sender.locator('#send-code')).not.toHaveText(first!);
|
||||||
|
await receiver.fill('#receive-code', 'nobody');
|
||||||
|
await receiver.click('#receive');
|
||||||
|
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Closes all of the above, transfer checks that.
|
||||||
|
await transfer('offline', sender, receiver, source, 100_000);
|
||||||
|
await expect(sender.locator('#send-code')).toHaveCount(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`check: ${name} accepts nothing before the receiver confirmed`, async () => {
|
test(`check: ${name} accepts nothing before the receiver confirmed`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, [], recordChannels), open(name, [])]);
|
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(randomBytes(SIZE));
|
||||||
await writeFile(source, randomBytes(SIZE));
|
|
||||||
|
|
||||||
await withLogs(sender!, receiver!, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
let downloads = 0;
|
let downloads = 0;
|
||||||
receiver!.on('download', () => downloads++);
|
receiver.on('download', () => downloads++);
|
||||||
await connect('offline', sender!, receiver!, source);
|
await connect('offline', sender, receiver, source);
|
||||||
// What a man in the middle could send without waiting for anyone's confirmation.
|
// What a man in the middle could send without waiting for anyone's confirmation.
|
||||||
await sender!.evaluate(() => {
|
await inject(sender, JSON.stringify({ name: 'injected.bin', size: 4 }), 4);
|
||||||
const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels;
|
await sender.click('#confirm');
|
||||||
channel!.send(JSON.stringify({ name: 'injected.bin', size: 4 }));
|
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
|
||||||
channel!.send(new Uint8Array(4));
|
|
||||||
});
|
|
||||||
await sender!.click('#confirm');
|
|
||||||
await expect(sender!.locator('#log')).toContainText("waiting for the receiver's security check");
|
|
||||||
// Proving that nothing starts needs a moment, a download would start within milliseconds.
|
// Proving that nothing starts needs a moment, a download would start within milliseconds.
|
||||||
await receiver!.waitForTimeout(1000);
|
await receiver.waitForTimeout(1000);
|
||||||
expect(await log(receiver!)).not.toContain('receiving');
|
expect(await log(receiver)).not.toContain('receiving');
|
||||||
expect(await log(sender!)).not.toContain('sending');
|
expect(await log(sender)).not.toContain('sending');
|
||||||
expect(downloads).toBe(0);
|
expect(downloads).toBe(0);
|
||||||
|
|
||||||
const started = downloadStarts(receiver!);
|
const started = downloadStarts(receiver);
|
||||||
await receiver!.click('#confirm');
|
await receiver.click('#confirm');
|
||||||
|
await receiver.click('#download');
|
||||||
const { download } = await started;
|
const { download } = await started;
|
||||||
expect(download.suggestedFilename()).toBe('payload.bin');
|
expect(download.suggestedFilename()).toBe('payload.bin');
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
expect(await hash(await download.path())).toBe(await hash(source));
|
||||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
await expect(sender.locator('#log')).toContainText('delivered');
|
||||||
expect(downloads).toBe(1);
|
expect(downloads).toBe(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
|
test(`check: ${name} offers nothing before the sender confirmed`, async () => {
|
||||||
test(`check: ${name} sender shares on after a mismatch`, async () => {
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: recordChannels })]);
|
||||||
const [sender, intruder, receiver] = await Promise.all([open(name, []), open(name, []), open(name, [])]);
|
const source = await payload(randomBytes(SIZE));
|
||||||
const source = test.info().outputPath('payload.bin');
|
|
||||||
await writeFile(source, randomBytes(SIZE));
|
|
||||||
|
|
||||||
await withLogs(sender!, receiver!, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await connect('tracker', sender!, intruder!, source);
|
await connect('offline', sender, receiver, source);
|
||||||
await receiver!.fill('#receive-code', (await sender!.locator('#send-code').textContent())!);
|
// A receiver that skips its own check and asks for the file right away.
|
||||||
await receiver!.click('#receive');
|
await inject(receiver, JSON.stringify({ ok: true }), JSON.stringify({ start: true }));
|
||||||
await expect(receiver!.locator('#log')).toContainText('looking on');
|
await sender.waitForTimeout(1000);
|
||||||
await sender!.click('#reject');
|
expect(await log(sender)).not.toContain('offered');
|
||||||
await intruder!.context().close();
|
|
||||||
await expect(sender!.locator('#log')).toContainText('waiting for the next receiver');
|
|
||||||
|
|
||||||
await expect(receiver!.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
await sender.click('#confirm');
|
||||||
await expect(sender!.locator('#check-local')).toHaveText((await receiver!.locator('#check-remote').textContent())!);
|
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
||||||
await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!);
|
// The early start counted for nothing, the sender waits for one after its offer.
|
||||||
const started = downloadStarts(receiver!);
|
await sender.waitForTimeout(500);
|
||||||
await sender!.click('#confirm');
|
expect(await log(sender)).not.toContain('sending');
|
||||||
await receiver!.click('#confirm');
|
|
||||||
const { download } = await started;
|
|
||||||
expect(await hash(await download.path())).toBe(await hash(source));
|
|
||||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`check: ${name} both sides go on after the receiver rejected`, async () => {
|
test(`protocol: ${name} receiver refuses an offer that isn't a file`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(randomBytes(SIZE));
|
||||||
await writeFile(source, randomBytes(SIZE));
|
|
||||||
|
|
||||||
await withLogs(sender!, receiver!, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await connect('tracker', sender!, receiver!, source);
|
await connect('offline', sender, receiver, source);
|
||||||
const first = await receiver!.locator('#check-local').textContent();
|
await receiver.click('#confirm');
|
||||||
// Retrying still has to work for a side that already confirmed.
|
await inject(sender, JSON.stringify({ name: 1, size: 2 }));
|
||||||
await sender!.click('#confirm');
|
await expect(receiver.locator('#receive-error')).toHaveText('the sender offered no valid file');
|
||||||
await receiver!.click('#reject');
|
await expect(receiver.locator('#download')).toHaveCount(0);
|
||||||
await expect(receiver!.locator('#log')).toContainText('looking again');
|
await expectClosed(receiver);
|
||||||
// The sender notices the receiver left, Chromium only once the connection counts as failed.
|
});
|
||||||
await expect(sender!.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
|
});
|
||||||
|
|
||||||
await expect(receiver!.locator('#check-local')).toHaveText(new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), {
|
test(`protocol: ${name} receiver fails a download with more bytes than offered`, async () => {
|
||||||
timeout: 45_000,
|
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||||
});
|
const source = await payload(randomBytes(SIZE));
|
||||||
await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!);
|
|
||||||
const started = downloadStarts(receiver!);
|
await withLogs(sender, receiver, async () => {
|
||||||
await sender!.click('#confirm');
|
await connect('offline', sender, receiver, source);
|
||||||
await receiver!.click('#confirm');
|
await receiver.click('#confirm');
|
||||||
|
await inject(sender, JSON.stringify({ name: 'twenty.bin', size: 20_000 }));
|
||||||
|
const started = downloadStarts(receiver);
|
||||||
|
await receiver.click('#download');
|
||||||
|
// The download only starts with the first bytes.
|
||||||
|
await inject(sender, 10_000);
|
||||||
|
const { download } = await started;
|
||||||
|
await inject(sender, 10_001);
|
||||||
|
await expect(receiver.locator('#receive-error')).toHaveText('download failed: the sender sent more than it offered');
|
||||||
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
|
// Firefox leaves the download stalled instead of failing it, see TODO.md.
|
||||||
|
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
|
||||||
|
await expectClosed(receiver);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test(`protocol: ${name} manual exchange reports a broken offer and answer`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.uncheck('#stun');
|
||||||
|
await sender.click('#send-manual summary');
|
||||||
|
await sender.click('#create-offer');
|
||||||
|
await expect(sender.locator('#offer')).toHaveValue(/.+/);
|
||||||
|
await sender.fill('#answer-input', 'not an answer');
|
||||||
|
await sender.click('#accept-answer');
|
||||||
|
await expect(sender.locator('#send-error')).toHaveText(/^not a valid answer/);
|
||||||
|
|
||||||
|
await receiver.click('#receive-manual summary');
|
||||||
|
await receiver.fill('#offer-input', btoa('v=0 but nothing else'));
|
||||||
|
await receiver.click('#create-answer');
|
||||||
|
await expect(receiver.locator('#receive-error')).toHaveText('not a valid offer, copy all of it');
|
||||||
|
await expectClosed(receiver);
|
||||||
|
});
|
||||||
|
|
||||||
|
// An offer that can't be answered used to keep the share busy forever.
|
||||||
|
test(`live tracker: ${name} sender goes on after an unusable offer`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', source);
|
||||||
|
await sender.click('#share');
|
||||||
|
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
|
||||||
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
|
const garbage = await announceGarbage(code);
|
||||||
|
await expect(sender.locator('#log')).toContainText('unusable offer');
|
||||||
|
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
||||||
|
garbage.close();
|
||||||
|
|
||||||
|
await receiver.fill('#receive-code', code);
|
||||||
|
await receiver.click('#receive');
|
||||||
|
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
||||||
|
const started = downloadStarts(receiver);
|
||||||
|
await sender.click('#confirm');
|
||||||
|
await receiver.click('#confirm');
|
||||||
|
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));
|
||||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
await expect(sender.locator('#log')).toContainText('delivered');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Trackers that keep the socket open but turn the announcement down used to leave both sides waiting.
|
||||||
|
test(`tracker: ${name} reports trackers that reject the announcement`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
const trackers = await Promise.all(
|
||||||
|
[sender, receiver].map((page) => mockTrackers(page, () => ({ 'failure reason': 'not here' }))),
|
||||||
|
);
|
||||||
|
const rejected = /^no tracker accepted it \(wss:\S+: not here; wss:\S+: not here\), check the list under Servers/;
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
await expect(sender.locator('#send-error')).toHaveText(rejected);
|
||||||
|
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||||
|
await receiver.click('#receive');
|
||||||
|
await expect(receiver.locator('#receive-error')).toHaveText(rejected);
|
||||||
|
await expect.poll(() => trackers.map(({ sockets, open }) => [sockets.length, open])).toEqual([[2, 0], [2, 0]]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
|
||||||
|
const sender = await open(name, { init: countAbortListeners });
|
||||||
|
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
||||||
|
const listeners = () => sender.evaluate(() => (window as unknown as { abortListeners: () => number }).abortListeners());
|
||||||
|
const unusable = async () => (await log(sender))!.match(/unusable offer/g)?.length ?? 0;
|
||||||
|
|
||||||
|
await withLogs(sender, sender, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
await sender.click('#share');
|
||||||
|
await expect.poll(() => trackers.sockets.length).toBe(2);
|
||||||
|
for (let offers = 1; offers <= 25; offers++) {
|
||||||
|
trackers.sockets[0]!.send(garbageOffer());
|
||||||
|
await expect.poll(unusable).toBe(offers);
|
||||||
|
// 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' }));
|
||||||
|
}
|
||||||
|
await expect(sender.locator('#log')).toContainText(': slow down');
|
||||||
|
await expect(sender.locator('#log')).not.toContainText('rejected by');
|
||||||
|
await expect(sender.locator('#send-error')).toHaveCount(0);
|
||||||
|
// One per tracker socket, none for the closed connections.
|
||||||
|
expect(await listeners()).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
|
||||||
|
test(`live check: ${name} sender shares on after a mismatch`, async () => {
|
||||||
|
const [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
|
||||||
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await connect('tracker', sender, intruder, source);
|
||||||
|
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||||
|
await receiver.click('#receive');
|
||||||
|
await expect(receiver.locator('#log')).toContainText('looking on');
|
||||||
|
await sender.click('#reject');
|
||||||
|
await intruder.context().close();
|
||||||
|
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
||||||
|
|
||||||
|
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
||||||
|
await expect(sender.locator('#check-local')).toHaveText((await receiver.locator('#check-remote').textContent())!);
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test(`live check: ${name} both sides go on after the receiver rejected`, async () => {
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await connect('tracker', sender, receiver, source);
|
||||||
|
const first = await receiver.locator('#check-local').textContent();
|
||||||
|
// Retrying still has to work for a side that already confirmed.
|
||||||
|
await sender.click('#confirm');
|
||||||
|
await receiver.click('#reject');
|
||||||
|
await expect(receiver.locator('#log')).toContainText('looking again');
|
||||||
|
// The sender notices the receiver left, Chromium only once the connection counts as failed.
|
||||||
|
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
|
||||||
|
|
||||||
|
await expect(receiver.locator('#check-local')).toHaveText(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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
|
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(Buffer.alloc(RUNNING_SIZE));
|
||||||
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
|
|
||||||
|
|
||||||
await withLogs(sender!, receiver!, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
const { download } = await start('offline', sender!, receiver!, source);
|
const { download } = await start('offline', sender, receiver, source);
|
||||||
await sender!.context().close();
|
await sender.context().close();
|
||||||
// Chromium only notices once the connection counts as failed, after ~16 s.
|
// Chromium only notices once the connection counts as failed, after ~16 s.
|
||||||
await expect(receiver!.locator('#log')).toContainText('download failed: connection lost', {
|
await expect(receiver.locator('#receive-error')).toHaveText('download failed: connection lost', {
|
||||||
timeout: 30_000,
|
timeout: 30_000,
|
||||||
});
|
});
|
||||||
await expect(receiver!.locator('iframe')).toHaveCount(0);
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
// Firefox leaves the download stalled instead of failing it, see TODO.md.
|
// Firefox leaves the download stalled instead of failing it, see TODO.md.
|
||||||
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
|
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// What a broken or hostile receiver could announce for the code: an offer no browser can parse.
|
||||||
|
async function announceGarbage(code: string) {
|
||||||
|
const ws = new WebSocket(TRACKER);
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
ws.onopen = resolve;
|
||||||
|
ws.onerror = reject;
|
||||||
|
});
|
||||||
|
const binary = (bytes: Buffer) => bytes.toString('latin1');
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
action: 'announce',
|
||||||
|
info_hash: binary(createHash('sha1').update(`hellcon:${code}`).digest()),
|
||||||
|
peer_id: binary(randomBytes(20)),
|
||||||
|
numwant: 1,
|
||||||
|
uploaded: 0,
|
||||||
|
downloaded: 0,
|
||||||
|
left: 1,
|
||||||
|
event: 'started',
|
||||||
|
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: 'garbage' } }],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return ws;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// page didn't close yet. They don't show up in sockets.
|
||||||
|
async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>) => object) {
|
||||||
|
const trackers = { sockets: [] as WebSocketRoute[], open: 0 };
|
||||||
|
await page.routeWebSocket(/^wss:/, (ws) => {
|
||||||
|
trackers.sockets.push(ws);
|
||||||
|
trackers.open++;
|
||||||
|
ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data))))));
|
||||||
|
ws.onClose(() => trackers.open--);
|
||||||
|
});
|
||||||
|
return trackers;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a tracker relays from a receiver: an offer no browser can parse.
|
||||||
|
const garbageOffer = () =>
|
||||||
|
JSON.stringify({
|
||||||
|
action: 'announce',
|
||||||
|
peer_id: randomBytes(20).toString('latin1'),
|
||||||
|
offer_id: randomBytes(20).toString('latin1'),
|
||||||
|
offer: { type: 'offer', sdp: 'garbage' },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal
|
||||||
|
// holds one for each thing it still has to close. It runs in the hidden frames too, only the app's
|
||||||
|
// own window counts.
|
||||||
|
function countAbortListeners() {
|
||||||
|
if (window !== window.top) return;
|
||||||
|
const listeners = new Set<unknown>();
|
||||||
|
const { addEventListener, removeEventListener } = EventTarget.prototype;
|
||||||
|
const signal = AbortSignal.prototype as EventTarget;
|
||||||
|
signal.addEventListener = function (this: AbortSignal, ...args: Parameters<EventTarget['addEventListener']>) {
|
||||||
|
if (args[0] === 'abort') listeners.add(args[1]);
|
||||||
|
addEventListener.apply(this, args);
|
||||||
|
};
|
||||||
|
signal.removeEventListener = function (this: AbortSignal, ...args: Parameters<EventTarget['removeEventListener']>) {
|
||||||
|
if (args[0] === 'abort') listeners.delete(args[1]);
|
||||||
|
removeEventListener.apply(this, args);
|
||||||
|
};
|
||||||
|
(window as unknown as { abortListeners: () => number }).abortListeners = () => listeners.size;
|
||||||
|
}
|
||||||
|
|
||||||
for (const name of Object.keys(BROWSERS)) {
|
for (const name of Object.keys(BROWSERS)) {
|
||||||
test(`large: ${name} survives a 40 s stall`, async () => {
|
test(`large: ${name} survives a 40 s stall`, async () => {
|
||||||
test.skip(!process.env.LARGE, 'set LARGE=1');
|
test.skip(!process.env.LARGE, 'set LARGE=1');
|
||||||
test.setTimeout(120_000);
|
test.setTimeout(120_000);
|
||||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
|
||||||
const source = test.info().outputPath('payload.bin');
|
const source = await payload(randomBytes(HELD_SIZE));
|
||||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
|
||||||
|
|
||||||
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
|
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
|
||||||
await expect.poll(() => received(receiver!)).toBe(WINDOW);
|
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||||
// Past the 30 s after which Firefox stops a service worker without events.
|
// Past the 30 s after which Firefox stops a service worker without events.
|
||||||
await receiver!.waitForTimeout(40_000);
|
await receiver.waitForTimeout(40_000);
|
||||||
await release(receiver!);
|
await release(receiver);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -487,19 +898,24 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await file.close();
|
await file.close();
|
||||||
|
|
||||||
// Real profiles on disk like normal users have; downloads go there too instead of the temp dir.
|
// Real profiles on disk like normal users have; downloads go there too instead of the temp dir.
|
||||||
const contexts = await Promise.all(
|
const profiles = await Promise.all(
|
||||||
['sender', 'receiver'].map((profile) =>
|
['sender', 'receiver'].map((profile) =>
|
||||||
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
|
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
|
||||||
downloadsPath: test.info().outputPath('downloads'),
|
downloadsPath: test.info().outputPath('downloads'),
|
||||||
|
permissions: PERMISSIONS[name],
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const [sender, receiver] = await Promise.all(contexts.map((context) => context.newPage()));
|
const [sender, receiver] = await Promise.all(profiles.map((profile) => profile.newPage()));
|
||||||
|
for (const page of [sender!, receiver!]) {
|
||||||
|
sockets.set(page, []);
|
||||||
|
await page.addInitScript(trackPeers);
|
||||||
|
}
|
||||||
await Promise.all([sender!.goto(url), receiver!.goto(url)]);
|
await Promise.all([sender!.goto(url), receiver!.goto(url)]);
|
||||||
await transfer('offline', sender!, receiver!, source, LARGE_SIZE);
|
await transfer('offline', sender!, receiver!, source, LARGE_SIZE);
|
||||||
} finally {
|
} finally {
|
||||||
await Promise.all(contexts.map((context) => context.close()));
|
await Promise.all(profiles.map((profile) => profile.close()));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+6
-4
@@ -1,6 +1,6 @@
|
|||||||
// Streams received files into the browser's download manager. It is the only script besides the app
|
// 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
|
// because service workers can only be registered from a same-origin script URL. Registered with the
|
||||||
// scope download/ by src/main.ts, it sees no other requests.
|
// scope download/ by src/core.ts, it sees no other requests.
|
||||||
|
|
||||||
// Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the
|
// 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.
|
// reply port and how many bytes the download manager has read.
|
||||||
@@ -9,6 +9,8 @@ const downloads = new Map();
|
|||||||
const responses = new Map();
|
const responses = new Map();
|
||||||
|
|
||||||
function open(id, { name, size }, port) {
|
function open(id, { name, size }, port) {
|
||||||
|
// The page checks the sender's offer already. Anything else would throw below or lie to the browser.
|
||||||
|
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
|
||||||
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
|
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
|
||||||
const body = new ReadableStream(
|
const body = new ReadableStream(
|
||||||
{
|
{
|
||||||
@@ -20,7 +22,7 @@ function open(id, { name, size }, port) {
|
|||||||
const chunk = download.chunks.shift();
|
const chunk = download.chunks.shift();
|
||||||
if (chunk) {
|
if (chunk) {
|
||||||
download.read += chunk.byteLength;
|
download.read += chunk.byteLength;
|
||||||
// Every MiB, src/main.ts forwards it to the sender for its flow control window.
|
// Every MiB, src/core.ts forwards it to the sender for its flow control window.
|
||||||
if (download.read - download.reported >= 2 ** 20) port.postMessage((download.reported = download.read));
|
if (download.read - download.reported >= 2 ** 20) port.postMessage((download.reported = download.read));
|
||||||
return controller.enqueue(chunk);
|
return controller.enqueue(chunk);
|
||||||
}
|
}
|
||||||
@@ -52,7 +54,7 @@ function open(id, { name, size }, port) {
|
|||||||
// The page posts the metadata with a reply port first, then every chunk as its own message and
|
// 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.
|
// finally done (queued as the end marker null) or an error. Pings come in between.
|
||||||
self.addEventListener('message', ({ data, ports: [port] }) => {
|
self.addEventListener('message', ({ data, ports: [port] }) => {
|
||||||
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/main.ts.
|
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/core.ts.
|
||||||
if (data.ping) return;
|
if (data.ping) return;
|
||||||
if (port) return open(data.id, data, port);
|
if (port) return open(data.id, data, port);
|
||||||
const download = downloads.get(data.id);
|
const download = downloads.get(data.id);
|
||||||
@@ -69,7 +71,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => {
|
|||||||
|
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
const id = new URL(event.request.url).pathname.split('/').pop();
|
const id = new URL(event.request.url).pathname.split('/').pop();
|
||||||
// download/ itself is the empty page src/main.ts keeps open to hold this worker during a transfer.
|
// download/ itself is the empty page src/core.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' } }));
|
if (!id) return event.respondWith(new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }));
|
||||||
const response = responses.get(id);
|
const response = responses.get(id);
|
||||||
responses.delete(id);
|
responses.delete(id);
|
||||||
|
|||||||
+163
-31
@@ -10,7 +10,9 @@ import {
|
|||||||
settings as coreSettings,
|
settings as coreSettings,
|
||||||
type Check,
|
type Check,
|
||||||
type Events,
|
type Events,
|
||||||
} from './main';
|
type Incoming,
|
||||||
|
type ReceiveEvents,
|
||||||
|
} from './core';
|
||||||
|
|
||||||
const SETTINGS_KEY = 'hellcon:settings';
|
const SETTINGS_KEY = 'hellcon:settings';
|
||||||
|
|
||||||
@@ -86,22 +88,97 @@ const receiveCode = ref('');
|
|||||||
const check = ref<Check>();
|
const check = ref<Check>();
|
||||||
const confirmed = ref(false);
|
const confirmed = ref(false);
|
||||||
const log = ref<string[]>([]);
|
const log = ref<string[]>([]);
|
||||||
|
// Of the session, shown in the card of its side.
|
||||||
|
const error = ref('');
|
||||||
|
|
||||||
const events: Events = {
|
// 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) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
|
||||||
|
error: (message) => {
|
||||||
|
events.log(message);
|
||||||
|
error.value = message;
|
||||||
|
},
|
||||||
check: (result) => {
|
check: (result) => {
|
||||||
check.value = result;
|
check.value = result;
|
||||||
confirmed.value = false;
|
confirmed.value = false;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
|
||||||
|
// a transfer starts.
|
||||||
|
type Progress = { read: number; size: number };
|
||||||
|
|
||||||
|
const sent = ref<Progress>();
|
||||||
|
const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) };
|
||||||
|
|
||||||
|
const incoming = ref<Incoming>();
|
||||||
|
const received = ref<Progress>();
|
||||||
|
const receiveEvents: ReceiveEvents = {
|
||||||
|
...events,
|
||||||
|
progress: (read, size) => (received.value = { read, size }),
|
||||||
|
incoming: (file) => {
|
||||||
|
incoming.value = file;
|
||||||
|
received.value = undefined;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
|
||||||
|
|
||||||
function onConfirm() {
|
function onConfirm() {
|
||||||
confirmed.value = true;
|
confirmed.value = true;
|
||||||
check.value?.confirm();
|
check.value?.confirm();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The text copied last, its button says so for a moment.
|
||||||
|
const copied = ref('');
|
||||||
|
let copiedTimer: number | undefined;
|
||||||
|
|
||||||
|
async function onCopy(text: string) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch {
|
||||||
|
return events.log('copy failed, the browser blocked the clipboard');
|
||||||
|
}
|
||||||
|
copied.value = text;
|
||||||
|
clearTimeout(copiedTimer);
|
||||||
|
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
|
||||||
|
}
|
||||||
|
|
||||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||||
|
|
||||||
|
// One session at a time, started by Share, Create offer, Receive or Create answer. Starting one ends
|
||||||
|
// the one before: its connections close and what it showed goes, so nothing else can write here.
|
||||||
|
let session: AbortController | undefined;
|
||||||
|
const side = ref<'send' | 'receive'>();
|
||||||
|
|
||||||
|
function begin(on: 'send' | 'receive') {
|
||||||
|
session?.abort();
|
||||||
|
session = new AbortController();
|
||||||
|
side.value = on;
|
||||||
|
error.value = '';
|
||||||
|
check.value = undefined;
|
||||||
|
confirmed.value = false;
|
||||||
|
sent.value = undefined;
|
||||||
|
incoming.value = undefined;
|
||||||
|
received.value = undefined;
|
||||||
|
sendCode.value = '';
|
||||||
|
offer.value = '';
|
||||||
|
answer.value = '';
|
||||||
|
acceptAnswer = undefined;
|
||||||
|
return session.signal;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolves with the result of a session step, or undefined if it failed, which is shown, or if a
|
||||||
|
// newer session replaced it meanwhile.
|
||||||
|
async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
|
||||||
|
try {
|
||||||
|
const result = await step;
|
||||||
|
return signal.aborted ? undefined : result;
|
||||||
|
} catch (failure) {
|
||||||
|
if (!signal.aborted) events.error(failure instanceof Error ? failure.message : String(failure));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function onPick(event: Event) {
|
function onPick(event: Event) {
|
||||||
file.value = (event.target as HTMLInputElement).files?.[0];
|
file.value = (event.target as HTMLInputElement).files?.[0];
|
||||||
}
|
}
|
||||||
@@ -124,25 +201,34 @@ function formatSize(bytes: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateOffer() {
|
async function onCreateOffer() {
|
||||||
const result = await createOffer(file.value!, events);
|
const signal = begin('send');
|
||||||
|
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
|
||||||
|
if (!result) return;
|
||||||
offer.value = result.offer;
|
offer.value = result.offer;
|
||||||
acceptAnswer = result.accept;
|
acceptAnswer = result.accept;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Part of the current session, a wrong answer can be corrected.
|
||||||
function onAcceptAnswer() {
|
function onAcceptAnswer() {
|
||||||
acceptAnswer?.(answerInput.value);
|
error.value = '';
|
||||||
|
if (acceptAnswer) attempt(session!.signal, acceptAnswer(answerInput.value));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateAnswer() {
|
async function onCreateAnswer() {
|
||||||
answer.value = await answerOffer(offerInput.value, events);
|
const signal = begin('receive');
|
||||||
|
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
||||||
|
if (result) answer.value = result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onShare() {
|
async function onShare() {
|
||||||
sendCode.value = await sendViaTracker(file.value!, events);
|
const signal = begin('send');
|
||||||
|
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
||||||
|
if (code) sendCode.value = code;
|
||||||
}
|
}
|
||||||
|
|
||||||
function onReceive() {
|
function onReceive() {
|
||||||
receiveViaTracker(receiveCode.value, events);
|
const signal = begin('receive');
|
||||||
|
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -189,46 +275,85 @@ function onReceive() {
|
|||||||
</template>
|
</template>
|
||||||
<template v-else>Drop a file or click to choose</template>
|
<template v-else>Drop a file or click to choose</template>
|
||||||
</label>
|
</label>
|
||||||
|
<p v-if="sent">
|
||||||
<section>
|
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
|
||||||
<h3>Manual</h3>
|
{{ percent(sent) }} %
|
||||||
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
|
</p>
|
||||||
<template v-if="offer">
|
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
|
||||||
<label for="offer">Offer, send this to the receiver:</label>
|
|
||||||
<textarea id="offer" readonly :value="offer"></textarea>
|
|
||||||
<label for="answer-input">Answer from the receiver:</label>
|
|
||||||
<textarea id="answer-input" v-model="answerInput"></textarea>
|
|
||||||
<button id="accept-answer" @click="onAcceptAnswer">Connect</button>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h3>Tracker</h3>
|
<h3>Tracker</h3>
|
||||||
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
|
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
|
||||||
<p v-if="sendCode">Code: <output id="send-code">{{ sendCode }}</output></p>
|
<template v-if="sendCode">
|
||||||
|
<label for="send-code">Code, give this to the receiver:</label>
|
||||||
|
<div role="group">
|
||||||
|
<output id="send-code">{{ sendCode }}</output>
|
||||||
|
<button id="copy-send-code" data-copy @click="onCopy(sendCode)">{{ copied === sendCode ? 'Copied' : 'Copy' }}</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<details id="send-manual">
|
||||||
|
<summary>Manual</summary>
|
||||||
|
<section>
|
||||||
|
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
|
||||||
|
<template v-if="offer">
|
||||||
|
<label for="offer">Offer, send this to the receiver:</label>
|
||||||
|
<textarea id="offer" readonly :value="offer"></textarea>
|
||||||
|
<button id="copy-offer" data-copy @click="onCopy(offer)">{{ copied === offer ? 'Copied' : 'Copy' }}</button>
|
||||||
|
<label for="answer-input">Answer from the receiver:</label>
|
||||||
|
<textarea id="answer-input" v-model="answerInput"></textarea>
|
||||||
|
<button id="accept-answer" :disabled="!answerInput.trim()" @click="onAcceptAnswer">Connect</button>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</details>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
<article>
|
<article>
|
||||||
<h2>Receive</h2>
|
<h2>Receive</h2>
|
||||||
|
<div id="incoming">
|
||||||
<section>
|
<template v-if="incoming">
|
||||||
<h3>Manual</h3>
|
<strong>{{ incoming.name }}</strong>
|
||||||
<textarea id="offer-input" v-model="offerInput" placeholder="Paste the offer"></textarea>
|
{{ formatSize(incoming.size) }}
|
||||||
<button id="create-answer" @click="onCreateAnswer">Create answer</button>
|
<button v-if="!received" id="download" @click="incoming.download()">Download</button>
|
||||||
<template v-if="answer">
|
|
||||||
<label for="answer">Answer, send this back to the sender:</label>
|
|
||||||
<textarea id="answer" readonly :value="answer"></textarea>
|
|
||||||
</template>
|
</template>
|
||||||
</section>
|
<template v-else>The sender's file shows up here after the security check</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="received">
|
||||||
|
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress>
|
||||||
|
{{ percent(received) }} %
|
||||||
|
</p>
|
||||||
|
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h3>Tracker</h3>
|
<h3>Tracker</h3>
|
||||||
|
<label for="receive-code">Code from the sender:</label>
|
||||||
<div role="group">
|
<div role="group">
|
||||||
<input id="receive-code" v-model="receiveCode" placeholder="Code" />
|
<input
|
||||||
<button id="receive" :disabled="!settings.trackers.length" @click="onReceive">Receive</button>
|
id="receive-code"
|
||||||
|
v-model="receiveCode"
|
||||||
|
autocapitalize="off"
|
||||||
|
autocomplete="off"
|
||||||
|
autocorrect="off"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<button id="receive" :disabled="!settings.trackers.length || !receiveCode.trim()" @click="onReceive">Receive</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<details id="receive-manual">
|
||||||
|
<summary>Manual</summary>
|
||||||
|
<section>
|
||||||
|
<label for="offer-input">Offer from the sender:</label>
|
||||||
|
<textarea id="offer-input" v-model="offerInput"></textarea>
|
||||||
|
<button id="create-answer" :disabled="!offerInput.trim()" @click="onCreateAnswer">Create answer</button>
|
||||||
|
<template v-if="answer">
|
||||||
|
<label for="answer">Answer, send this back to the sender:</label>
|
||||||
|
<textarea id="answer" readonly :value="answer"></textarea>
|
||||||
|
<button id="copy-answer" data-copy @click="onCopy(answer)">{{ copied === answer ? 'Copied' : 'Copy' }}</button>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</details>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
<details id="servers">
|
<details id="servers">
|
||||||
@@ -255,4 +380,11 @@ function onReceive() {
|
|||||||
<pre id="log">{{ log.join('\n') }}</pre>
|
<pre id="log">{{ log.join('\n') }}</pre>
|
||||||
</details>
|
</details>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||||
|
<img src="/gitea.svg" alt="" width="20" height="20" />
|
||||||
|
Source code
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
</template>
|
</template>
|
||||||
+817
@@ -0,0 +1,817 @@
|
|||||||
|
export const DEFAULT_TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
|
||||||
|
|
||||||
|
export const DEFAULT_STUN_SERVERS = [
|
||||||
|
'stun:stun.pagequit.net:3478',
|
||||||
|
'stun:stun.cloudflare.com:3478',
|
||||||
|
'stun:stun.l.google.com:19302',
|
||||||
|
'stun:stun.nextcloud.com:443',
|
||||||
|
];
|
||||||
|
|
||||||
|
// 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 = {
|
||||||
|
stun: true,
|
||||||
|
stunServers: [...DEFAULT_STUN_SERVERS],
|
||||||
|
trackers: [...DEFAULT_TRACKERS],
|
||||||
|
};
|
||||||
|
|
||||||
|
const CHUNK_SIZE = 16 * 1024;
|
||||||
|
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;
|
||||||
|
const ICE_GRACE = 300;
|
||||||
|
const ICE_TIMEOUT = 5000;
|
||||||
|
// 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: its connection never even fails.
|
||||||
|
const CONNECT_TIMEOUT = 30_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 type Check = {
|
||||||
|
local: string;
|
||||||
|
remote: string;
|
||||||
|
// Once the user compared the codes: confirm if they match, else reject.
|
||||||
|
confirm: () => void;
|
||||||
|
reject: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Events = {
|
||||||
|
log: (message: string) => void;
|
||||||
|
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||||
|
error: (message: string) => void;
|
||||||
|
// Called on both sides once connected, and without a check when it ended undecided.
|
||||||
|
check: (check?: Check) => void;
|
||||||
|
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
|
||||||
|
// the transfer starts.
|
||||||
|
progress: (read: number, size: number) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The sender's file, offered once both sides confirmed the check. download() starts saving it.
|
||||||
|
export type Incoming = { name: string; size: number; download: () => void };
|
||||||
|
|
||||||
|
export type ReceiveEvents = Events & {
|
||||||
|
// Without a file when the sender left before the download started.
|
||||||
|
incoming: (file?: Incoming) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Every export runs one session until its signal aborts: then it closes the connections and tracker
|
||||||
|
// sockets it opened, starts nothing new and calls no more events. A new session doesn't touch an old one.
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
const closeResource = resource.close.bind(resource);
|
||||||
|
// Without the abort event, WebSocket.close() would take it for a close code and throw.
|
||||||
|
const close = () => closeResource();
|
||||||
|
if (signal.aborted) close();
|
||||||
|
else signal.addEventListener('abort', close, { once: true });
|
||||||
|
resource.close = () => {
|
||||||
|
signal.removeEventListener('abort', close);
|
||||||
|
close();
|
||||||
|
};
|
||||||
|
return resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
|
||||||
|
) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPeerConnection(signal: AbortSignal) {
|
||||||
|
// An empty urls list is a syntax error.
|
||||||
|
const stun = settings.stun && settings.stunServers.length;
|
||||||
|
return own(signal, new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peers and trackers send JSON objects. Anything else, malformed or not an object, counts as nothing.
|
||||||
|
// Whatever is read from one has to be checked, the any only saves the casts for that.
|
||||||
|
type Message = Record<string, any>;
|
||||||
|
|
||||||
|
function parse(data: unknown): Message | undefined {
|
||||||
|
if (typeof data !== 'string') return;
|
||||||
|
try {
|
||||||
|
const message = JSON.parse(data);
|
||||||
|
return message && typeof message === 'object' ? message : undefined;
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored.
|
||||||
|
function decode(code: string, type: 'offer' | 'answer') {
|
||||||
|
try {
|
||||||
|
return { type, sdp: atob(code.replace(/\s/g, '')) };
|
||||||
|
} catch {
|
||||||
|
throw new Error(`not a valid ${type}, copy all of it`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function randomBinary(length: number) {
|
||||||
|
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||||
|
|
||||||
|
// 8 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
|
||||||
|
function randomCode() {
|
||||||
|
let code = '';
|
||||||
|
while (code.length < 8)
|
||||||
|
for (const byte of crypto.getRandomValues(new Uint8Array(8)))
|
||||||
|
if (byte < 248 && code.length < 8) code += CODE_CHARS[byte % 62];
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
|
||||||
|
async function infoHash(code: string) {
|
||||||
|
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
||||||
|
return String.fromCharCode(...new Uint8Array(digest));
|
||||||
|
}
|
||||||
|
|
||||||
|
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
action: 'announce',
|
||||||
|
info_hash: hash,
|
||||||
|
peer_id: peerId,
|
||||||
|
numwant: 0,
|
||||||
|
uploaded: 0,
|
||||||
|
downloaded: 0,
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
|
||||||
|
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
|
||||||
|
// the same public address: the first one plus a short grace for the other IP family is enough.
|
||||||
|
async function gatherIce(pc: RTCPeerConnection) {
|
||||||
|
if (pc.iceGatheringState === 'complete') return;
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const timeout = setTimeout(resolve, ICE_TIMEOUT);
|
||||||
|
const done = () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
pc.addEventListener('icegatheringstatechange', () => {
|
||||||
|
if (pc.iceGatheringState === 'complete') done();
|
||||||
|
});
|
||||||
|
pc.addEventListener('icecandidate', ({ candidate }) => {
|
||||||
|
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// checked resolves once the user confirmed the codes. 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 confirmations, a rejected 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 };
|
||||||
|
|
||||||
|
function connected(
|
||||||
|
pc: RTCPeerConnection,
|
||||||
|
channel: RTCDataChannel,
|
||||||
|
via: string,
|
||||||
|
events: Events,
|
||||||
|
next?: () => void,
|
||||||
|
): Handshake {
|
||||||
|
events.log(`connected via ${via}`);
|
||||||
|
events.log('waiting for the security check');
|
||||||
|
let done = false;
|
||||||
|
const end = (reason: string) => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
events.check();
|
||||||
|
pc.close();
|
||||||
|
if (!next) return events.error(reason);
|
||||||
|
events.log(reason);
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
||||||
|
channel.addEventListener('close', () => end('peer left before the transfer'));
|
||||||
|
pc.addEventListener('connectionstatechange', () => {
|
||||||
|
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
checked: new Promise((resolve) =>
|
||||||
|
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||||
|
),
|
||||||
|
start: () => (done = true),
|
||||||
|
end,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offers the file once checked resolved and the receiver confirmed its own check with { ok }, sends
|
||||||
|
// it once the receiver started the download with { start }. Then it answers with { read } progress,
|
||||||
|
// { 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(
|
||||||
|
pc: RTCPeerConnection,
|
||||||
|
channel: RTCDataChannel,
|
||||||
|
file: File,
|
||||||
|
events: Events,
|
||||||
|
handshake: Handshake,
|
||||||
|
signal: AbortSignal,
|
||||||
|
) {
|
||||||
|
let read = 0;
|
||||||
|
let accepted = false;
|
||||||
|
let offered = false;
|
||||||
|
let sending = false;
|
||||||
|
let stopped = false;
|
||||||
|
// Every event the send loop can wait for calls this.
|
||||||
|
let wake = () => {};
|
||||||
|
const stop = (error?: string) => {
|
||||||
|
if (stopped) return;
|
||||||
|
stopped = true;
|
||||||
|
signal.removeEventListener('abort', abort);
|
||||||
|
if (error) events.error(error);
|
||||||
|
pc.close();
|
||||||
|
wake();
|
||||||
|
};
|
||||||
|
channel.onmessage = ({ data }) => {
|
||||||
|
const message = parse(data);
|
||||||
|
if (!offered) accepted ||= message?.ok === true;
|
||||||
|
else if (!sending) sending = message?.start === true;
|
||||||
|
else if (Number.isSafeInteger(message?.read) && message!.read > read && message!.read <= file.size) {
|
||||||
|
read = message!.read;
|
||||||
|
events.progress(read, file.size);
|
||||||
|
} else if (message?.done === true && !stopped) {
|
||||||
|
events.log('delivered');
|
||||||
|
events.progress(file.size, file.size);
|
||||||
|
stop();
|
||||||
|
} else if (typeof message?.error === 'string') {
|
||||||
|
stop(`receiver stopped: ${message.error.slice(0, 200)}`);
|
||||||
|
}
|
||||||
|
wake();
|
||||||
|
};
|
||||||
|
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection. Before
|
||||||
|
// sending, connected reports it.
|
||||||
|
const lost = () => stop(sending ? 'connection lost' : undefined);
|
||||||
|
channel.addEventListener('close', lost);
|
||||||
|
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
||||||
|
channel.addEventListener('bufferedamountlow', () => wake());
|
||||||
|
const abort = () => stop();
|
||||||
|
signal.addEventListener('abort', abort, { once: true });
|
||||||
|
// Also false once the channel closes, its close event may still be on the way.
|
||||||
|
const open = () => !stopped && channel.readyState === 'open';
|
||||||
|
|
||||||
|
if (channel.readyState === 'connecting') {
|
||||||
|
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||||
|
}
|
||||||
|
await handshake.checked;
|
||||||
|
if (!accepted && open()) events.log("waiting for the receiver's security check");
|
||||||
|
while (open() && !accepted) await new Promise<void>((resolve) => (wake = resolve));
|
||||||
|
if (!open()) return;
|
||||||
|
|
||||||
|
channel.send(JSON.stringify({ name: file.name, size: file.size }));
|
||||||
|
offered = true;
|
||||||
|
events.log(`offered ${file.name} (${file.size} bytes)`);
|
||||||
|
events.log('waiting for the receiver to download');
|
||||||
|
while (open() && !sending) await new Promise<void>((resolve) => (wake = resolve));
|
||||||
|
if (!open()) return;
|
||||||
|
|
||||||
|
handshake.start();
|
||||||
|
events.log(`sending ${file.name}`);
|
||||||
|
events.progress(0, file.size);
|
||||||
|
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||||
|
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||||
|
while (open() && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
|
||||||
|
await new Promise<void>((resolve) => (wake = resolve));
|
||||||
|
}
|
||||||
|
// E.g. the file was changed or deleted since it was picked.
|
||||||
|
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer().catch(() => undefined);
|
||||||
|
if (!chunk) return stop(`could not read ${file.name} anymore`);
|
||||||
|
if (!open()) return;
|
||||||
|
channel.send(chunk);
|
||||||
|
}
|
||||||
|
events.log('sent');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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(
|
||||||
|
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 received = 0;
|
||||||
|
// By the download manager. The rest of received is held in this page and the worker.
|
||||||
|
let read = 0;
|
||||||
|
let confirmed = false;
|
||||||
|
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 | void> = Promise.resolve();
|
||||||
|
const post = (message: object, transfer: Transferable[] = []) =>
|
||||||
|
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.
|
||||||
|
function release() {
|
||||||
|
clearInterval(keepalive);
|
||||||
|
for (const frame of frames) frame.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;
|
||||||
|
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') {
|
||||||
|
events.log('download complete');
|
||||||
|
events.progress(meta!.size, meta!.size);
|
||||||
|
reply({ done: true });
|
||||||
|
}
|
||||||
|
if (data === 'cancelled' && !ended) {
|
||||||
|
events.log('download cancelled');
|
||||||
|
reply({ error: 'download cancelled' });
|
||||||
|
}
|
||||||
|
ended = true;
|
||||||
|
channel.close();
|
||||||
|
release();
|
||||||
|
};
|
||||||
|
worker.postMessage({ id, ...meta }, [port2]);
|
||||||
|
return worker;
|
||||||
|
}, (error) => fail(String(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
handshake.checked.then(() => {
|
||||||
|
confirmed = true;
|
||||||
|
reply({ ok: true });
|
||||||
|
events.log('waiting for the sender');
|
||||||
|
});
|
||||||
|
|
||||||
|
function receivedAll() {
|
||||||
|
complete = true;
|
||||||
|
post({ done: true });
|
||||||
|
events.log('received');
|
||||||
|
}
|
||||||
|
|
||||||
|
function download() {
|
||||||
|
if (downloading || ended || signal.aborted) return;
|
||||||
|
downloading = true;
|
||||||
|
// Until then closing the connection is all there is to stop, the session does that. Only one
|
||||||
|
// download per session, so this never piles up.
|
||||||
|
signal.addEventListener('abort', () => fail('stopped'), { once: true });
|
||||||
|
handshake.start();
|
||||||
|
events.log(`receiving ${meta!.name}`);
|
||||||
|
events.progress(0, meta!.size);
|
||||||
|
startDownload();
|
||||||
|
reply({ start: true });
|
||||||
|
if (!meta!.size) receivedAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
channel.binaryType = 'arraybuffer';
|
||||||
|
channel.onmessage = ({ data }) => {
|
||||||
|
if (ended || !confirmed) return;
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
if (meta) return;
|
||||||
|
const { name, size } = parse(data) ?? {};
|
||||||
|
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)`);
|
||||||
|
events.incoming({ name, size, 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]);
|
||||||
|
if (received === meta!.size) receivedAll();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
|
||||||
|
// peer only closes the channel in Firefox, Chromium just fails the connection. Before the download
|
||||||
|
// started, connected reports it and only the offer goes.
|
||||||
|
function lost() {
|
||||||
|
if (!meta || ended) return;
|
||||||
|
if (!downloading) events.incoming();
|
||||||
|
else if (!complete) fail('connection lost');
|
||||||
|
}
|
||||||
|
channel.addEventListener('close', lost);
|
||||||
|
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
||||||
|
}
|
||||||
|
|
||||||
|
// The manual exchange has nobody else to try: a connection that fails before the data channel opened,
|
||||||
|
// e.g. after a wrong answer or between networks without STUN, ends the session.
|
||||||
|
function failUnconnected(pc: RTCPeerConnection, opened: () => boolean, events: Events) {
|
||||||
|
pc.addEventListener('connectionstatechange', () => {
|
||||||
|
if (pc.connectionState !== 'failed' || opened()) return;
|
||||||
|
pc.close();
|
||||||
|
events.error('could not connect, check the codes. Between different networks both sides need STUN');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
|
||||||
|
// The sender offers, the receiver answers, no tracker involved.
|
||||||
|
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
|
||||||
|
events = live(events, signal);
|
||||||
|
const pc = createPeerConnection(signal);
|
||||||
|
const channel = pc.createDataChannel('file');
|
||||||
|
channel.onopen = () =>
|
||||||
|
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||||
|
failUnconnected(pc, () => channel.readyState !== 'connecting', events);
|
||||||
|
await pc.setLocalDescription();
|
||||||
|
await gatherIce(pc);
|
||||||
|
|
||||||
|
return {
|
||||||
|
offer: btoa(pc.localDescription!.sdp),
|
||||||
|
// Rejects with a message for the user. After a wrong answer the offer is still good for the right one.
|
||||||
|
accept: async (answer: string) => {
|
||||||
|
const description = decode(answer, 'answer');
|
||||||
|
if (pc.signalingState === 'closed') throw new Error('this offer is used up, create a new one');
|
||||||
|
// Already connecting with an earlier answer.
|
||||||
|
if (pc.signalingState !== 'have-local-offer') return;
|
||||||
|
await pc.setRemoteDescription(description).catch(() => {
|
||||||
|
throw new Error('not a valid answer to this offer, copy all of it');
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function answerOffer(offer: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||||
|
events = live(events, signal);
|
||||||
|
const description = decode(offer, 'offer');
|
||||||
|
await downloadsReady();
|
||||||
|
const pc = createPeerConnection(signal);
|
||||||
|
let opened = false;
|
||||||
|
pc.ondatachannel = ({ channel }) => {
|
||||||
|
// The sender's file channel, anything more is none of ours.
|
||||||
|
if (opened) return;
|
||||||
|
opened = true;
|
||||||
|
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||||
|
};
|
||||||
|
failUnconnected(pc, () => opened, events);
|
||||||
|
await pc.setRemoteDescription(description).catch(() => {
|
||||||
|
pc.close();
|
||||||
|
throw new Error('not a valid offer, copy all of it');
|
||||||
|
});
|
||||||
|
await pc.setLocalDescription();
|
||||||
|
await gatherIce(pc);
|
||||||
|
|
||||||
|
return btoa(pc.localDescription!.sdp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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. lost runs once it closed without close() being
|
||||||
|
// called: unreachable, lost or rejected.
|
||||||
|
function trackerSocket(
|
||||||
|
url: string,
|
||||||
|
signal: AbortSignal,
|
||||||
|
events: Events,
|
||||||
|
message: (msg: Message) => void,
|
||||||
|
lost: () => void,
|
||||||
|
) {
|
||||||
|
const ws = own(signal, new WebSocket(url));
|
||||||
|
let opened = false;
|
||||||
|
let accepted = false;
|
||||||
|
let closed = false;
|
||||||
|
const end = (reason: string) => {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
// Already closed unless rejected, this only lets go of it.
|
||||||
|
ws.close();
|
||||||
|
events.log(reason);
|
||||||
|
lost();
|
||||||
|
};
|
||||||
|
const tracker = {
|
||||||
|
ws,
|
||||||
|
// What the tracker answered, if it rejected the announcement.
|
||||||
|
rejected: undefined as string | undefined,
|
||||||
|
alive: () => !closed,
|
||||||
|
close: () => {
|
||||||
|
closed = true;
|
||||||
|
ws.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
ws.addEventListener('open', () => (opened = true));
|
||||||
|
ws.addEventListener('message', ({ data }) => {
|
||||||
|
const msg = parse(data);
|
||||||
|
const failure = msg?.['failure reason'];
|
||||||
|
if (typeof failure !== 'string') {
|
||||||
|
if (!msg) return;
|
||||||
|
accepted = true;
|
||||||
|
return message(msg);
|
||||||
|
}
|
||||||
|
if (accepted) return events.log(`${url}: ${failure}`);
|
||||||
|
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
|
||||||
|
end(`rejected by ${tracker.rejected}`);
|
||||||
|
});
|
||||||
|
ws.addEventListener('close', () => end(opened ? `lost ${url}` : `${url} unreachable`));
|
||||||
|
return tracker;
|
||||||
|
}
|
||||||
|
|
||||||
|
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)[]) {
|
||||||
|
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`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be
|
||||||
|
// answered or never connects. Once the download started the share is used up, the trackers go.
|
||||||
|
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||||
|
events = live(events, signal);
|
||||||
|
const code = randomCode();
|
||||||
|
const hash = await infoHash(code);
|
||||||
|
const peerId = randomBinary(20);
|
||||||
|
const trackers: Tracker[] = [];
|
||||||
|
let busy = false;
|
||||||
|
let shared = false;
|
||||||
|
// The latest offer that came while busy, answered once that peer is out.
|
||||||
|
let waiting: (() => void) | undefined;
|
||||||
|
|
||||||
|
// Without a tracker no further receiver can find the share.
|
||||||
|
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||||
|
|
||||||
|
function next() {
|
||||||
|
busy = false;
|
||||||
|
if (signal.aborted) return;
|
||||||
|
if (stranded()) return events.error(noTracker(trackers));
|
||||||
|
events.log('waiting for the next receiver');
|
||||||
|
const offer = waiting;
|
||||||
|
waiting = undefined;
|
||||||
|
offer?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function answer(ws: WebSocket, url: string, msg: { offer: { sdp: string }; peer_id: string; offer_id: string }) {
|
||||||
|
busy = true;
|
||||||
|
events.log(`offer via ${url}`);
|
||||||
|
const pc = createPeerConnection(signal);
|
||||||
|
// Until the data channel opens this ends the turn, from then on connected does.
|
||||||
|
let settled = false;
|
||||||
|
const giveUp = (reason: string) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
events.log(reason);
|
||||||
|
pc.close();
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
const timeout = setTimeout(() => giveUp('receiver did not connect'), CONNECT_TIMEOUT);
|
||||||
|
pc.ondatachannel = ({ channel }) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
const handshake = connected(pc, channel, url, events, next);
|
||||||
|
const start = () => {
|
||||||
|
handshake.start();
|
||||||
|
shared = true;
|
||||||
|
waiting = undefined;
|
||||||
|
for (const tracker of trackers) tracker.close();
|
||||||
|
};
|
||||||
|
sendFile(pc, channel, file, events, { ...handshake, start }, signal);
|
||||||
|
};
|
||||||
|
pc.addEventListener('connectionstatechange', () => {
|
||||||
|
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp });
|
||||||
|
await pc.setLocalDescription();
|
||||||
|
await gatherIce(pc);
|
||||||
|
} catch (error) {
|
||||||
|
return giveUp(`unusable offer via ${url}: ${error}`);
|
||||||
|
}
|
||||||
|
if (settled) return;
|
||||||
|
announce(ws, hash, peerId, {
|
||||||
|
left: 0,
|
||||||
|
to_peer_id: msg.peer_id,
|
||||||
|
offer_id: msg.offer_id,
|
||||||
|
answer: pc.localDescription,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const url of settings.trackers) {
|
||||||
|
const tracker = trackerSocket(
|
||||||
|
url,
|
||||||
|
signal,
|
||||||
|
events,
|
||||||
|
(msg) => {
|
||||||
|
// 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 (typeof msg.offer_id !== 'string') return;
|
||||||
|
const offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||||
|
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||||
|
else answer(tracker.ws, url, offer);
|
||||||
|
},
|
||||||
|
() => stranded() && events.error(noTracker(trackers)),
|
||||||
|
);
|
||||||
|
tracker.ws.onopen = () => {
|
||||||
|
announce(tracker.ws, hash, peerId, { left: 0, event: 'started' });
|
||||||
|
events.log(`waiting on ${url}`);
|
||||||
|
};
|
||||||
|
trackers.push(tracker);
|
||||||
|
}
|
||||||
|
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// queued one of them. An answer that can't be used or never connects is replaced right away. Once the
|
||||||
|
// download started, every other offer and tracker socket goes.
|
||||||
|
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||||
|
events = live(events, signal);
|
||||||
|
await downloadsReady();
|
||||||
|
const hash = await infoHash(code.trim());
|
||||||
|
if (signal.aborted) return;
|
||||||
|
const peerId = randomBinary(20);
|
||||||
|
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
||||||
|
// before that.
|
||||||
|
const offers = new Map<string, { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean }>();
|
||||||
|
let isConnected = false;
|
||||||
|
let started = false;
|
||||||
|
|
||||||
|
const next = () => {
|
||||||
|
isConnected = false;
|
||||||
|
if (signal.aborted) return;
|
||||||
|
events.log('looking again');
|
||||||
|
for (const [url, { pc }] of offers) if (pc.signalingState === 'closed') offer(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
function offer(url: string) {
|
||||||
|
const pc = createPeerConnection(signal);
|
||||||
|
const entry: { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean } = { pc, lost: false };
|
||||||
|
offers.set(url, entry);
|
||||||
|
const channel = pc.createDataChannel('file');
|
||||||
|
const offerId = randomBinary(20);
|
||||||
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
// Unless another offer is connected, next replaces this one then.
|
||||||
|
const retry = (reason: string) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
if (pc.signalingState === 'closed') return;
|
||||||
|
events.log(reason);
|
||||||
|
pc.close();
|
||||||
|
if (!isConnected && !started && !signal.aborted) offer(url);
|
||||||
|
};
|
||||||
|
channel.onopen = () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
if (isConnected || started) return pc.close();
|
||||||
|
isConnected = true;
|
||||||
|
const handshake = connected(pc, channel, url, events, next);
|
||||||
|
const start = () => {
|
||||||
|
handshake.start();
|
||||||
|
started = true;
|
||||||
|
for (const other of offers.values()) {
|
||||||
|
other.tracker?.close();
|
||||||
|
if (other.pc !== pc) other.pc.close();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
receiveFile(pc, channel, events, { ...handshake, start }, signal);
|
||||||
|
};
|
||||||
|
pc.addEventListener('connectionstatechange', () => {
|
||||||
|
if (pc.connectionState === 'failed' && channel.readyState === 'connecting') retry(`sender via ${url} did not connect`);
|
||||||
|
});
|
||||||
|
|
||||||
|
pc.setLocalDescription()
|
||||||
|
.then(() => gatherIce(pc))
|
||||||
|
.then(() => {
|
||||||
|
if (pc.signalingState === 'closed') return;
|
||||||
|
const tracker = trackerSocket(
|
||||||
|
url,
|
||||||
|
signal,
|
||||||
|
events,
|
||||||
|
(msg) => {
|
||||||
|
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
|
||||||
|
events.log(`answer via ${url}`);
|
||||||
|
// Only one answer per offer, a replacement opens its own socket.
|
||||||
|
tracker.close();
|
||||||
|
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
|
||||||
|
pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() =>
|
||||||
|
retry(`unusable answer via ${url}`),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
entry.lost = true;
|
||||||
|
if (!isConnected && !started && [...offers.values()].every((other) => other.lost)) {
|
||||||
|
events.error(noTracker([...offers.values()].map((other) => other.tracker)));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
entry.tracker = tracker;
|
||||||
|
tracker.ws.onopen = () => {
|
||||||
|
announce(tracker.ws, hash, peerId, {
|
||||||
|
left: 1,
|
||||||
|
numwant: 1,
|
||||||
|
event: 'started',
|
||||||
|
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
||||||
|
});
|
||||||
|
events.log(`looking on ${url}`);
|
||||||
|
};
|
||||||
|
})
|
||||||
|
// Closed in the meantime, nothing to report then.
|
||||||
|
.catch((error) => pc.signalingState === 'closed' || events.error(String(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const url of settings.trackers) offer(url);
|
||||||
|
}
|
||||||
-498
@@ -2,502 +2,4 @@ import { createApp } from 'vue';
|
|||||||
import App from './App.vue';
|
import App from './App.vue';
|
||||||
import './style.css';
|
import './style.css';
|
||||||
|
|
||||||
export const DEFAULT_TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
|
|
||||||
|
|
||||||
export const DEFAULT_STUN_SERVERS = [
|
|
||||||
'stun:stun.pagequit.net:3478',
|
|
||||||
'stun:stun.cloudflare.com:3478',
|
|
||||||
'stun:stun.l.google.com:19302',
|
|
||||||
'stun:stun.nextcloud.com:443',
|
|
||||||
];
|
|
||||||
|
|
||||||
// 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 = {
|
|
||||||
stun: true,
|
|
||||||
stunServers: [...DEFAULT_STUN_SERVERS],
|
|
||||||
trackers: [...DEFAULT_TRACKERS],
|
|
||||||
};
|
|
||||||
|
|
||||||
const CHUNK_SIZE = 16 * 1024;
|
|
||||||
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;
|
|
||||||
const ICE_GRACE = 300;
|
|
||||||
const ICE_TIMEOUT = 5000;
|
|
||||||
|
|
||||||
export type Check = {
|
|
||||||
local: string;
|
|
||||||
remote: string;
|
|
||||||
// Once the user compared the codes: confirm if they match, else reject.
|
|
||||||
confirm: () => void;
|
|
||||||
reject: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Events = {
|
|
||||||
log: (message: string) => void;
|
|
||||||
// Called on both sides once connected, and without a check when it ended undecided.
|
|
||||||
check: (check?: Check) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
function createPeerConnection() {
|
|
||||||
// An empty urls list is a syntax error.
|
|
||||||
const stun = settings.stun && settings.stunServers.length;
|
|
||||||
return new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] });
|
|
||||||
}
|
|
||||||
|
|
||||||
function randomBinary(length: number) {
|
|
||||||
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
|
|
||||||
}
|
|
||||||
|
|
||||||
function randomCode() {
|
|
||||||
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 100_000_000).padStart(8, '0');
|
|
||||||
}
|
|
||||||
|
|
||||||
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
|
|
||||||
async function infoHash(code: string) {
|
|
||||||
const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`));
|
|
||||||
return String.fromCharCode(...new Uint8Array(digest));
|
|
||||||
}
|
|
||||||
|
|
||||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
|
||||||
ws.send(
|
|
||||||
JSON.stringify({
|
|
||||||
action: 'announce',
|
|
||||||
info_hash: hash,
|
|
||||||
peer_id: peerId,
|
|
||||||
numwant: 0,
|
|
||||||
uploaded: 0,
|
|
||||||
downloaded: 0,
|
|
||||||
...params,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
|
|
||||||
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
|
|
||||||
// the same public address: the first one plus a short grace for the other IP family is enough.
|
|
||||||
async function gatherIce(pc: RTCPeerConnection) {
|
|
||||||
if (pc.iceGatheringState === 'complete') return;
|
|
||||||
await new Promise<void>((resolve) => {
|
|
||||||
const timeout = setTimeout(resolve, ICE_TIMEOUT);
|
|
||||||
const done = () => {
|
|
||||||
clearTimeout(timeout);
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
pc.addEventListener('icegatheringstatechange', () => {
|
|
||||||
if (pc.iceGatheringState === 'complete') done();
|
|
||||||
});
|
|
||||||
pc.addEventListener('icecandidate', ({ candidate }) => {
|
|
||||||
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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) };
|
|
||||||
}
|
|
||||||
|
|
||||||
// checked resolves once the user confirmed the codes. 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 confirmations, a rejected check or a peer that left closes the connection and calls next:
|
|
||||||
// tracker signaling goes on with another peer. From start on, sendFile and receiveFile handle a loss.
|
|
||||||
type Handshake = { checked: Promise<void>; start: () => void };
|
|
||||||
|
|
||||||
function connected(
|
|
||||||
pc: RTCPeerConnection,
|
|
||||||
channel: RTCDataChannel,
|
|
||||||
via: string,
|
|
||||||
events: Events,
|
|
||||||
next = () => {},
|
|
||||||
): Handshake {
|
|
||||||
events.log(`connected via ${via}`);
|
|
||||||
events.log('waiting for the security check');
|
|
||||||
let done = false;
|
|
||||||
const end = (reason: string) => {
|
|
||||||
if (done) return;
|
|
||||||
done = true;
|
|
||||||
events.log(reason);
|
|
||||||
events.check();
|
|
||||||
pc.close();
|
|
||||||
next();
|
|
||||||
};
|
|
||||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
|
||||||
channel.addEventListener('close', () => end('peer left before the transfer'));
|
|
||||||
pc.addEventListener('connectionstatechange', () => {
|
|
||||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
checked: new Promise((resolve) =>
|
|
||||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
|
||||||
),
|
|
||||||
start: () => (done = true),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers
|
|
||||||
// with { read } progress, { done } once the download manager read the last byte, or { error } when
|
|
||||||
// its download was cancelled or failed.
|
|
||||||
async function sendFile(
|
|
||||||
pc: RTCPeerConnection,
|
|
||||||
channel: RTCDataChannel,
|
|
||||||
file: File,
|
|
||||||
events: Events,
|
|
||||||
handshake: Handshake,
|
|
||||||
) {
|
|
||||||
if (channel.readyState !== 'open') {
|
|
||||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
|
||||||
}
|
|
||||||
let read = 0;
|
|
||||||
let accepted = false;
|
|
||||||
let sending = false;
|
|
||||||
let stopped = false;
|
|
||||||
// Every event the send loop can wait for calls this.
|
|
||||||
let wake = () => {};
|
|
||||||
const stop = (message?: string) => {
|
|
||||||
if (stopped) return;
|
|
||||||
stopped = true;
|
|
||||||
if (message) events.log(message);
|
|
||||||
wake();
|
|
||||||
};
|
|
||||||
channel.onmessage = ({ data }) => {
|
|
||||||
const message = JSON.parse(data);
|
|
||||||
if (message.ok) accepted = true;
|
|
||||||
// Before that, nothing else can come from a receiver that passed its check.
|
|
||||||
else if (!sending) return;
|
|
||||||
if (message.read) read = message.read;
|
|
||||||
if (message.done) {
|
|
||||||
events.log('delivered');
|
|
||||||
// Finished, a later close is no loss.
|
|
||||||
stopped = true;
|
|
||||||
}
|
|
||||||
if (message.error) stop(`receiver stopped: ${message.error}`);
|
|
||||||
wake();
|
|
||||||
};
|
|
||||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection. Before
|
|
||||||
// sending, connected reports it.
|
|
||||||
const lost = () => stop(sending ? 'connection lost' : undefined);
|
|
||||||
channel.addEventListener('close', lost);
|
|
||||||
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
|
||||||
channel.addEventListener('bufferedamountlow', () => wake());
|
|
||||||
|
|
||||||
await handshake.checked;
|
|
||||||
if (!accepted && !stopped) events.log("waiting for the receiver's security check");
|
|
||||||
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
|
|
||||||
if (stopped) return;
|
|
||||||
|
|
||||||
sending = true;
|
|
||||||
handshake.start();
|
|
||||||
events.log(`sending ${file.name} (${file.size} bytes)`);
|
|
||||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
|
||||||
channel.send(JSON.stringify({ name: file.name, size: file.size }));
|
|
||||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
|
||||||
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
|
|
||||||
await new Promise<void>((resolve) => (wake = resolve));
|
|
||||||
}
|
|
||||||
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
|
||||||
if (stopped) return;
|
|
||||||
channel.send(chunk);
|
|
||||||
}
|
|
||||||
events.log('sent');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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();
|
|
||||||
|
|
||||||
// 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(events: Events) {
|
|
||||||
return downloads.catch((error) => {
|
|
||||||
events.log(`downloads unavailable: ${error}`);
|
|
||||||
throw 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 }.
|
|
||||||
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, handshake: Handshake) {
|
|
||||||
const id = crypto.randomUUID();
|
|
||||||
const frames: HTMLIFrameElement[] = [];
|
|
||||||
let meta: { name: string; size: number } | undefined;
|
|
||||||
let received = 0;
|
|
||||||
let confirmed = 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 | void> = Promise.resolve();
|
|
||||||
const post = (message: object, transfer: Transferable[] = []) =>
|
|
||||||
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));
|
|
||||||
|
|
||||||
let keepalive: ReturnType<typeof setInterval> | undefined;
|
|
||||||
|
|
||||||
// Releases the worker, so a waiting update can take over.
|
|
||||||
function release() {
|
|
||||||
clearInterval(keepalive);
|
|
||||||
for (const frame of frames) frame.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;
|
|
||||||
ended = true;
|
|
||||||
post({ error: reason });
|
|
||||||
reply({ error: reason });
|
|
||||||
events.log(`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') return reply({ read: data });
|
|
||||||
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 === 'finished') {
|
|
||||||
events.log('download complete');
|
|
||||||
reply({ done: true });
|
|
||||||
}
|
|
||||||
if (data === 'cancelled' && !ended) {
|
|
||||||
events.log('download cancelled');
|
|
||||||
reply({ error: 'download cancelled' });
|
|
||||||
}
|
|
||||||
ended = true;
|
|
||||||
release();
|
|
||||||
};
|
|
||||||
worker.postMessage({ id, ...meta }, [port2]);
|
|
||||||
return worker;
|
|
||||||
}, (error) => fail(String(error)));
|
|
||||||
}
|
|
||||||
|
|
||||||
handshake.checked.then(() => {
|
|
||||||
confirmed = true;
|
|
||||||
reply({ ok: true });
|
|
||||||
events.log('waiting for the sender');
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.binaryType = 'arraybuffer';
|
|
||||||
channel.onmessage = ({ data }) => {
|
|
||||||
if (ended || !confirmed) return;
|
|
||||||
if (typeof data === 'string') {
|
|
||||||
meta = JSON.parse(data);
|
|
||||||
handshake.start();
|
|
||||||
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
|
|
||||||
startDownload();
|
|
||||||
} else {
|
|
||||||
received += data.byteLength;
|
|
||||||
post({ chunk: data }, [data]);
|
|
||||||
}
|
|
||||||
if (meta && received === meta.size) {
|
|
||||||
post({ done: true });
|
|
||||||
events.log('received');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
|
|
||||||
// peer only closes the channel in Firefox, Chromium just fails the connection.
|
|
||||||
function lost() {
|
|
||||||
if (meta && received < meta.size) fail('connection lost');
|
|
||||||
}
|
|
||||||
channel.addEventListener('close', lost);
|
|
||||||
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
|
|
||||||
// The sender offers, the receiver answers, no tracker involved.
|
|
||||||
export async function createOffer(file: File, events: Events) {
|
|
||||||
const pc = createPeerConnection();
|
|
||||||
const channel = pc.createDataChannel('file');
|
|
||||||
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events));
|
|
||||||
await pc.setLocalDescription();
|
|
||||||
await gatherIce(pc);
|
|
||||||
|
|
||||||
return {
|
|
||||||
offer: btoa(pc.localDescription!.sdp),
|
|
||||||
accept: (answer: string) => pc.setRemoteDescription({ type: 'answer', sdp: atob(answer.trim()) }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function answerOffer(offer: string, events: Events) {
|
|
||||||
await downloadsReady(events);
|
|
||||||
const pc = createPeerConnection();
|
|
||||||
pc.ondatachannel = ({ channel }) =>
|
|
||||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events));
|
|
||||||
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
|
|
||||||
await pc.setLocalDescription();
|
|
||||||
await gatherIce(pc);
|
|
||||||
|
|
||||||
return btoa(pc.localDescription!.sdp);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
// the code, or got the same one by chance, doesn't end the share.
|
|
||||||
export async function sendViaTracker(file: File, events: Events) {
|
|
||||||
const code = randomCode();
|
|
||||||
const hash = await infoHash(code);
|
|
||||||
const peerId = randomBinary(20);
|
|
||||||
let busy = false;
|
|
||||||
// The latest offer that came while busy, answered once that peer is out.
|
|
||||||
let waiting: (() => void) | undefined;
|
|
||||||
|
|
||||||
async function answer(ws: WebSocket, url: string, msg: { offer: RTCSessionDescriptionInit; peer_id: string; offer_id: string }) {
|
|
||||||
busy = true;
|
|
||||||
events.log(`offer via ${url}`);
|
|
||||||
const pc = createPeerConnection();
|
|
||||||
const next = () => {
|
|
||||||
busy = false;
|
|
||||||
events.log('waiting for the next receiver');
|
|
||||||
const offer = waiting;
|
|
||||||
waiting = undefined;
|
|
||||||
offer?.();
|
|
||||||
};
|
|
||||||
let checking = false;
|
|
||||||
pc.ondatachannel = ({ channel }) => {
|
|
||||||
checking = true;
|
|
||||||
sendFile(pc, channel, file, events, connected(pc, channel, url, events, next));
|
|
||||||
};
|
|
||||||
// An offer whose receiver is gone never gets to the check.
|
|
||||||
pc.addEventListener('connectionstatechange', () => {
|
|
||||||
if (pc.connectionState !== 'failed' || checking) return;
|
|
||||||
pc.close();
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
await pc.setRemoteDescription(msg.offer);
|
|
||||||
await pc.setLocalDescription();
|
|
||||||
await gatherIce(pc);
|
|
||||||
announce(ws, hash, peerId, {
|
|
||||||
left: 0,
|
|
||||||
to_peer_id: msg.peer_id,
|
|
||||||
offer_id: msg.offer_id,
|
|
||||||
answer: pc.localDescription,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const url of settings.trackers) {
|
|
||||||
const ws = new WebSocket(url);
|
|
||||||
ws.onopen = () => {
|
|
||||||
announce(ws, hash, peerId, { left: 0, event: 'started' });
|
|
||||||
events.log(`waiting on ${url}`);
|
|
||||||
};
|
|
||||||
ws.onmessage = (event) => {
|
|
||||||
const msg = JSON.parse(event.data);
|
|
||||||
if (!msg.offer) return;
|
|
||||||
if (busy) waiting = () => answer(ws, url, msg);
|
|
||||||
else answer(ws, url, msg);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
// queued one of them.
|
|
||||||
export async function receiveViaTracker(code: string, events: Events) {
|
|
||||||
await downloadsReady(events);
|
|
||||||
const hash = await infoHash(code);
|
|
||||||
const peerId = randomBinary(20);
|
|
||||||
const offers = new Map<string, RTCPeerConnection>();
|
|
||||||
let isConnected = false;
|
|
||||||
|
|
||||||
const next = () => {
|
|
||||||
isConnected = false;
|
|
||||||
events.log('looking again');
|
|
||||||
for (const [url, pc] of offers) if (pc.signalingState === 'closed') offer(url);
|
|
||||||
};
|
|
||||||
|
|
||||||
function offer(url: string) {
|
|
||||||
const pc = createPeerConnection();
|
|
||||||
offers.set(url, pc);
|
|
||||||
const channel = pc.createDataChannel('file');
|
|
||||||
const offerId = randomBinary(20);
|
|
||||||
channel.onopen = () => {
|
|
||||||
if (isConnected) return pc.close();
|
|
||||||
isConnected = true;
|
|
||||||
receiveFile(pc, channel, events, connected(pc, channel, url, events, next));
|
|
||||||
};
|
|
||||||
|
|
||||||
pc.setLocalDescription()
|
|
||||||
.then(() => gatherIce(pc))
|
|
||||||
.then(() => {
|
|
||||||
const ws = new WebSocket(url);
|
|
||||||
ws.onopen = () => {
|
|
||||||
announce(ws, hash, peerId, {
|
|
||||||
left: 1,
|
|
||||||
numwant: 1,
|
|
||||||
event: 'started',
|
|
||||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
|
||||||
});
|
|
||||||
events.log(`looking on ${url}`);
|
|
||||||
};
|
|
||||||
ws.onmessage = (event) => {
|
|
||||||
const msg = JSON.parse(event.data);
|
|
||||||
if (msg.answer && msg.offer_id === offerId) {
|
|
||||||
events.log(`answer via ${url}`);
|
|
||||||
pc.setRemoteDescription(msg.answer);
|
|
||||||
// Only one answer per offer, a replacement opens its own connection.
|
|
||||||
ws.close();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const url of settings.trackers) offer(url);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mounted last: App.vue imports the core from this module.
|
|
||||||
createApp(App).mount('#app');
|
createApp(App).mount('#app');
|
||||||
+161
-27
@@ -48,7 +48,10 @@ h1, h2, h3, h4, h5, h6 {
|
|||||||
|
|
||||||
--color-primary: #5865f2;
|
--color-primary: #5865f2;
|
||||||
--color-primary-hover: #4752c4;
|
--color-primary-hover: #4752c4;
|
||||||
|
--color-on-primary: #fff;
|
||||||
--color-secondary: #eb459e;
|
--color-secondary: #eb459e;
|
||||||
|
/* The secondary is too dark for text on the surfaces, this one keeps 4.5:1 */
|
||||||
|
--color-secondary-text: #f278b7;
|
||||||
--color-success: #23a559;
|
--color-success: #23a559;
|
||||||
|
|
||||||
--color-bg: #313338;
|
--color-bg: #313338;
|
||||||
@@ -82,7 +85,7 @@ body {
|
|||||||
|
|
||||||
/* Layout */
|
/* Layout */
|
||||||
|
|
||||||
header, main {
|
header, main, footer {
|
||||||
max-width: 64rem;
|
max-width: 64rem;
|
||||||
margin-inline: auto;
|
margin-inline: auto;
|
||||||
padding-inline: var(--space-4);
|
padding-inline: var(--space-4);
|
||||||
@@ -144,7 +147,7 @@ section {
|
|||||||
border-top: 1px solid var(--color-border);
|
border-top: 1px solid var(--color-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
h3 {
|
h3, article summary {
|
||||||
font-size: var(--text-sm);
|
font-size: var(--text-sm);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
@@ -152,12 +155,6 @@ h3 {
|
|||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
small {
|
|
||||||
font-weight: normal;
|
|
||||||
text-transform: none;
|
|
||||||
letter-spacing: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
label, section p {
|
label, section p {
|
||||||
font-size: var(--text-sm);
|
font-size: var(--text-sm);
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
@@ -181,6 +178,10 @@ input, textarea {
|
|||||||
|
|
||||||
input:focus, textarea:focus {
|
input:focus, textarea:focus {
|
||||||
border-color: var(--color-secondary);
|
border-color: var(--color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||||
|
input:not([type='checkbox'], [type='file']):focus-visible, textarea:focus-visible {
|
||||||
outline: none;
|
outline: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,7 +202,7 @@ button {
|
|||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
background: var(--color-primary);
|
background: var(--color-primary);
|
||||||
color: var(--color-text);
|
color: var(--color-on-primary);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background-color var(--transition);
|
transition: background-color var(--transition);
|
||||||
@@ -223,22 +224,64 @@ button:disabled {
|
|||||||
|
|
||||||
[role='group'] {
|
[role='group'] {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
gap: var(--space-2);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='group'] > input {
|
/* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
|
||||||
border-start-end-radius: 0;
|
#send-code, #receive-code {
|
||||||
border-end-end-radius: 0;
|
color: var(--color-secondary-text);
|
||||||
|
font-family: ui-monospace, monospace;
|
||||||
|
font-size: var(--text-lg);
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.15em;
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='group'] > button {
|
#send-code {
|
||||||
border-start-start-radius: 0;
|
flex: 1;
|
||||||
border-end-start-radius: 0;
|
padding: var(--space-2) var(--space-3);
|
||||||
|
background: var(--color-input);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
user-select: all;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Drop zone, the invisible file input covers the whole label */
|
/* Copy buttons, secondary next to the value they copy */
|
||||||
|
|
||||||
label:has(> [type='file']) {
|
[data-copy] {
|
||||||
|
padding: var(--space-1) var(--space-3);
|
||||||
|
background: transparent;
|
||||||
|
border-color: var(--color-border);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-copy]:hover:not(:disabled) {
|
||||||
|
background: var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Manual signaling, folded away below the tracker in each card */
|
||||||
|
|
||||||
|
article details {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
border-radius: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
article summary {
|
||||||
|
padding: var(--space-4) 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
article details section {
|
||||||
|
padding-top: var(--space-2);
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
|
||||||
|
|
||||||
|
label:has(> [type='file']), #incoming {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -265,6 +308,16 @@ label:has(> [type='file']:focus-visible) {
|
|||||||
outline-offset: 2px;
|
outline-offset: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#incoming {
|
||||||
|
border-style: solid;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#incoming button {
|
||||||
|
margin-top: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
[type='file'] {
|
[type='file'] {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
@@ -272,11 +325,61 @@ label:has(> [type='file']:focus-visible) {
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
label strong {
|
label strong, #incoming strong {
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Progress and what went wrong, below the file on both sides */
|
||||||
|
|
||||||
|
article > p[role='alert'] {
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
article > p[role='alert']::first-letter {
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
p:has(> progress) {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-3);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress {
|
||||||
|
flex: 1;
|
||||||
|
height: 0.5rem;
|
||||||
|
appearance: none;
|
||||||
|
border: none;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--color-input);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
progress::-webkit-progress-bar {
|
||||||
|
background: var(--color-input);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress::-webkit-progress-value {
|
||||||
|
background: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress::-moz-progress-bar {
|
||||||
|
background: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress[value='100']::-webkit-progress-value {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress[value='100']::-moz-progress-bar {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
/* Switch, like Pico's role="switch" */
|
/* Switch, like Pico's role="switch" */
|
||||||
|
|
||||||
label:has([role='switch']) {
|
label:has([role='switch']) {
|
||||||
@@ -319,23 +422,23 @@ label:has([role='switch']) {
|
|||||||
|
|
||||||
/* Security check callout */
|
/* Security check callout */
|
||||||
|
|
||||||
[role='alert'] {
|
aside {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: var(--space-4);
|
gap: var(--space-4);
|
||||||
padding: var(--space-4) var(--space-6);
|
padding: var(--space-4) var(--space-6);
|
||||||
background: color-mix(in srgb, var(--color-secondary) 10%, var(--color-surface));
|
background: color-mix(in srgb, var(--color-secondary) 8%, var(--color-surface));
|
||||||
border: 1px solid var(--color-secondary);
|
border: 1px solid var(--color-secondary);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='alert'] p {
|
aside p {
|
||||||
flex: 1 1 100%;
|
flex: 1 1 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Monospaced in a grid, so both codes line up byte by byte */
|
/* Monospaced in a grid, so both codes line up byte by byte */
|
||||||
[role='alert'] dl {
|
aside dl {
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: auto auto;
|
grid-template-columns: auto auto;
|
||||||
@@ -343,31 +446,62 @@ label:has([role='switch']) {
|
|||||||
column-gap: var(--space-3);
|
column-gap: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='alert'] dt {
|
aside dt {
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='alert'] div {
|
aside div {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='alert'] button + button {
|
aside button + button {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
border-color: var(--color-border);
|
border-color: var(--color-border);
|
||||||
|
color: var(--color-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
[role='alert'] button + button:hover {
|
aside button + button:hover {
|
||||||
background: var(--color-border);
|
background: var(--color-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
output {
|
output {
|
||||||
color: var(--color-secondary);
|
color: var(--color-secondary-text);
|
||||||
font-family: ui-monospace, monospace;
|
font-family: ui-monospace, monospace;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Source link, quiet below everything */
|
||||||
|
|
||||||
|
footer {
|
||||||
|
padding-bottom: var(--space-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a:hover {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer img {
|
||||||
|
filter: grayscale(1);
|
||||||
|
opacity: 0.6;
|
||||||
|
transition: opacity var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a:hover img {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
/* Servers */
|
/* Servers */
|
||||||
|
|
||||||
#servers > div {
|
#servers > div {
|
||||||
|
|||||||
Reference in new issue
Block a user