Salt the tracker swarm with the clock or an own salt
The code used to be derived with a fixed salt, so a tracker could compute a table from swarm to code ahead of time, once for every share. Now the salt is the UTC 6 minute window the share was made in, and the code's new 11th character names that window, so the receiver finds it even with a clock hours off. Use own salt adds a salt both sides agree on, which nobody can guess ahead for; Generate makes a random one. The salt is locked while a tracker share or search runs, and a receiver that finds no sender is told to check the salt too. Settings are no longer kept in localStorage: a remembered list or salt that differs from the other side's would silently break shares. The core now reports when a share expires and until when it lasts, and the session owns a tracker's timers, so a socket still closing after an abort announces nothing more. Header options line up with the cards, disabled switches look disabled, and sizes, percents and times don't wrap. postcss 8.5.32. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e3a2b348d6
commit
2e47b55901
7 files changed
+449
-129
No files matched your search
@@ -6,7 +6,7 @@ size limit: the file goes directly to the other person and is never stored on a
|
|||||||
## How to send a file
|
## How to send a file
|
||||||
|
|
||||||
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
||||||
a 10 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
|
an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
|
||||||
get the file, or pretend to be you, so give it to nobody else.
|
get the file, or pretend to be you, so give it to nobody else.
|
||||||
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
||||||
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
|
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
|
||||||
@@ -74,7 +74,7 @@ networks, a direct connection may not be possible.
|
|||||||
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
|
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
|
||||||
receiver goes down the list until it finds the sender, and the trackers it passes keep its
|
receiver goes down the list until it finds the sender, and the trackers it passes keep its
|
||||||
encrypted offer. Nobody without the code learns your address through a tracker.
|
encrypted offer. Nobody without the code learns your address through a tracker.
|
||||||
- Settings (STUN on or off, your server lists) are kept in your browser only.
|
- Nothing is kept: every reload starts with the default settings.
|
||||||
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
|
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
|
||||||
host your own (below).
|
host your own (below).
|
||||||
|
|
||||||
@@ -86,6 +86,15 @@ brings back the original lists. The order matters: the sender stays on the first
|
|||||||
works, the receiver tries them in order until it finds the sender. Both lists must contain that
|
works, the receiver tries them in order until it finds the sender. Both lists must contain that
|
||||||
tracker.
|
tracker.
|
||||||
|
|
||||||
|
The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC):
|
||||||
|
guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the
|
||||||
|
receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could
|
||||||
|
still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both
|
||||||
|
sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody
|
||||||
|
can guess ahead for a salt they don't know.
|
||||||
|
|
||||||
|
Nothing of this is kept, a reload brings back the defaults.
|
||||||
|
|
||||||
## Host your own
|
## Host your own
|
||||||
|
|
||||||
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
||||||
|
|||||||
@@ -2,10 +2,26 @@
|
|||||||
|
|
||||||
## Ideas
|
## Ideas
|
||||||
|
|
||||||
|
- Unstick a wrong salt: while a tracker share or search runs, the salt is locked, and a receiver
|
||||||
|
told "Check the code and the salt" can't change it for up to 6 minutes. The receiver doesn't need
|
||||||
|
the lock: like the code field, the salt could stay editable and count from the next Receive
|
||||||
|
(`saltLocked` only for `side === 'send'`). The sender does, the code shown must match the salt
|
||||||
|
shown: a Stop button next to the valid code would end the share, unlock the salt and also let a
|
||||||
|
share be withdrawn early. Changing the salt itself shouldn't end a share, a stray click would.
|
||||||
|
|
||||||
- Resume interrupted transfers: the receiver already reports how much the download manager has
|
- Resume interrupted transfers: the receiver already reports how much the download manager has
|
||||||
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
|
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
|
||||||
finished or failed download though, so a resume would have to start a new one.
|
finished or failed download though, so a resume would have to start a new one.
|
||||||
|
|
||||||
|
- Keep user settings again: for now every reload starts from the defaults, the server lists and the
|
||||||
|
own salt too. Open which ones to keep, and how a kept one that differs from the other side's would
|
||||||
|
show, instead of silently breaking a share.
|
||||||
|
|
||||||
|
- Version the protocol for 1.0: put a version into the key derivation, e.g. `hellcon/1 <salt>` as
|
||||||
|
the PBKDF2 salt in `secrets`. Until then any change to it silently breaks sharing between
|
||||||
|
deployments on different versions, the receiver only sees "No sender with this code". Open how a
|
||||||
|
mismatch would be reported, e.g. by trying the previous version's swarm too.
|
||||||
|
|
||||||
## Open observations
|
## Open observations
|
||||||
|
|
||||||
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
|
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
|
||||||
|
|||||||
+202
-37
@@ -37,6 +37,14 @@ const PROBE_TIMEOUT = 2000;
|
|||||||
const PROOF_TIMEOUT = 10_000;
|
const PROOF_TIMEOUT = 10_000;
|
||||||
const CONNECT_TIMEOUT = 30_000;
|
const CONNECT_TIMEOUT = 30_000;
|
||||||
const DOWNLOAD_GRACE = 1000;
|
const DOWNLOAD_GRACE = 1000;
|
||||||
|
// Every page's clock starts a second into the window from 12:00 to 12:06 UTC unless a test sets
|
||||||
|
// another time, so the test knows the salt of every code, see saltOf. SALT_WINDOW is the one in
|
||||||
|
// src/core.ts.
|
||||||
|
const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1);
|
||||||
|
const SALT_WINDOW = 6 * 60_000;
|
||||||
|
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||||
|
// When a share or search ends, in its error. The browser writes the time its own way.
|
||||||
|
const UNTIL = String.raw`until \d\d?:\d\d(?:[\u00a0\u202f][AP]M)?`;
|
||||||
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
||||||
const HELD_SIZE = 3 * WINDOW;
|
const HELD_SIZE = 3 * WINDOW;
|
||||||
// What the fake STUN server reports as public address, reserved for documentation.
|
// What the fake STUN server reports as public address, reserved for documentation.
|
||||||
@@ -73,7 +81,7 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
|||||||
},
|
},
|
||||||
async tracker(sender, receiver) {
|
async tracker(sender, receiver) {
|
||||||
await sender.click('#share');
|
await sender.click('#share');
|
||||||
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{10}$/);
|
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{11}$/);
|
||||||
await sender.click('#copy-send-code');
|
await sender.click('#copy-send-code');
|
||||||
await expect(sender.locator('#copy-send-code')).toHaveText('Copied');
|
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');
|
||||||
@@ -134,13 +142,18 @@ test.afterAll(async () => {
|
|||||||
stun.close();
|
stun.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
// init runs in the page before the app. base is the app's URL, the dev server's by default.
|
// init runs in the page before the app. base is the app's URL, the dev server's by default. time is
|
||||||
async function open(name: string, { init, base = url }: { init?: () => void; base?: string } = {}) {
|
// where the page's clock starts.
|
||||||
|
async function open(
|
||||||
|
name: string,
|
||||||
|
{ init, base = url, time = TEST_TIME }: { init?: () => void; base?: string; time?: number } = {},
|
||||||
|
) {
|
||||||
browsers[name] ??= BROWSERS[name]!.launch();
|
browsers[name] ??= BROWSERS[name]!.launch();
|
||||||
const browser = await browsers[name];
|
const browser = await browsers[name];
|
||||||
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
|
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
|
||||||
contexts.push(context);
|
contexts.push(context);
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
|
await page.clock.install({ time });
|
||||||
const trackers: PageSocket[] = [];
|
const trackers: PageSocket[] = [];
|
||||||
sockets.set(page, trackers);
|
sockets.set(page, trackers);
|
||||||
page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws));
|
page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws));
|
||||||
@@ -450,13 +463,28 @@ for (const [from, to] of [
|
|||||||
test(`own tracker: ${from} sends to ${to}`, async () => {
|
test(`own tracker: ${from} sends to ${to}`, async () => {
|
||||||
const tracker = await ownTracker();
|
const tracker = await ownTracker();
|
||||||
const [sender, receiver] = await Promise.all([open(from), open(to)]);
|
const [sender, receiver] = await Promise.all([open(from), open(to)]);
|
||||||
|
// With an own salt, the clock's is in the live tests.
|
||||||
|
for (const page of [sender, receiver]) {
|
||||||
|
await page.uncheck('#stun');
|
||||||
|
await page.click('#servers summary');
|
||||||
|
await page.fill('#trackers', tracker);
|
||||||
|
await page.check('#own-salt');
|
||||||
|
await page.fill('#salt', 'own tracker');
|
||||||
|
}
|
||||||
|
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||||
|
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The code tells its window, the receiver's clock can be hours off. With the clock's salt.
|
||||||
|
test(`own tracker: ${from} sends to ${to} with the receiver's clock 2 hours behind`, async () => {
|
||||||
|
const tracker = await ownTracker();
|
||||||
|
const [sender, receiver] = await Promise.all([open(from), open(to, { time: TEST_TIME - 2 * 3_600_000 })]);
|
||||||
for (const page of [sender, receiver]) {
|
for (const page of [sender, receiver]) {
|
||||||
await page.uncheck('#stun');
|
await page.uncheck('#stun');
|
||||||
await page.click('#servers summary');
|
await page.click('#servers summary');
|
||||||
await page.fill('#trackers', tracker);
|
await page.fill('#trackers', tracker);
|
||||||
}
|
}
|
||||||
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||||
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,7 +502,7 @@ test('build: chromium sends to firefox from the production build', async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
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, a reload brings back the defaults`, async () => {
|
||||||
const page = await open(name);
|
const page = await open(name);
|
||||||
const core = () =>
|
const core = () =>
|
||||||
page.evaluate(
|
page.evaluate(
|
||||||
@@ -489,10 +517,16 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await expect(page.locator('#servers')).toContainText('without #: tracker.example, wss://tracker.example/#');
|
await expect(page.locator('#servers')).toContainText('without #: tracker.example, wss://tracker.example/#');
|
||||||
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
||||||
|
|
||||||
|
await page.uncheck('#stun');
|
||||||
|
await page.check('#own-salt');
|
||||||
|
await page.fill('#salt', 'salt');
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.click('#servers summary');
|
await page.click('#servers summary');
|
||||||
await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example');
|
await expect(page.locator('#trackers')).toHaveValue(/^wss:\/\/tracker\.pagequit\.net\n/);
|
||||||
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
await expect(page.locator('#stun')).toBeChecked();
|
||||||
|
await expect(page.locator('#own-salt')).not.toBeChecked();
|
||||||
|
await expect(page.locator('#salt')).toHaveCount(0);
|
||||||
|
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
|
||||||
|
|
||||||
await page.fill('#receive-code', 'code');
|
await page.fill('#receive-code', 'code');
|
||||||
await page.fill('#trackers', '');
|
await page.fill('#trackers', '');
|
||||||
@@ -701,7 +735,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
// DOWNLOAD_GRACE. The frame holding the worker goes right away, it would block an update.
|
// DOWNLOAD_GRACE. The frame holding the worker goes right away, it would block an update.
|
||||||
test(`boundary: ${name} keeps a finished download's frame for DOWNLOAD_GRACE`, async () => {
|
test(`boundary: ${name} keeps a finished download's frame for DOWNLOAD_GRACE`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
await receiver.clock.install();
|
|
||||||
|
|
||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
await connect('offline', sender, receiver, await payload(Buffer.alloc(0), 'empty.bin'));
|
await connect('offline', sender, receiver, await payload(Buffer.alloc(0), 'empty.bin'));
|
||||||
@@ -762,7 +795,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
const first = await sender.locator('#send-code').textContent();
|
const first = await sender.locator('#send-code').textContent();
|
||||||
await sender.click('#share');
|
await sender.click('#share');
|
||||||
await expect(sender.locator('#send-code')).not.toHaveText(first!);
|
await expect(sender.locator('#send-code')).not.toHaveText(first!);
|
||||||
await receiver.fill('#receive-code', 'nobody');
|
await receiver.fill('#receive-code', 'nobodyhere0');
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
||||||
// The log tells the sessions apart.
|
// The log tells the sessions apart.
|
||||||
@@ -1002,7 +1035,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
// The 6 minutes only limit finding each other, a receiver connected by then still gets the file.
|
// The 6 minutes only limit finding each other, a receiver connected by then still gets the file.
|
||||||
test(`live tracker: ${name} a receiver connected before the expiry downloads after it`, async () => {
|
test(`live tracker: ${name} a receiver connected before the expiry downloads after it`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
await Promise.all([sender, receiver].map((page) => page.clock.install()));
|
|
||||||
const source = await payload(randomBytes(SIZE));
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
@@ -1091,7 +1123,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await receiver.uncheck('#stun');
|
await receiver.uncheck('#stun');
|
||||||
await receiver.click('#servers summary');
|
await receiver.click('#servers summary');
|
||||||
await receiver.fill('#trackers', urls.join('\n'));
|
await receiver.fill('#trackers', urls.join('\n'));
|
||||||
await receiver.fill('#receive-code', 'somecode');
|
await receiver.fill('#receive-code', 'somecode123');
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`);
|
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`);
|
||||||
// A third one would come within milliseconds.
|
// A third one would come within milliseconds.
|
||||||
@@ -1146,6 +1178,134 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The info_hash tells which salt a share took: the window its code ends with, or that and the own
|
||||||
|
// salt, trimmed and NFC. A code made late in a window still lasts 6 minutes. The salt stays as it is
|
||||||
|
// while a share or search runs.
|
||||||
|
test(`salt: ${name} a share takes the clock's salt or the own one, which stays while it runs`, async () => {
|
||||||
|
const sender = await open(name);
|
||||||
|
const hashes: string[] = [];
|
||||||
|
await mockTrackers(sender, (msg) => {
|
||||||
|
if (msg.event === 'started') hashes.push(msg.info_hash as string);
|
||||||
|
return { action: 'announce', interval: 120, info_hash: msg.info_hash };
|
||||||
|
});
|
||||||
|
const label = sender.locator('label[for=send-code]');
|
||||||
|
const valid = /^\s*Code, give this to the receiver, valid until .+:\s*$/;
|
||||||
|
// The time as the label writes it, in the page's locale and time zone.
|
||||||
|
const time = (at: number) =>
|
||||||
|
sender.evaluate(
|
||||||
|
(at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'),
|
||||||
|
at,
|
||||||
|
);
|
||||||
|
// The code and info_hash of the share start begins, by default a click on Share.
|
||||||
|
const share = async (start = () => sender.click('#share')) => {
|
||||||
|
const count = hashes.length;
|
||||||
|
await start();
|
||||||
|
await expect.poll(() => hashes.length).toBe(count + 1);
|
||||||
|
return { code: (await sender.locator('#send-code').textContent())!, hash: hashes.at(-1) };
|
||||||
|
};
|
||||||
|
|
||||||
|
await withLogs(sender, sender, async () => {
|
||||||
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
|
const first = await share();
|
||||||
|
expect(first.hash).toBe(swarm(first.code));
|
||||||
|
await expect(label).toHaveText(valid);
|
||||||
|
// toHaveText takes a no-break space for any space, the text itself has to have it.
|
||||||
|
expect(await label.textContent()).toMatch(new RegExp(`${UNTIL}:`));
|
||||||
|
|
||||||
|
// 12:05:30, half a minute before the window ends. Still valid for 6 minutes, until 12:11.
|
||||||
|
await sender.clock.fastForward('05:29');
|
||||||
|
const late = await share();
|
||||||
|
expect(late.code.at(-1)).toBe(first.code.at(-1));
|
||||||
|
expect(late.hash).toBe(swarm(late.code));
|
||||||
|
await expect(label).toHaveText(valid);
|
||||||
|
expect(await label.textContent()).toContain(`until ${await time(Date.UTC(2026, 0, 1, 12, 11, 30))}:`);
|
||||||
|
|
||||||
|
await sender.clock.fastForward('06:00');
|
||||||
|
await expect(label).toHaveText('Code, no longer valid:');
|
||||||
|
const next = await share();
|
||||||
|
expect(next.code.at(-1)).not.toBe(first.code.at(-1));
|
||||||
|
expect(next.hash).toBe(swarm(next.code));
|
||||||
|
|
||||||
|
// The switch, and the salt with Generate while it's on.
|
||||||
|
const locked = async (disabled: boolean) => {
|
||||||
|
const ids = (await sender.isChecked('#own-salt')) ? ['#own-salt', '#salt', '#generate-salt'] : ['#own-salt'];
|
||||||
|
for (const id of ids) await expect(sender.locator(id)).toBeEnabled({ enabled: !disabled });
|
||||||
|
};
|
||||||
|
await locked(true);
|
||||||
|
await sender.clock.fastForward('06:00');
|
||||||
|
await expect(label).toHaveText('Code, no longer valid:');
|
||||||
|
await locked(false);
|
||||||
|
|
||||||
|
await sender.check('#own-salt');
|
||||||
|
await expect(sender.locator('#share')).toBeDisabled();
|
||||||
|
await sender.fill('#salt', ' ');
|
||||||
|
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'true');
|
||||||
|
await expect(sender.locator('#share')).toBeDisabled();
|
||||||
|
// ü decomposed, u and a combining diaeresis.
|
||||||
|
await sender.fill('#salt', ' Gru\u0308ße ');
|
||||||
|
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'false');
|
||||||
|
const own = await share();
|
||||||
|
expect(own.hash).toBe(swarm(own.code, 'Grüße'));
|
||||||
|
await expect(label).toHaveText(/^\s*Code, give this and your salt to the receiver, valid until .+:\s*$/);
|
||||||
|
await locked(true);
|
||||||
|
|
||||||
|
// 16 of the code's characters.
|
||||||
|
await sender.clock.fastForward('06:00');
|
||||||
|
await locked(false);
|
||||||
|
await sender.click('#generate-salt');
|
||||||
|
const generated = await sender.inputValue('#salt');
|
||||||
|
expect(generated).toMatch(/^[0-9a-zA-Z]{16}$/);
|
||||||
|
const resalted = await share();
|
||||||
|
expect(resalted.hash).toBe(swarm(resalted.code, generated));
|
||||||
|
|
||||||
|
// What can't be a code is told right away, that search is over.
|
||||||
|
await sender.fill('#receive-code', 'abcdefghij');
|
||||||
|
await sender.click('#receive');
|
||||||
|
await expect(sender.locator('#receive-error')).toHaveText('a code has 11 letters and digits, check it');
|
||||||
|
await locked(false);
|
||||||
|
|
||||||
|
await sender.fill('#receive-code', 'abcdefghijk');
|
||||||
|
await sender.click('#receive');
|
||||||
|
await expect.poll(() => hashes).toContain(swarm('abcdefghijk', generated));
|
||||||
|
await locked(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Until the transfer is over, on both sides.
|
||||||
|
test(`salt: ${name} stays while the peers are connected`, async () => {
|
||||||
|
const tracker = await ownTracker();
|
||||||
|
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||||
|
for (const page of [sender, receiver]) {
|
||||||
|
await page.uncheck('#stun');
|
||||||
|
await page.click('#servers summary');
|
||||||
|
await page.fill('#trackers', tracker);
|
||||||
|
await page.check('#own-salt');
|
||||||
|
await page.fill('#salt', 'salt');
|
||||||
|
}
|
||||||
|
const locked = (disabled: boolean) =>
|
||||||
|
Promise.all(
|
||||||
|
[sender, receiver].flatMap((page) =>
|
||||||
|
['#own-salt', '#salt', '#generate-salt'].map((id) =>
|
||||||
|
expect(page.locator(id)).toBeEnabled({ enabled: !disabled }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await withLogs(sender, receiver, async () => {
|
||||||
|
await connect('tracker', sender, receiver, await payload(randomBytes(1000)));
|
||||||
|
await expect(sender.locator('#send-status')).toHaveText('Waiting for the receiver to download');
|
||||||
|
await expect(receiver.locator('#receive-status')).toHaveText('Click Download to save the file');
|
||||||
|
await locked(true);
|
||||||
|
|
||||||
|
const started = downloadStarts(receiver);
|
||||||
|
await receiver.click('#download');
|
||||||
|
await started;
|
||||||
|
await expect(sender.locator('#send-status')).toHaveText('Delivered');
|
||||||
|
await expect(receiver.locator('#receive-status')).toHaveText('Download complete');
|
||||||
|
await locked(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Trackers drop a peer that doesn't announce again on their interval, the defaults after 2 to 3
|
// Trackers drop a peer that doesn't announce again on their interval, the defaults after 2 to 3
|
||||||
// minutes. A code nobody uses still ends after 6 minutes, on both sides.
|
// minutes. A code nobody uses still ends after 6 minutes, on both sides.
|
||||||
test(`tracker: ${name} both sides announce again until they give up after 6 minutes`, async () => {
|
test(`tracker: ${name} both sides announce again until they give up after 6 minutes`, async () => {
|
||||||
@@ -1156,7 +1316,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
// 0 would announce in a loop, the app waits 30 s at least.
|
// 0 would announce in a loop, the app waits 30 s at least.
|
||||||
const trackers = await Promise.all(
|
const trackers = await Promise.all(
|
||||||
pages.map(async (page, i) => {
|
pages.map(async (page, i) => {
|
||||||
await page.clock.install();
|
|
||||||
return mockTrackers(page, (msg) => {
|
return mockTrackers(page, (msg) => {
|
||||||
announced[i]!.push(msg);
|
announced[i]!.push(msg);
|
||||||
return { action: 'announce', interval: 0, info_hash: msg.info_hash };
|
return { action: 'announce', interval: 0, info_hash: msg.info_hash };
|
||||||
@@ -1191,12 +1350,12 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
|
|
||||||
await fastForward(330_000);
|
await fastForward(330_000);
|
||||||
await expect(sender.locator('#send-error')).toHaveText(
|
await expect(sender.locator('#send-error')).toHaveText(
|
||||||
'nobody received the file within 6 minutes, share it again',
|
new RegExp(`^nobody received the file ${UNTIL}, share it again$`),
|
||||||
);
|
);
|
||||||
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
|
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
|
||||||
await expect(sender.locator('#copy-send-code')).toBeDisabled();
|
await expect(sender.locator('#copy-send-code')).toBeDisabled();
|
||||||
await expect(receiver.locator('#receive-error')).toHaveText(
|
await expect(receiver.locator('#receive-error')).toHaveText(
|
||||||
'no sender answered within 6 minutes, check the code and try again',
|
new RegExp(`^no sender answered ${UNTIL}, ask the sender for a new code$`),
|
||||||
);
|
);
|
||||||
await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]);
|
await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]);
|
||||||
await expectClosed(sender);
|
await expectClosed(sender);
|
||||||
@@ -1225,7 +1384,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||||
for (let session = 0; session < 5; session++) {
|
for (let session = 0; session < 5; session++) {
|
||||||
await sender.click('#share');
|
await sender.click('#share');
|
||||||
await receiver.fill('#receive-code', `nobody ${session}`);
|
await receiver.fill('#receive-code', `nobodyhere${session}`);
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
}
|
}
|
||||||
await expect.poll(deadlines).toEqual([1, 1]);
|
await expect.poll(deadlines).toEqual([1, 1]);
|
||||||
@@ -1245,7 +1404,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
// gets no turn either.
|
// gets no turn either.
|
||||||
test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => {
|
test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => {
|
||||||
const sender = await open(name, { init: holdDecrypts });
|
const sender = await open(name, { init: holdDecrypts });
|
||||||
await sender.clock.install();
|
|
||||||
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
|
||||||
const decrypts = () =>
|
const decrypts = () =>
|
||||||
sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts);
|
sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts);
|
||||||
@@ -1259,7 +1417,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
|
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
|
||||||
await sender.clock.fastForward('06:00');
|
await sender.clock.fastForward('06:00');
|
||||||
await expect(sender.locator('#send-error')).toHaveText(
|
await expect(sender.locator('#send-error')).toHaveText(
|
||||||
'nobody received the file within 6 minutes, share it again',
|
new RegExp(`^nobody received the file ${UNTIL}, share it again$`),
|
||||||
);
|
);
|
||||||
|
|
||||||
await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts());
|
await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts());
|
||||||
@@ -1324,10 +1482,10 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await fastForward('06:00');
|
await fastForward('06:00');
|
||||||
await fastForward(CONNECT_TIMEOUT);
|
await fastForward(CONNECT_TIMEOUT);
|
||||||
await expect(sender.locator('#send-error')).toHaveText(
|
await expect(sender.locator('#send-error')).toHaveText(
|
||||||
`no receiver connected within 6 minutes: the receiver ${NO_PUBLIC}`,
|
new RegExp(`^no receiver connected ${UNTIL}: the receiver ${NO_PUBLIC}$`),
|
||||||
);
|
);
|
||||||
await expect(receiver.locator('#receive-error')).toHaveText(
|
await expect(receiver.locator('#receive-error')).toHaveText(
|
||||||
`no sender connected within 6 minutes: this side ${NO_PUBLIC}`,
|
new RegExp(`^no sender connected ${UNTIL}: this side ${NO_PUBLIC}$`),
|
||||||
);
|
);
|
||||||
await expectClosed(sender);
|
await expectClosed(sender);
|
||||||
await expectClosed(receiver);
|
await expectClosed(receiver);
|
||||||
@@ -1346,7 +1504,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
|
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
|
||||||
const code = (await sender.locator('#send-code').textContent())!;
|
const code = (await sender.locator('#send-code').textContent())!;
|
||||||
await intrude(intruder, swarm(code));
|
await intrude(intruder, swarm(code));
|
||||||
await intruder.fill('#receive-code', 'notthecode');
|
await intruder.fill('#receive-code', 'notthecode0');
|
||||||
await intruder.click('#receive');
|
await intruder.click('#receive');
|
||||||
await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 });
|
await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 });
|
||||||
await intruder.context().close();
|
await intruder.context().close();
|
||||||
@@ -1366,7 +1524,6 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
|
|
||||||
test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => {
|
test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]);
|
const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]);
|
||||||
await sender.clock.install();
|
|
||||||
const source = await payload(randomBytes(SIZE));
|
const source = await payload(randomBytes(SIZE));
|
||||||
|
|
||||||
await withLogs(sender, receiver, async () => {
|
await withLogs(sender, receiver, async () => {
|
||||||
@@ -1537,15 +1694,27 @@ async function interpose(middle: Page, code: string, toSender: Announce[], toRec
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// What secrets in src/core.ts derives from the code for info, PBKDF2 once per code.
|
// The salt src/core.ts derives with for a code made or entered around TEST_TIME: the start of the window
|
||||||
const masters = new Map<string, Buffer>();
|
// the code's last character tells, the one nearest TEST_TIME's, then own if given.
|
||||||
function secret(code: string, info: string, length: number) {
|
function saltOf(code: string, own?: string) {
|
||||||
if (!masters.has(code)) masters.set(code, pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'));
|
const now = Math.floor(TEST_TIME / SALT_WINDOW);
|
||||||
return Buffer.from(hkdfSync('sha256', masters.get(code)!, '', info, length));
|
const cycle = CODE_CHARS.length;
|
||||||
|
const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle;
|
||||||
|
const salt = new Date((now + (ahead < cycle / 2 ? ahead : ahead - cycle)) * SALT_WINDOW).toISOString().slice(0, 16);
|
||||||
|
return own === undefined ? salt : `${salt} ${own}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The code's info_hash.
|
// What secrets in src/core.ts derives from the code and own salt for info, PBKDF2 once per pair.
|
||||||
const swarm = (code: string) => secret(code, 'swarm', 20).toString('latin1');
|
const masters = new Map<string, Buffer>();
|
||||||
|
function secret(code: string, info: string, length: number, own?: string) {
|
||||||
|
const salt = saltOf(code, own);
|
||||||
|
const pair = JSON.stringify([code, salt]);
|
||||||
|
if (!masters.has(pair)) masters.set(pair, pbkdf2Sync(code, `hellcon ${salt}`, 600_000, 32, 'sha256'));
|
||||||
|
return Buffer.from(hkdfSync('sha256', masters.get(pair)!, '', info, length));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The info_hash of the code with the own salt, if any.
|
||||||
|
const swarm = (code: string, own?: string) => secret(code, 'swarm', 20, own).toString('latin1');
|
||||||
|
|
||||||
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code.
|
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code.
|
||||||
function seal(code: string, type: 'offer' | 'answer', sdp: string) {
|
function seal(code: string, type: 'offer' | 'answer', sdp: string) {
|
||||||
@@ -1610,14 +1779,11 @@ const garbageOffer = (code?: string) =>
|
|||||||
|
|
||||||
const NO_PUBLIC = 'has no public address, between different networks both sides need STUN';
|
const NO_PUBLIC = 'has no public address, between different networks both sides need STUN';
|
||||||
|
|
||||||
// A sender and a receiver as if on different networks, with the servers open and the clock installed.
|
// A sender and a receiver as if on different networks, with the servers open.
|
||||||
// Only the sender has a public address, from the fake STUN server, it answers nobody though.
|
// Only the sender has a public address, from the fake STUN server, it answers nobody though.
|
||||||
async function apart(name: string) {
|
async function apart(name: string) {
|
||||||
const pages = await Promise.all([open(name, { init: dropHosts }), open(name, { init: dropHosts })]);
|
const pages = await Promise.all([open(name, { init: dropHosts }), open(name, { init: dropHosts })]);
|
||||||
for (const page of pages) {
|
for (const page of pages) await page.click('#servers summary');
|
||||||
await page.clock.install();
|
|
||||||
await page.click('#servers summary');
|
|
||||||
}
|
|
||||||
await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`);
|
await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`);
|
||||||
await pages[1]!.uncheck('#stun');
|
await pages[1]!.uncheck('#stun');
|
||||||
return pages as [Page, Page];
|
return pages as [Page, Page];
|
||||||
@@ -1685,15 +1851,14 @@ function holdDecrypts() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry.
|
// Init script: window.deadlines() counts the core's pending expiry timers, see deadline in
|
||||||
// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own
|
// src/core.ts. It runs in the hidden frames too, only the app's own window counts.
|
||||||
// window counts.
|
|
||||||
function countDeadlines() {
|
function countDeadlines() {
|
||||||
if (window !== window.top) return;
|
if (window !== window.top) return;
|
||||||
const pending = new Set<number>();
|
const pending = new Set<number>();
|
||||||
const { setTimeout: set, clearTimeout: clear } = window;
|
const { setTimeout: set, clearTimeout: clear } = window;
|
||||||
window.setTimeout = ((handler: () => void, ms?: number) => {
|
window.setTimeout = ((handler: () => void, ms?: number) => {
|
||||||
if (ms !== 6 * 60_000 || !new Error().stack?.includes('/src/core.ts')) return set(handler, ms);
|
if (!/\bdeadline\b.*\/src\/core\.ts/.test(new Error().stack ?? '')) return set(handler, ms);
|
||||||
const id = set(() => {
|
const id = set(() => {
|
||||||
pending.delete(id);
|
pending.delete(id);
|
||||||
handler();
|
handler();
|
||||||
|
|||||||
Generated
+5
-5
@@ -571,8 +571,8 @@ packages:
|
|||||||
engines: {node: '>=20'}
|
engines: {node: '>=20'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
postcss@8.5.31:
|
postcss@8.5.32:
|
||||||
resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==}
|
resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
|
||||||
engines: {node: ^10 || ^12 || >=14}
|
engines: {node: ^10 || ^12 || >=14}
|
||||||
|
|
||||||
rolldown@1.2.15:
|
rolldown@1.2.15:
|
||||||
@@ -819,7 +819,7 @@ snapshots:
|
|||||||
'@vue/shared': 3.5.44
|
'@vue/shared': 3.5.44
|
||||||
estree-walker: 2.0.2
|
estree-walker: 2.0.2
|
||||||
magic-string: 0.30.21
|
magic-string: 0.30.21
|
||||||
postcss: 8.5.31
|
postcss: 8.5.32
|
||||||
source-map-js: 1.2.2
|
source-map-js: 1.2.2
|
||||||
|
|
||||||
'@vue/compiler-ssr@3.5.44':
|
'@vue/compiler-ssr@3.5.44':
|
||||||
@@ -947,7 +947,7 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
playwright-core: 1.64.1
|
playwright-core: 1.64.1
|
||||||
|
|
||||||
postcss@8.5.31:
|
postcss@8.5.32:
|
||||||
dependencies:
|
dependencies:
|
||||||
nanoid: 3.3.20
|
nanoid: 3.3.20
|
||||||
picocolors: 1.1.1
|
picocolors: 1.1.1
|
||||||
@@ -989,7 +989,7 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
postcss: 8.5.31
|
postcss: 8.5.32
|
||||||
rolldown: 1.2.15
|
rolldown: 1.2.15
|
||||||
tinyglobby: 0.2.17
|
tinyglobby: 0.2.17
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
|
|||||||
+73
-42
@@ -8,36 +8,27 @@ import {
|
|||||||
DEFAULT_STUN_SERVERS,
|
DEFAULT_STUN_SERVERS,
|
||||||
DEFAULT_TRACKERS,
|
DEFAULT_TRACKERS,
|
||||||
type Events,
|
type Events,
|
||||||
|
formatTime,
|
||||||
type Incoming,
|
type Incoming,
|
||||||
type Phase,
|
type Phase,
|
||||||
type ReceiveEvents,
|
type ReceiveEvents,
|
||||||
|
randomCode,
|
||||||
receiveViaTracker,
|
receiveViaTracker,
|
||||||
|
type SendEvents,
|
||||||
sendViaTracker,
|
sendViaTracker,
|
||||||
TRACKER_WAIT,
|
|
||||||
} from './core';
|
} from './core';
|
||||||
|
|
||||||
const SETTINGS_KEY = 'hellcon:settings';
|
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
|
||||||
|
// defaults.
|
||||||
// Same object as the core's, so the core sees every change.
|
|
||||||
const settings = reactive(coreSettings);
|
const settings = reactive(coreSettings);
|
||||||
|
|
||||||
// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay.
|
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
|
||||||
try {
|
const ownSalt = reactive({ on: false, text: '' });
|
||||||
const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}');
|
// Empty is no salt, Share and Receive wait for one.
|
||||||
if (typeof saved.stun === 'boolean') settings.stun = saved.stun;
|
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
|
||||||
if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers;
|
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
|
||||||
if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers;
|
// From the code's alphabet, 16 characters are about 95 bits.
|
||||||
} catch {}
|
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
|
||||||
|
|
||||||
watch(
|
|
||||||
settings,
|
|
||||||
() => {
|
|
||||||
try {
|
|
||||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
|
||||||
} catch {}
|
|
||||||
},
|
|
||||||
{ deep: true },
|
|
||||||
);
|
|
||||||
|
|
||||||
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
|
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
|
||||||
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
|
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
|
||||||
@@ -69,7 +60,7 @@ function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boo
|
|||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
);
|
);
|
||||||
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
|
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
|
||||||
// Immediate, a saved list may hold lines this browser rejects.
|
// Immediate, a default may be a line this browser rejects.
|
||||||
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
|
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
|
||||||
// Unwraps both refs, so the template can bind them as plain properties.
|
// Unwraps both refs, so the template can bind them as plain properties.
|
||||||
return reactive({ text, invalid });
|
return reactive({ text, invalid });
|
||||||
@@ -89,10 +80,10 @@ const shared = ref<File>();
|
|||||||
const offer = ref('');
|
const offer = ref('');
|
||||||
const answerInput = ref('');
|
const answerInput = ref('');
|
||||||
const sendCode = ref('');
|
const sendCode = ref('');
|
||||||
// Until when a receiver can find the share with its code, the time shown and whether it passed.
|
// Until when a receiver can find the share with its code, whether with an own salt and whether that
|
||||||
const sendUntil = ref('');
|
// passed, as the core tells.
|
||||||
|
const sendUntil = ref(0);
|
||||||
const sendExpired = ref(false);
|
const sendExpired = ref(false);
|
||||||
let sendTimer: number | undefined;
|
|
||||||
|
|
||||||
const offerInput = ref('');
|
const offerInput = ref('');
|
||||||
const answer = ref('');
|
const answer = ref('');
|
||||||
@@ -126,7 +117,11 @@ const events: Omit<Events, 'progress'> = {
|
|||||||
type Progress = { read: number; size: number };
|
type Progress = { read: number; size: number };
|
||||||
|
|
||||||
const sent = ref<Progress>();
|
const sent = ref<Progress>();
|
||||||
const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) };
|
const sendEvents: SendEvents = {
|
||||||
|
...events,
|
||||||
|
progress: (read, size) => (sent.value = { read, size }),
|
||||||
|
expired: () => (sendExpired.value = true),
|
||||||
|
};
|
||||||
|
|
||||||
const incoming = ref<Incoming>();
|
const incoming = ref<Incoming>();
|
||||||
const received = ref<Progress>();
|
const received = ref<Progress>();
|
||||||
@@ -186,12 +181,15 @@ let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
|||||||
// the one before: its connections close and what it showed goes, so nothing else can write here.
|
// the one before: its connections close and what it showed goes, so nothing else can write here.
|
||||||
let session: AbortController | undefined;
|
let session: AbortController | undefined;
|
||||||
const side = ref<'send' | 'receive'>();
|
const side = ref<'send' | 'receive'>();
|
||||||
|
// Whether the session is a tracker share or search, which runs with the salt it started with.
|
||||||
|
const viaTracker = ref(false);
|
||||||
|
|
||||||
// what goes into the log, so the sessions in it can be told apart.
|
// what goes into the log, so the sessions in it can be told apart.
|
||||||
function begin(on: 'send' | 'receive', what: string) {
|
function begin(on: 'send' | 'receive', what: string, tracker = false) {
|
||||||
session?.abort();
|
session?.abort();
|
||||||
session = new AbortController();
|
session = new AbortController();
|
||||||
side.value = on;
|
side.value = on;
|
||||||
|
viaTracker.value = tracker;
|
||||||
events.log(`--- ${what} ---`);
|
events.log(`--- ${what} ---`);
|
||||||
error.value = '';
|
error.value = '';
|
||||||
status.value = undefined;
|
status.value = undefined;
|
||||||
@@ -202,7 +200,6 @@ function begin(on: 'send' | 'receive', what: string) {
|
|||||||
received.value = undefined;
|
received.value = undefined;
|
||||||
sendCode.value = '';
|
sendCode.value = '';
|
||||||
sendExpired.value = false;
|
sendExpired.value = false;
|
||||||
clearTimeout(sendTimer);
|
|
||||||
offer.value = '';
|
offer.value = '';
|
||||||
answer.value = '';
|
answer.value = '';
|
||||||
acceptAnswer = undefined;
|
acceptAnswer = undefined;
|
||||||
@@ -238,7 +235,7 @@ function formatSize(bytes: number) {
|
|||||||
bytes /= 1024;
|
bytes /= 1024;
|
||||||
unit++;
|
unit++;
|
||||||
}
|
}
|
||||||
return `${bytes.toFixed(unit ? 1 : 0)} ${units[unit]}`;
|
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateOffer() {
|
async function onCreateOffer() {
|
||||||
@@ -263,13 +260,12 @@ async function onCreateAnswer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onShare() {
|
async function onShare() {
|
||||||
const signal = begin('send', `share ${file.value!.name} via tracker`);
|
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
|
||||||
shared.value = file.value;
|
shared.value = file.value;
|
||||||
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
|
||||||
if (!code) return;
|
if (!result) return;
|
||||||
sendCode.value = code;
|
sendCode.value = result.code;
|
||||||
sendUntil.value = new Date(Date.now() + TRACKER_WAIT).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
sendUntil.value = result.until;
|
||||||
sendTimer = window.setTimeout(() => (sendExpired.value = true), TRACKER_WAIT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
|
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
|
||||||
@@ -277,20 +273,52 @@ async function onShare() {
|
|||||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||||
|
|
||||||
function onReceive() {
|
function onReceive() {
|
||||||
const signal = begin('receive', 'receive via tracker');
|
const signal = begin('receive', 'receive via tracker', true);
|
||||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The salt stays as it is while a tracker share or search runs: it found or waits in the swarm of the
|
||||||
|
// salt it started with, another one shown would be the wrong one to give the receiver.
|
||||||
|
const saltLocked = computed(() => viaTracker.value && !['error', 'done', 'stopped'].includes(phase.value!));
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<header>
|
<header>
|
||||||
|
<div>
|
||||||
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
||||||
<h1>HellCon</h1>
|
<h1>HellCon</h1>
|
||||||
|
</div>
|
||||||
|
<div id="options">
|
||||||
|
<div>
|
||||||
<label>
|
<label>
|
||||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||||
Use STUN
|
Use STUN
|
||||||
</label>
|
</label>
|
||||||
|
<label>
|
||||||
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
|
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
|
||||||
|
Use own salt
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div v-if="ownSalt.on" role="group">
|
||||||
|
<input
|
||||||
|
id="salt"
|
||||||
|
v-model="ownSalt.text"
|
||||||
|
aria-label="Own salt"
|
||||||
|
placeholder="Same salt on both sides"
|
||||||
|
:aria-invalid="saltMissing"
|
||||||
|
:disabled="saltLocked"
|
||||||
|
autocapitalize="off"
|
||||||
|
autocomplete="off"
|
||||||
|
autocorrect="off"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
|
||||||
|
Generate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main>
|
<main>
|
||||||
@@ -340,18 +368,21 @@ function onReceive() {
|
|||||||
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
||||||
<p v-else role="status">
|
<p v-else role="status">
|
||||||
<span id="send-status">{{ status!.text }}</span>
|
<span id="send-status">{{ status!.text }}</span>
|
||||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h3>Tracker</h3>
|
<h3>Tracker</h3>
|
||||||
<button id="share" type="button" :disabled="!file || !settings.trackers.length" @click="onShare">
|
<button id="share" type="button" :disabled="!file || !settings.trackers.length || saltMissing" @click="onShare">
|
||||||
Share via tracker
|
Share via tracker
|
||||||
</button>
|
</button>
|
||||||
<template v-if="sendCode">
|
<template v-if="sendCode">
|
||||||
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
|
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
|
||||||
<label v-else for="send-code">Code, give this to the receiver, valid until {{ sendUntil }}:</label>
|
<label v-else for="send-code">
|
||||||
|
Code, give this {{ ownSalt.on ? 'and your salt ' : '' }}to the receiver, valid until
|
||||||
|
{{ formatTime(sendUntil) }}:
|
||||||
|
</label>
|
||||||
<div role="group">
|
<div role="group">
|
||||||
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
||||||
<button
|
<button
|
||||||
@@ -410,7 +441,7 @@ function onReceive() {
|
|||||||
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
||||||
<p v-else role="status">
|
<p v-else role="status">
|
||||||
<span id="receive-status">{{ status!.text }}</span>
|
<span id="receive-status">{{ status!.text }}</span>
|
||||||
<span v-if="received">{{ percent(received) }} %</span>
|
<span v-if="received">{{ percent(received) }} %</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -429,7 +460,7 @@ function onReceive() {
|
|||||||
<button
|
<button
|
||||||
id="receive"
|
id="receive"
|
||||||
type="button"
|
type="button"
|
||||||
:disabled="!settings.trackers.length || !receiveCode.trim()"
|
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
|
||||||
@click="onReceive"
|
@click="onReceive"
|
||||||
>
|
>
|
||||||
Receive
|
Receive
|
||||||
|
|||||||
+108
-39
@@ -82,6 +82,12 @@ export type Events = {
|
|||||||
progress: (read: number, size: number) => void;
|
progress: (read: number, size: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type SendEvents = Events & {
|
||||||
|
// Once a tracker share's TRACKER_WAIT passed: no further receiver finds it with the code. One
|
||||||
|
// connected by then still gets its turn.
|
||||||
|
expired: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
// The sender's file, offered once both sides confirmed the check. download() starts saving it.
|
// 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 Incoming = { name: string; size: number; download: () => void };
|
||||||
|
|
||||||
@@ -257,30 +263,78 @@ function randomBinary(length: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||||
|
// The largest multiple of the alphabet's length a byte holds. The bytes above would make the first
|
||||||
|
// characters likelier, they are dropped.
|
||||||
|
const CODE_LIMIT = 256 - (256 % CODE_CHARS.length);
|
||||||
|
|
||||||
// 10 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
|
// length of the 62 characters, each equally likely.
|
||||||
function randomCode() {
|
export function randomCode(length: number) {
|
||||||
let code = '';
|
let code = '';
|
||||||
while (code.length < 10)
|
while (code.length < length)
|
||||||
for (const byte of crypto.getRandomValues(new Uint8Array(10)))
|
for (const byte of crypto.getRandomValues(new Uint8Array(length)))
|
||||||
if (byte < 248 && code.length < 10) code += CODE_CHARS[byte % 62];
|
if (byte < CODE_LIMIT && code.length < length) code += CODE_CHARS[byte % CODE_CHARS.length];
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The code is all both sides share. It gives the tracker swarm, identified by a 20 byte info_hash,
|
// Hours and minutes, the way the user's browser writes them. The time and an AM or PM keep together.
|
||||||
// and the key that proves the connection, see prove. Whoever sees the swarms, a tracker or anyone
|
export const formatTime = (time: number) =>
|
||||||
// scraping one, can test a guessed code against all of them at once. PBKDF2 makes every guess cost
|
new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0');
|
||||||
// what a share pays once (~50 ms). The salt is fixed, both sides only know the code, so the guesses
|
|
||||||
// can also be made ahead of time, once for every share: a table from info_hash to code would let a
|
// Tracker signaling salts with the clock: its windows of SALT_WINDOW, counted in UTC from 1970. The
|
||||||
// tracker take over any share as it happens. Only the code's length prices that: for 62¹⁰ codes
|
// last of a code's CODE_LENGTH characters is the window it was made in, mod the number of characters,
|
||||||
// it's over a million GPU years. Any length derives the same way, an older client takes a longer
|
// so the same one comes back every ~6 hours. The receiver takes the window with that character nearest
|
||||||
// code. HKDF splits the result, the public info_hash tells nothing about the keys: one seals the
|
// its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts
|
||||||
// signaling, see seal, one proves the connection.
|
// TRACKER_WAIT from the click whenever in its window that was.
|
||||||
async function secrets(code: string) {
|
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
|
||||||
|
const SALT_WINDOW = 6 * 60_000;
|
||||||
|
const CODE_LENGTH = 11;
|
||||||
|
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
|
||||||
|
|
||||||
|
// The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo,
|
||||||
|
// not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share.
|
||||||
|
function trackerSalt(at: number, own?: string) {
|
||||||
|
const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16);
|
||||||
|
if (own === undefined) return salt;
|
||||||
|
if (!own.trim()) throw new Error('the own salt is empty');
|
||||||
|
return `${salt} ${own.trim()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A sender's new code and its salt.
|
||||||
|
function newCode(own?: string) {
|
||||||
|
const at = clockWindow(Date.now());
|
||||||
|
return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The salt of the code a receiver got, its window from half the characters before the clock's to half
|
||||||
|
// after. Anything else can't be a code, a typo gets told right away instead of searched for.
|
||||||
|
function codeSalt(code: string, own?: string) {
|
||||||
|
if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char)))
|
||||||
|
throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`);
|
||||||
|
const now = clockWindow(Date.now());
|
||||||
|
const cycle = CODE_CHARS.length;
|
||||||
|
const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle;
|
||||||
|
return trackerSalt(now + (ahead < cycle / 2 ? ahead : ahead - cycle), own);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The code and the salt are all both sides share. They give the tracker swarm, identified by a 20
|
||||||
|
// byte info_hash, and the key that proves the connection, see prove. Whoever sees the swarms, a
|
||||||
|
// tracker or anyone scraping one, can test a guessed code against all of them at once. PBKDF2 makes
|
||||||
|
// every guess cost what a share pays once (~50 ms). A salt known ahead lets the guesses be made ahead
|
||||||
|
// too: a table from info_hash to code would let a tracker take over any share as it happens. The
|
||||||
|
// clock's salt limits a table to the shares of one window, for 62¹⁰ codes it takes over a million GPU
|
||||||
|
// years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one
|
||||||
|
// system can be other bytes than on the next. HKDF splits the result, the public info_hash tells
|
||||||
|
// nothing about the keys: one seals the signaling, see seal, one proves the connection.
|
||||||
|
async function secrets(code: string, salt: string) {
|
||||||
const text = new TextEncoder();
|
const text = new TextEncoder();
|
||||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||||
const bits = await crypto.subtle.deriveBits(
|
const bits = await crypto.subtle.deriveBits(
|
||||||
{ name: 'PBKDF2', hash: 'SHA-256', salt: text.encode('hellcon'), iterations: PBKDF2_ITERATIONS },
|
{
|
||||||
|
name: 'PBKDF2',
|
||||||
|
hash: 'SHA-256',
|
||||||
|
salt: text.encode(`hellcon ${salt.normalize('NFC')}`),
|
||||||
|
iterations: PBKDF2_ITERATIONS,
|
||||||
|
},
|
||||||
password,
|
password,
|
||||||
256,
|
256,
|
||||||
);
|
);
|
||||||
@@ -892,23 +946,21 @@ function trackerSocket(
|
|||||||
lost: () => void,
|
lost: () => void,
|
||||||
again: () => void,
|
again: () => void,
|
||||||
) {
|
) {
|
||||||
const ws = own(signal, new WebSocket(url));
|
const ws = new WebSocket(url);
|
||||||
let opened = false;
|
let opened = false;
|
||||||
let accepted = false;
|
let accepted = false;
|
||||||
let closed = false;
|
let closed = false;
|
||||||
let reannounce: ReturnType<typeof setInterval> | undefined;
|
let reannounce: ReturnType<typeof setInterval> | undefined;
|
||||||
const end = (reason: string) => {
|
const end = (reason: string) => {
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
closed = true;
|
|
||||||
clearTimeout(timeout);
|
|
||||||
clearInterval(reannounce);
|
|
||||||
// Already closed unless rejected or silent, this only lets go of it.
|
// Already closed unless rejected or silent, this only lets go of it.
|
||||||
ws.close();
|
tracker.close();
|
||||||
events.log(reason);
|
events.log(reason);
|
||||||
lost();
|
lost();
|
||||||
};
|
};
|
||||||
const timeout = setTimeout(() => end(opened ? `${url} did not answer` : `${url} unreachable`), TRACKER_TIMEOUT);
|
const timeout = setTimeout(() => end(opened ? `${url} did not answer` : `${url} unreachable`), TRACKER_TIMEOUT);
|
||||||
const tracker = {
|
// The session owns the timers too: a socket still closing after the abort gets no announce.
|
||||||
|
const tracker = own(signal, {
|
||||||
ws,
|
ws,
|
||||||
// What the tracker answered, if it rejected the announcement.
|
// What the tracker answered, if it rejected the announcement.
|
||||||
rejected: undefined as string | undefined,
|
rejected: undefined as string | undefined,
|
||||||
@@ -920,7 +972,7 @@ function trackerSocket(
|
|||||||
clearInterval(reannounce);
|
clearInterval(reannounce);
|
||||||
ws.close();
|
ws.close();
|
||||||
},
|
},
|
||||||
};
|
});
|
||||||
ws.addEventListener('open', () => (opened = true));
|
ws.addEventListener('open', () => (opened = true));
|
||||||
ws.addEventListener('message', ({ data }) => {
|
ws.addEventListener('message', ({ data }) => {
|
||||||
const msg = parse(data);
|
const msg = parse(data);
|
||||||
@@ -958,12 +1010,13 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
|||||||
// it doesn't even learn the sender's address. Until a receiver proved the code, the next one gets its
|
// it doesn't even learn the sender's address. Until a receiver proved the code, the next one gets its
|
||||||
// turn: an offer that can't be answered, never connects or proves nothing doesn't end the share. Once
|
// turn: an offer that can't be answered, never connects or proves nothing doesn't end the share. Once
|
||||||
// the download started the share is used up, the tracker goes. After TRACKER_WAIT it goes as well, a
|
// the download started the share is used up, the tracker goes. After TRACKER_WAIT it goes as well, a
|
||||||
// receiver connected by then still gets its turn.
|
// receiver connected by then still gets its turn. Resolves with the code and when it ends.
|
||||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
export async function sendViaTracker(file: File, events: SendEvents, signal: AbortSignal, ownSalt?: string) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
events.status('start', 'Creating the code');
|
events.status('start', 'Creating the code');
|
||||||
const code = randomCode();
|
const until = Date.now() + TRACKER_WAIT;
|
||||||
const { hash, key, sealing } = await secrets(code);
|
const { code, salt } = newCode(ownSalt);
|
||||||
|
const { hash, key, sealing } = await secrets(code, salt);
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
const urls = [...settings.trackers];
|
const urls = [...settings.trackers];
|
||||||
// Every one tried so far, only the last can be alive.
|
// Every one tried so far, only the last can be alive.
|
||||||
@@ -989,13 +1042,18 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||||
const nobody = () =>
|
const nobody = () =>
|
||||||
hint
|
hint
|
||||||
? `no receiver connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
? `no receiver connected until ${formatTime(until)}: ${hint}`
|
||||||
: `nobody received the file within ${TRACKER_WAIT / 60_000} minutes, share it again`;
|
: `nobody received the file until ${formatTime(until)}, share it again`;
|
||||||
const expiry = deadline(signal, () => {
|
const expiry = deadline(
|
||||||
|
signal,
|
||||||
|
() => {
|
||||||
expired = true;
|
expired = true;
|
||||||
|
events.expired();
|
||||||
for (const tracker of trackers) tracker.close();
|
for (const tracker of trackers) tracker.close();
|
||||||
if (stranded()) events.error(nobody());
|
if (stranded()) events.error(nobody());
|
||||||
});
|
},
|
||||||
|
until - Date.now(),
|
||||||
|
);
|
||||||
// Once stranded the share is over.
|
// Once stranded the share is over.
|
||||||
const end = (reason: string) => {
|
const end = (reason: string) => {
|
||||||
expiry.close();
|
expiry.close();
|
||||||
@@ -1117,7 +1175,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
}
|
}
|
||||||
|
|
||||||
join(0);
|
join(0);
|
||||||
return code;
|
return { code, until };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Receiver walks the trackers in order with one offer each, until one has a seeder: the sender, which
|
// Receiver walks the trackers in order with one offer each, until one has a seeder: the sender, which
|
||||||
@@ -1128,11 +1186,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
// the code is ignored, the offer waits for the real one. One that can't be used or never connects is
|
// the code is ignored, the offer waits for the real one. One that can't be used or never connects is
|
||||||
// replaced right away. Once the download started, every other offer and tracker socket goes. After
|
// replaced right away. Once the download started, every other offer and tracker socket goes. After
|
||||||
// TRACKER_WAIT no offer is made or kept any more, a sender connected by then still gets its turn.
|
// TRACKER_WAIT no offer is made or kept any more, a sender connected by then still gets its turn.
|
||||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal, ownSalt?: string) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
events.status('start', 'Looking for the sender');
|
events.status('start', 'Looking for the sender');
|
||||||
|
// From the click, getting ready may take a moment.
|
||||||
|
const salt = codeSalt(code.trim(), ownSalt);
|
||||||
|
const until = Date.now() + TRACKER_WAIT;
|
||||||
await downloadsReady();
|
await downloadsReady();
|
||||||
const { hash, key, sealing } = await secrets(code.trim());
|
const { hash, key, sealing } = await secrets(code.trim(), salt);
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
const urls = [...settings.trackers];
|
const urls = [...settings.trackers];
|
||||||
@@ -1158,10 +1219,11 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
else events.status('start', text);
|
else events.status('start', text);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// No sender with this code can come after the end, a new code can.
|
||||||
const nobody = () =>
|
const nobody = () =>
|
||||||
hint
|
hint
|
||||||
? `no sender connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
? `no sender connected until ${formatTime(until)}: ${hint}`
|
||||||
: `no sender answered within ${TRACKER_WAIT / 60_000} minutes, check the code and try again`;
|
: `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`;
|
||||||
// Without a sender connected the search is over, every offer goes.
|
// Without a sender connected the search is over, every offer goes.
|
||||||
const end = (reason: string) => {
|
const end = (reason: string) => {
|
||||||
expiry.close();
|
expiry.close();
|
||||||
@@ -1172,11 +1234,15 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
events.error(reason);
|
events.error(reason);
|
||||||
};
|
};
|
||||||
// A connected sender keeps its connection, the other offers wait for next or start.
|
// A connected sender keeps its connection, the other offers wait for next or start.
|
||||||
const expiry = deadline(signal, () => {
|
const expiry = deadline(
|
||||||
|
signal,
|
||||||
|
() => {
|
||||||
expired = true;
|
expired = true;
|
||||||
if (!isConnected) return end(nobody());
|
if (!isConnected) return end(nobody());
|
||||||
for (const { tracker } of offers.values()) tracker?.close();
|
for (const { tracker } of offers.values()) tracker?.close();
|
||||||
});
|
},
|
||||||
|
until - Date.now(),
|
||||||
|
);
|
||||||
|
|
||||||
const next = (reason: string) => {
|
const next = (reason: string) => {
|
||||||
isConnected = false;
|
isConnected = false;
|
||||||
@@ -1269,7 +1335,10 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
const none = offers.size === urls.length && everywhere;
|
const none = offers.size === urls.length && everywhere;
|
||||||
if (none !== noSender && !isConnected && !started) {
|
if (none !== noSender && !isConnected && !started) {
|
||||||
if (none)
|
if (none)
|
||||||
events.status('retry', 'No sender with this code on any tracker. Check the code, still looking');
|
events.status(
|
||||||
|
'retry',
|
||||||
|
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'}, still looking`,
|
||||||
|
);
|
||||||
else if (failure) events.status('retry', `${failure}. Looking again`);
|
else if (failure) events.status('retry', `${failure}. Looking again`);
|
||||||
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-4
@@ -113,19 +113,38 @@ footer {
|
|||||||
padding-inline: var(--space-4);
|
padding-inline: var(--space-4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
|
||||||
header {
|
header {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding-block: var(--space-6) var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
header > div:first-child {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: var(--space-3);
|
gap: var(--space-3);
|
||||||
padding-block: var(--space-6);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
header h1 {
|
header h1 {
|
||||||
font-size: var(--text-xl);
|
font-size: var(--text-xl);
|
||||||
}
|
}
|
||||||
|
|
||||||
header label {
|
/* The switches at the end, the own salt below while it's on */
|
||||||
margin-left: auto;
|
#options {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#options > div:first-child {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: end;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
main {
|
||||||
@@ -219,6 +238,17 @@ textarea:focus {
|
|||||||
border-color: var(--color-secondary);
|
border-color: var(--color-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Like a disabled button, the switch with its label */
|
||||||
|
input:not([role='switch']):disabled,
|
||||||
|
label:has([role='switch']:disabled) {
|
||||||
|
opacity: 0.4;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
label:has([role='switch']:disabled) [role='switch'] {
|
||||||
|
cursor: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||||
input:not([type='checkbox'], [type='file']):focus-visible,
|
input:not([type='checkbox'], [type='file']):focus-visible,
|
||||||
textarea:focus-visible {
|
textarea:focus-visible {
|
||||||
@@ -292,7 +322,7 @@ button:disabled {
|
|||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Copy buttons, secondary next to the value they copy */
|
/* Copy and Generate, secondary next to the value they are for */
|
||||||
|
|
||||||
[data-copy] {
|
[data-copy] {
|
||||||
padding: var(--space-1) var(--space-3);
|
padding: var(--space-1) var(--space-3);
|
||||||
|
|||||||
Reference in new issue
Block a user