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
+462
-142
No files matched your search
+80
-49
@@ -8,36 +8,27 @@ import {
|
||||
DEFAULT_STUN_SERVERS,
|
||||
DEFAULT_TRACKERS,
|
||||
type Events,
|
||||
formatTime,
|
||||
type Incoming,
|
||||
type Phase,
|
||||
type ReceiveEvents,
|
||||
randomCode,
|
||||
receiveViaTracker,
|
||||
type SendEvents,
|
||||
sendViaTracker,
|
||||
TRACKER_WAIT,
|
||||
} from './core';
|
||||
|
||||
const SETTINGS_KEY = 'hellcon:settings';
|
||||
|
||||
// Same object as the core's, so the core sees every change.
|
||||
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
|
||||
// defaults.
|
||||
const settings = reactive(coreSettings);
|
||||
|
||||
// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay.
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}');
|
||||
if (typeof saved.stun === 'boolean') settings.stun = saved.stun;
|
||||
if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers;
|
||||
if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers;
|
||||
} catch {}
|
||||
|
||||
watch(
|
||||
settings,
|
||||
() => {
|
||||
try {
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||
} catch {}
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
|
||||
const ownSalt = reactive({ on: false, text: '' });
|
||||
// Empty is no salt, Share and Receive wait for one.
|
||||
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
|
||||
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
|
||||
// From the code's alphabet, 16 characters are about 95 bits.
|
||||
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
|
||||
|
||||
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
|
||||
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
|
||||
@@ -69,7 +60,7 @@ function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boo
|
||||
.filter(Boolean),
|
||||
);
|
||||
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 });
|
||||
// Unwraps both refs, so the template can bind them as plain properties.
|
||||
return reactive({ text, invalid });
|
||||
@@ -89,10 +80,10 @@ const shared = ref<File>();
|
||||
const offer = ref('');
|
||||
const answerInput = ref('');
|
||||
const sendCode = ref('');
|
||||
// Until when a receiver can find the share with its code, the time shown and whether it passed.
|
||||
const sendUntil = ref('');
|
||||
// Until when a receiver can find the share with its code, whether with an own salt and whether that
|
||||
// passed, as the core tells.
|
||||
const sendUntil = ref(0);
|
||||
const sendExpired = ref(false);
|
||||
let sendTimer: number | undefined;
|
||||
|
||||
const offerInput = ref('');
|
||||
const answer = ref('');
|
||||
@@ -126,7 +117,11 @@ const events: Omit<Events, 'progress'> = {
|
||||
type Progress = { read: number; size: number };
|
||||
|
||||
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 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.
|
||||
let session: AbortController | undefined;
|
||||
const side = ref<'send' | 'receive'>();
|
||||
// Whether the session is a tracker share or search, which runs with the salt it started with.
|
||||
const viaTracker = ref(false);
|
||||
|
||||
// what goes into the log, so the sessions in it can be told apart.
|
||||
function begin(on: 'send' | 'receive', what: string) {
|
||||
function begin(on: 'send' | 'receive', what: string, tracker = false) {
|
||||
session?.abort();
|
||||
session = new AbortController();
|
||||
side.value = on;
|
||||
viaTracker.value = tracker;
|
||||
events.log(`--- ${what} ---`);
|
||||
error.value = '';
|
||||
status.value = undefined;
|
||||
@@ -202,7 +200,6 @@ function begin(on: 'send' | 'receive', what: string) {
|
||||
received.value = undefined;
|
||||
sendCode.value = '';
|
||||
sendExpired.value = false;
|
||||
clearTimeout(sendTimer);
|
||||
offer.value = '';
|
||||
answer.value = '';
|
||||
acceptAnswer = undefined;
|
||||
@@ -238,7 +235,7 @@ function formatSize(bytes: number) {
|
||||
bytes /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${bytes.toFixed(unit ? 1 : 0)} ${units[unit]}`;
|
||||
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
|
||||
}
|
||||
|
||||
async function onCreateOffer() {
|
||||
@@ -263,13 +260,12 @@ async function onCreateAnswer() {
|
||||
}
|
||||
|
||||
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;
|
||||
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
||||
if (!code) return;
|
||||
sendCode.value = code;
|
||||
sendUntil.value = new Date(Date.now() + TRACKER_WAIT).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
sendTimer = window.setTimeout(() => (sendExpired.value = true), TRACKER_WAIT);
|
||||
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
|
||||
if (!result) return;
|
||||
sendCode.value = result.code;
|
||||
sendUntil.value = result.until;
|
||||
}
|
||||
|
||||
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
|
||||
@@ -277,20 +273,52 @@ async function onShare() {
|
||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||
|
||||
function onReceive() {
|
||||
const signal = begin('receive', 'receive via tracker');
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
||||
const signal = begin('receive', 'receive via tracker', true);
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
|
||||
}
|
||||
|
||||
// The salt stays as it is while a tracker share 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>
|
||||
|
||||
<template>
|
||||
<header>
|
||||
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
||||
<h1>HellCon</h1>
|
||||
<label>
|
||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||
Use STUN
|
||||
</label>
|
||||
<div>
|
||||
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
||||
<h1>HellCon</h1>
|
||||
</div>
|
||||
<div id="options">
|
||||
<div>
|
||||
<label>
|
||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||
Use STUN
|
||||
</label>
|
||||
<label>
|
||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
|
||||
Use own salt
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="ownSalt.on" role="group">
|
||||
<input
|
||||
id="salt"
|
||||
v-model="ownSalt.text"
|
||||
aria-label="Own salt"
|
||||
placeholder="Same salt on both sides"
|
||||
:aria-invalid="saltMissing"
|
||||
:disabled="saltLocked"
|
||||
autocapitalize="off"
|
||||
autocomplete="off"
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
|
||||
Generate
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
@@ -340,18 +368,21 @@ function onReceive() {
|
||||
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="send-status">{{ status!.text }}</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<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
|
||||
</button>
|
||||
<template v-if="sendCode">
|
||||
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
|
||||
<label v-else for="send-code">Code, give this 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">
|
||||
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
||||
<button
|
||||
@@ -410,7 +441,7 @@ function onReceive() {
|
||||
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="receive-status">{{ status!.text }}</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -429,7 +460,7 @@ function onReceive() {
|
||||
<button
|
||||
id="receive"
|
||||
type="button"
|
||||
:disabled="!settings.trackers.length || !receiveCode.trim()"
|
||||
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
|
||||
@click="onReceive"
|
||||
>
|
||||
Receive
|
||||
|
||||
+114
-45
@@ -82,6 +82,12 @@ export type Events = {
|
||||
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.
|
||||
export type Incoming = { name: string; size: number; download: () => void };
|
||||
|
||||
@@ -257,30 +263,78 @@ function randomBinary(length: number) {
|
||||
}
|
||||
|
||||
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.
|
||||
function randomCode() {
|
||||
// length of the 62 characters, each equally likely.
|
||||
export function randomCode(length: number) {
|
||||
let code = '';
|
||||
while (code.length < 10)
|
||||
for (const byte of crypto.getRandomValues(new Uint8Array(10)))
|
||||
if (byte < 248 && code.length < 10) code += CODE_CHARS[byte % 62];
|
||||
while (code.length < length)
|
||||
for (const byte of crypto.getRandomValues(new Uint8Array(length)))
|
||||
if (byte < CODE_LIMIT && code.length < length) code += CODE_CHARS[byte % CODE_CHARS.length];
|
||||
return code;
|
||||
}
|
||||
|
||||
// The code is all both sides share. It gives 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). 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 take over any share as it happens. Only the code's length prices that: for 62¹⁰ codes
|
||||
// it's over a million GPU years. Any length derives the same way, an older client takes a longer
|
||||
// code. HKDF splits the result, the public info_hash tells nothing about the keys: one seals the
|
||||
// signaling, see seal, one proves the connection.
|
||||
async function secrets(code: string) {
|
||||
// Hours and minutes, the way the user's browser writes them. The time and an AM or PM keep together.
|
||||
export const formatTime = (time: number) =>
|
||||
new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0');
|
||||
|
||||
// Tracker signaling salts with the clock: its windows of SALT_WINDOW, counted in UTC from 1970. The
|
||||
// last of a code's CODE_LENGTH characters is the window it was made in, mod the number of characters,
|
||||
// so the same one comes back every ~6 hours. The receiver takes the window with that character nearest
|
||||
// its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts
|
||||
// TRACKER_WAIT from the click whenever in its window that was.
|
||||
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
|
||||
const SALT_WINDOW = 6 * 60_000;
|
||||
const CODE_LENGTH = 11;
|
||||
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 password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', hash: 'SHA-256', salt: text.encode('hellcon'), iterations: PBKDF2_ITERATIONS },
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
hash: 'SHA-256',
|
||||
salt: text.encode(`hellcon ${salt.normalize('NFC')}`),
|
||||
iterations: PBKDF2_ITERATIONS,
|
||||
},
|
||||
password,
|
||||
256,
|
||||
);
|
||||
@@ -892,23 +946,21 @@ function trackerSocket(
|
||||
lost: () => void,
|
||||
again: () => void,
|
||||
) {
|
||||
const ws = own(signal, new WebSocket(url));
|
||||
const ws = new WebSocket(url);
|
||||
let opened = false;
|
||||
let accepted = false;
|
||||
let closed = false;
|
||||
let reannounce: ReturnType<typeof setInterval> | undefined;
|
||||
const end = (reason: string) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearTimeout(timeout);
|
||||
clearInterval(reannounce);
|
||||
// Already closed unless rejected or silent, this only lets go of it.
|
||||
ws.close();
|
||||
tracker.close();
|
||||
events.log(reason);
|
||||
lost();
|
||||
};
|
||||
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,
|
||||
// What the tracker answered, if it rejected the announcement.
|
||||
rejected: undefined as string | undefined,
|
||||
@@ -920,7 +972,7 @@ function trackerSocket(
|
||||
clearInterval(reannounce);
|
||||
ws.close();
|
||||
},
|
||||
};
|
||||
});
|
||||
ws.addEventListener('open', () => (opened = true));
|
||||
ws.addEventListener('message', ({ 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
|
||||
// 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
|
||||
// receiver connected by then still gets its turn.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
// receiver connected by then still gets its turn. Resolves with the code and when it ends.
|
||||
export async function sendViaTracker(file: File, events: SendEvents, signal: AbortSignal, ownSalt?: string) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the code');
|
||||
const code = randomCode();
|
||||
const { hash, key, sealing } = await secrets(code);
|
||||
const until = Date.now() + TRACKER_WAIT;
|
||||
const { code, salt } = newCode(ownSalt);
|
||||
const { hash, key, sealing } = await secrets(code, salt);
|
||||
const peerId = randomBinary(20);
|
||||
const urls = [...settings.trackers];
|
||||
// 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 nobody = () =>
|
||||
hint
|
||||
? `no receiver connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
||||
: `nobody received the file within ${TRACKER_WAIT / 60_000} minutes, share it again`;
|
||||
const expiry = deadline(signal, () => {
|
||||
expired = true;
|
||||
for (const tracker of trackers) tracker.close();
|
||||
if (stranded()) events.error(nobody());
|
||||
});
|
||||
? `no receiver connected until ${formatTime(until)}: ${hint}`
|
||||
: `nobody received the file until ${formatTime(until)}, share it again`;
|
||||
const expiry = deadline(
|
||||
signal,
|
||||
() => {
|
||||
expired = true;
|
||||
events.expired();
|
||||
for (const tracker of trackers) tracker.close();
|
||||
if (stranded()) events.error(nobody());
|
||||
},
|
||||
until - Date.now(),
|
||||
);
|
||||
// Once stranded the share is over.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1117,7 +1175,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
}
|
||||
|
||||
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
|
||||
@@ -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
|
||||
// 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.
|
||||
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.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();
|
||||
const { hash, key, sealing } = await secrets(code.trim());
|
||||
const { hash, key, sealing } = await secrets(code.trim(), salt);
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
const urls = [...settings.trackers];
|
||||
@@ -1158,10 +1219,11 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
else events.status('start', text);
|
||||
};
|
||||
|
||||
// No sender with this code can come after the end, a new code can.
|
||||
const nobody = () =>
|
||||
hint
|
||||
? `no sender connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
||||
: `no sender answered within ${TRACKER_WAIT / 60_000} minutes, check the code and try again`;
|
||||
? `no sender connected until ${formatTime(until)}: ${hint}`
|
||||
: `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`;
|
||||
// Without a sender connected the search is over, every offer goes.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1172,11 +1234,15 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
events.error(reason);
|
||||
};
|
||||
// A connected sender keeps its connection, the other offers wait for next or start.
|
||||
const expiry = deadline(signal, () => {
|
||||
expired = true;
|
||||
if (!isConnected) return end(nobody());
|
||||
for (const { tracker } of offers.values()) tracker?.close();
|
||||
});
|
||||
const expiry = deadline(
|
||||
signal,
|
||||
() => {
|
||||
expired = true;
|
||||
if (!isConnected) return end(nobody());
|
||||
for (const { tracker } of offers.values()) tracker?.close();
|
||||
},
|
||||
until - Date.now(),
|
||||
);
|
||||
|
||||
const next = (reason: string) => {
|
||||
isConnected = false;
|
||||
@@ -1269,7 +1335,10 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
const none = offers.size === urls.length && everywhere;
|
||||
if (none !== noSender && !isConnected && !started) {
|
||||
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 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);
|
||||
}
|
||||
|
||||
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
|
||||
header {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
padding-block: var(--space-6) var(--space-4);
|
||||
}
|
||||
|
||||
header > div:first-child {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
padding-block: var(--space-6);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: var(--text-xl);
|
||||
}
|
||||
|
||||
header label {
|
||||
margin-left: auto;
|
||||
/* The switches at the end, the own salt below while it's on */
|
||||
#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 {
|
||||
@@ -219,6 +238,17 @@ textarea:focus {
|
||||
border-color: var(--color-secondary);
|
||||
}
|
||||
|
||||
/* Like a disabled button, the switch with its label */
|
||||
input:not([role='switch']):disabled,
|
||||
label:has([role='switch']:disabled) {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
label:has([role='switch']:disabled) [role='switch'] {
|
||||
cursor: inherit;
|
||||
}
|
||||
|
||||
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||
input:not([type='checkbox'], [type='file']):focus-visible,
|
||||
textarea:focus-visible {
|
||||
@@ -292,7 +322,7 @@ button:disabled {
|
||||
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] {
|
||||
padding: var(--space-1) var(--space-3);
|
||||
|
||||
Reference in new issue
Block a user