Limit what a tracker can make the page do, recommend anti-framing headers

A tracker message over 64 KiB isn't parsed, before acceptance it rejects
the tracker like a failure reason. Beyond 20 messages per 10 s the rest is
dropped, so a tracker can't keep the page parsing and decrypting. What a
tracker makes a socket log goes through one note: each line once, at most
10 per socket. The log keeps the last 1000 lines in a shallow ref and says
how many went.

index.html sets Referrer-Policy itself, the README recommends the headers a
<meta> can't set: frame-ancestors, X-Frame-Options and nosniff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-30 00:29:23 +01:00
1 parent b102e55495
commit 7f4811485a
7 files changed
+151 -31

No files matched your search

+14 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
import {
answerOffer,
type Check,
@@ -91,7 +91,12 @@ const receiveCode = ref('');
const check = ref<Check>();
const confirmed = ref(false);
const log = ref<string[]>([]);
// Changed in place and triggered, a deep ref would make each line cost every line kept.
const log = shallowRef<string[]>([]);
// Lines kept, the oldest go first and dropped counts them. A session logs a few dozen, a tracker or
// peer that sends garbage could add lines until the tab freezes.
const MAX_LOG = 1000;
const dropped = ref(0);
// Of the session, shown in the card of its side.
const error = ref('');
const status = ref<{ phase: Phase; text: string }>();
@@ -100,7 +105,12 @@ const phase = computed(() => (error.value ? 'error' : status.value?.phase));
// Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
log: (message) => {
const lines = log.value;
lines.push(`${new Date().toISOString().slice(11, 23)} ${message}`);
if (lines.length > MAX_LOG) dropped.value += lines.splice(0, lines.length - MAX_LOG).length;
triggerRef(log);
},
error: (message) => {
events.log(message);
error.value = message;
@@ -522,7 +532,7 @@ const saltLocked = computed(
<details>
<summary>Log</summary>
<pre id="log">{{ log.join('\n') }}</pre>
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
</details>
</main>
+78 -6
View File
@@ -21,6 +21,9 @@ import {
live,
MAX_BUFFERED,
MAX_NAME,
MAX_TRACKER_MESSAGE,
MAX_TRACKER_MESSAGES,
MESSAGE_WINDOW,
MIN_INTERVAL,
newCode,
noTracker,
@@ -43,6 +46,7 @@ import {
settings,
stunChoice,
stunHint,
TRACKER_NOTES,
TRACKER_TIMEOUT,
TRACKER_WAIT,
trackerSalt,
@@ -732,7 +736,7 @@ describe('tracker socket', () => {
expect(tracker.ws.readyState).toBeGreaterThanOrEqual(2);
});
it('takes a failure before anything else for a rejection, after that only logs it', async () => {
it('takes a failure before anything else for a rejection, after that only notes it', async () => {
new FakeTracker('wss://one.test', () => ({ 'failure reason': 'not here' }));
const rejected = socket();
await until(() => rejected.tracker.ws.readyState === 1);
@@ -747,13 +751,75 @@ describe('tracker socket', () => {
await until(() => accepted.tracker.ws.readyState === 1);
accepted.tracker.ws.send('{}');
await until(() => accepted.got.length);
(accepted.tracker.ws as unknown as FakeSocket).deliver({ 'failure reason': 'slow down' });
(accepted.tracker.ws as unknown as FakeSocket).deliver({ 'not json': undefined });
expect(accepted.session.logs).toEqual(['wss://two.test: slow down']);
const ws = accepted.tracker.ws as unknown as FakeSocket;
ws.deliver({ 'failure reason': 'x'.repeat(1000) });
ws.deliver({ 'failure reason': 'slow down' });
ws.deliver({ 'not json': undefined });
ws.deliver({ 'failure reason': 'slow down' });
ws.deliver({ 'failure reason': 'shutting down' });
expect(accepted.session.logs).toEqual([
`wss://two.test: ${'x'.repeat(200)}`,
'wss://two.test: slow down',
'wss://two.test: shutting down',
]);
expect(accepted.tracker.alive()).toBe(true);
expect(accepted.lost).not.toHaveBeenCalled();
});
it('takes a message over MAX_TRACKER_MESSAGE first for a rejection, after that only notes and drops it', async () => {
new FakeTracker('wss://one.test', () => undefined);
// msg padded to length characters of JSON.
const sized = (length: number, msg: object) => {
const json = JSON.stringify({ ...msg, pad: '' });
return { ...msg, pad: ' '.repeat(length - json.length) };
};
const rejected = socket();
await until(() => rejected.tracker.ws.readyState === 1);
(rejected.tracker.ws as unknown as FakeSocket).deliver(
sized(MAX_TRACKER_MESSAGE + 1, { 'failure reason': 'not here' }),
);
expect(rejected.tracker.rejected).toBe('wss://one.test: message over 64 KiB');
expect(rejected.session.logs).toEqual(['rejected by wss://one.test: message over 64 KiB']);
expect(rejected.lost).toHaveBeenCalledTimes(1);
const { session, tracker, got, lost } = socket();
await until(() => tracker.ws.readyState === 1);
const ws = tracker.ws as unknown as FakeSocket;
ws.deliver(sized(MAX_TRACKER_MESSAGE, { action: 'announce' }));
ws.deliver(sized(MAX_TRACKER_MESSAGE + 1, { action: 'announce' }));
ws.deliver(sized(MAX_TRACKER_MESSAGE + 1, { action: 'announce' }));
expect(got).toHaveLength(1);
expect(session.logs).toEqual(['wss://one.test: message over 64 KiB']);
expect(lost).not.toHaveBeenCalled();
});
it('drops messages beyond MAX_TRACKER_MESSAGES per MESSAGE_WINDOW', async () => {
new FakeTracker('wss://one.test', () => undefined);
const { session, tracker, got } = socket();
await until(() => tracker.ws.readyState === 1);
const ws = tracker.ws as unknown as FakeSocket;
for (let i = 0; i < MAX_TRACKER_MESSAGES + 5; i++) ws.deliver({ action: 'announce', i });
expect(got.map((msg) => msg.i)).toEqual([...Array(MAX_TRACKER_MESSAGES).keys()]);
expect(session.logs).toEqual(['wss://one.test sends too much, dropping some of it']);
vi.setSystemTime(Date.now() + MESSAGE_WINDOW);
ws.deliver({ action: 'announce', i: 'later' });
expect(got.at(-1).i).toBe('later');
expect(session.logs).toHaveLength(1);
});
it('notes at most TRACKER_NOTES lines', async () => {
new FakeTracker('wss://one.test', () => undefined);
const { session, tracker } = socket();
await until(() => tracker.ws.readyState === 1);
const ws = tracker.ws as unknown as FakeSocket;
ws.deliver({ action: 'announce' });
for (let i = 0; i < TRACKER_NOTES + 5; i++) ws.deliver({ 'failure reason': `reason ${i}` });
expect(session.logs).toEqual([
...[...Array(TRACKER_NOTES).keys()].map((i) => `wss://one.test: reason ${i}`),
'wss://one.test: more of it, no longer logged',
]);
});
it('announces again on the interval it names, at least MIN_INTERVAL, at most TRACKER_WAIT', async () => {
for (const [interval, every] of [
[0, MIN_INTERVAL],
@@ -1373,7 +1439,9 @@ describe('tracker signaling', () => {
for (const sdp of ['v=0\r\na=fingerprint:sha-256 AA\r\n', offer.sdp]) {
tracker.sockets[0]!.deliver(relayed({ offer_id, answer: { type: 'answer', sdp } }));
}
await until(() => receiver.count('answer without the code') === 2);
await until(() => receiver.count('answer without the code'));
await settle();
expect(receiver.count('answer without the code')).toBe(1);
expect(receiver.logged('answer via')).toBe(false);
expect(FakePeer.all.map((pc) => pc.remoteDescription)).toEqual([null]);
});
@@ -1410,9 +1478,13 @@ describe('tracker signaling', () => {
);
await until(() => sender.count('unusable offer') === offers);
if (offers === 1) ws.deliver({ 'failure reason': 'slow down' });
// Fewer than MAX_TRACKER_MESSAGES per MESSAGE_WINDOW, none of them is dropped.
if (offers % 10 === 0) vi.setSystemTime(Date.now() + MESSAGE_WINDOW);
}
for (let offers = 0; offers < 5; offers++) ws.deliver(relayed({ offer_id: offerId(), offer: { sdp: 'garbage' } }));
await until(() => sender.count('offer without the code') === 5);
await until(() => sender.count('offer without the code'));
await settle();
expect(sender.count('offer without the code')).toBe(1);
expect(sender.logged(`${URLS[0]}: slow down`)).toBe(true);
expect(sender.logged('rejected by')).toBe(false);
expect(sender.errors).toEqual([]);
+42 -8
View File
@@ -36,6 +36,15 @@ const ICE_TIMEOUT = 5000;
const PROBE_TIMEOUT = 2000;
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
export const TRACKER_TIMEOUT = 10_000;
// A tracker relays one sealed SDP of a few KiB at a time, a larger message isn't parsed. The browser
// has received it by then, nothing limits that: this only spares parsing and decrypting it.
export const MAX_TRACKER_MESSAGE = 64 * 1024;
// A tracker sends a few messages a minute, replies to announcements and the other side's SDP. Beyond
// MAX_TRACKER_MESSAGES per MESSAGE_WINDOW the rest is dropped, a tracker can't keep the page busy.
export const MAX_TRACKER_MESSAGES = 20;
export const MESSAGE_WINDOW = 10_000;
// What a tracker makes a socket log, each line once and at most this many: it can't fill the log.
export const TRACKER_NOTES = 10;
// A tracker peer that got an answer but never opens the data channel gives up its turn after this,
// e.g. one whose SDP has no usable candidates: Chromium never even fails its connection. The manual
// sender gives up on the answer after it as well.
@@ -882,9 +891,11 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
// A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason
// before anything else rejects the announcement, the tracker is no use then and its socket closes, a
// later one only concerns that message and is logged. message may be async, the next message doesn't
// wait for it. lost runs once it closed without close() being called: unreachable, lost, rejected or
// without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names.
// later one only concerns that message and is noted. A message over MAX_TRACKER_MESSAGE rejects it the
// same way, a later one is noted and dropped. note logs what the tracker made the page do, see
// TRACKER_NOTES. message may be async, the next message doesn't wait for it. lost runs once it closed
// without close() being called: unreachable, lost, rejected or without an answer within
// TRACKER_TIMEOUT. again announces once more, on the first interval it names.
export function trackerSocket(
url: string,
signal: AbortSignal,
@@ -897,6 +908,15 @@ export function trackerSocket(
let opened = false;
let accepted = false;
let closed = false;
// Messages in the current MESSAGE_WINDOW, since windowStart.
let windowStart = Date.now();
let count = 0;
const noted = new Set<string>();
const note = (line: string) => {
if (noted.has(line) || noted.size > TRACKER_NOTES) return;
noted.add(line);
events.log(noted.size > TRACKER_NOTES ? `${url}: more of it, no longer logged` : line);
};
let reannounce: ReturnType<typeof setInterval> | undefined;
const end = (reason: string) => {
if (closed) return;
@@ -912,6 +932,7 @@ export function trackerSocket(
// What the tracker answered, if it rejected the announcement.
rejected: undefined as string | undefined,
alive: () => !closed,
note,
close: () => {
if (closed) return;
closed = true;
@@ -922,6 +943,15 @@ export function trackerSocket(
});
ws.addEventListener('open', () => (opened = true));
ws.addEventListener('message', ({ data }) => {
const now = Date.now();
if (now - windowStart >= MESSAGE_WINDOW) {
windowStart = now;
count = 0;
}
if (++count > MAX_TRACKER_MESSAGES) return note(`${url} sends too much, dropping some of it`);
if (typeof data === 'string' && data.length > MAX_TRACKER_MESSAGE) {
return reject(`${url}: message over ${MAX_TRACKER_MESSAGE / 1024} KiB`);
}
const msg = parse(data);
const failure = msg?.['failure reason'];
if (typeof failure !== 'string') {
@@ -934,10 +964,14 @@ export function trackerSocket(
}
return void message(msg);
}
if (accepted) return events.log(`${url}: ${failure}`);
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
end(`rejected by ${tracker.rejected}`);
reject(`${url}: ${failure.slice(0, 200)}`);
});
// A problem with the tracker's message: the end before acceptance, after it only that message's.
const reject = (reason: string) => {
if (accepted) return note(reason);
tracker.rejected = reason;
end(`rejected by ${reason}`);
};
ws.addEventListener('close', () => end(opened ? `lost ${url}` : `${url} unreachable`));
return tracker;
}
@@ -1101,7 +1135,7 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
// Meanwhile the share may have been used up, expired or ended, its tracker closed then.
if (signal.aborted || !tracker.alive()) return;
if (sdp === undefined) return events.log(`offer without the code via ${url}`);
if (sdp === undefined) return tracker.note(`offer without the code via ${url}`);
const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
if (busy) waiting = () => answer(tracker.ws, url, offer);
else void answer(tracker.ws, url, offer);
@@ -1297,7 +1331,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
// Only one answer per offer, a replacement opens its own socket. Meanwhile it may have
// come, or the search ended, its socket closed then.
if (pc.signalingState === 'closed' || !tracker.alive()) return;
if (answer === undefined) return events.log(`answer without the code via ${url}`);
if (answer === undefined) return tracker.note(`answer without the code via ${url}`);
events.log(`answer via ${url}`);
attempts++;
noSender = false;