fix timeout issue (maybe?)

This commit is contained in:
Schluffe committed 2026-10-16 12:01:43 +02:00
1 parent 95e4a879b9
commit b7f47531b7
7 files changed
+397 -5

No files matched your search

+25 -1
View File
@@ -12,7 +12,8 @@ explicit opt-in by both people; no relay is configured automatically.
1. The sender picks one file and configures STUN (PageQuit by default, Google,
Cloudflare, a custom provider, or None). They create a code and send it
privately to the intended receiver through an authenticated channel.
privately to the intended receiver through an authenticated channel. Normal
messenger copy/paste is supported; there is no need to transcribe codes.
2. The receiver pastes the code, creates an answer, and sends it back. The sender
pastes the answer. Gathering waits for completion, up to 30 seconds; a timeout
fails rather than quietly exporting incomplete connection information.
@@ -34,6 +35,8 @@ explicit opt-in by both people; no relay is configured automatically.
Cancel, reset, changing the selected file, or switching Send/Receive closes the
connection and aborts unfinished disk writes. Keep the tab open until receipt is
confirmed. A completed memory download is discarded when you reset or switch.
Switching browser tabs or apps to copy/paste does not explicitly cancel the
session, although a browser or mobile OS can suspend a background page.
Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. The two peers must use this protocol version (v2);
legacy connection codes are rejected.
@@ -47,6 +50,27 @@ separate browser tabs or windows; switching Send/Receive inside one page cancels
that page's previous connection. Use the specific error shown in red to diagnose
failures; if a configured STUN server is unreachable, try None for a local test.
### Connection diagnostics and first-version comparison
Expand **Connection diagnostics** to copy the last 80 timed events. The log
retains local/remote candidate type counts, candidate-pair states, selected
route types, and ICE check request/response counters after failure. Final stats
are requested before closing the peer, with a 300 ms cleanup bound. A `?` means
the browser did not supply a counter; it does not mean zero. Addresses, raw SDP,
candidate IDs, credentials, server URLs and filenames are excluded.
Same-machine success does not establish cross-device connectivity. Error 701
alone does not establish the cause of a failed connection. A receiver shutdown
after both sides report completion can be normal sender cleanup.
The comparison with the first commit and controlled test results are recorded in
[the investigation notes](docs/connection-investigation.md). Run the isolated
ICE experiment with `node scripts/compare-ice.mjs firefox` or replace `firefox`
with `chromium`. This uses local browser peers and deliberately unusable offer
ports plus a 20-second answer delay; it is **not a cross-device test**. Add
`--normal-candidates` to preserve the real candidate ports. No firewall changes,
TURN credentials or public STUN service are required.
## Network privacy and optional TURN
STUN discovers externally reachable addresses. Its operator can see your public
+67
View File
@@ -0,0 +1,67 @@
# First-version comparison
Compared `d198332` (first commit) with `95e4a87` (current checkout), 2026-10-16.
The checkout was clean and did not contain the diagnostics files mentioned in
the handoff. The preview on port 4174 was not running.
The user reports the original version works between two physical machines on
different networks. Earlier successful diagnostic logs were both same-machine
tests. The physical-device regression remains **unexplained**; the experiments
below do not reproduce it and do not establish a firewall, DNS or timing cause.
## Relevant differences
| Area | First version | Current checkout | Finding |
| --- | --- | --- | --- |
| STUN default | Google | PageQuit (introduced in `1d8e595`) | User also observed failure with Google; 701 is not a sufficient explanation. |
| Gathering | Completes immediately when done, otherwise returns partial SDP after 5 s | Requires completion within 30 s (`752d0cf`) | A real behavior change, but reported failed sessions gathered in 0–0.1 s. No evidence this deadline caused those failures. |
| Signaling | Base64 of SDP | Base64 of a versioned JSON envelope (`752d0cf`) | Both use the gathered `localDescription.sdp`, preserve candidates, and apply decoded SDP directly. Neither implements trickle signaling. |
| Failed peer | UI marks closed; peer stays alive | Session disposes failed peer (`752d0cf`) | Tested keeping it alive; did not recover in the controlled Firefox case. No justification yet to treat this as the root cause. |
| Transfer | Sends metadata/file on channel open | Requires fingerprint confirmation and receiver acceptance | These happen after ICE connects. The reported failures are at ICE setup. |
| Lifecycle | Sender was not closed on component unmount | Both roles close when switching Send/Receive | Browser-tab/app switching has no explicit cancellation handler in either version. |
| TURN | None | Explicit opt-in only | Default remains direct; do not assume another application's successful path was direct. |
## Controlled experiment
`scripts/compare-ice.mjs` loads the actual signaling helpers from the first
commit using `git show`, and the current helpers using Node's TypeScript
eraser. It creates independent local peer pairs for three modes: original,
current with the current UI's immediate failed-peer cleanup, and current with
that cleanup disabled. This isolates signaling/lifecycle behavior; it is not a
test of either complete Vue UI and does not simulate a physical network fully.
All modes use identical ICE configuration. The experiment removes TCP offer
candidates and changes advertised UDP ports to port 9, leaving the real sender
socket alive. This deliberately prevents initial checks to the advertised
sender endpoint; a subsequent sender-initiated check can potentially discover
a usable peer-reflexive candidate. The answer is applied after 20 seconds.
Only times/states and receipt of a fixed probe string are reported, never SDP.
Observed results on this host:
| Browser | Original | Current | Current, keep failed peer |
| --- | --- | --- | --- |
| Firefox | Receiver failed at ~5 s; no probe received | Receiver failed at ~5 s; no probe received | Receiver failed at ~5 s; no probe received |
| Chromium | Probe received at ~20.3 s | Probe received at ~20.3 s | Probe received at ~20.3 s |
A further Firefox run configured a silent loopback UDP socket as STUN
(`--slow-stun`). All modes still completed gathering in under 0.1 s and included
the end-of-candidates marker, so this did **not** exercise the partial-gathering
fallback. All failed alike. Do not claim this tested a genuinely slow STUN path.
These results rule out the claim that simply retaining a failed peer fixes this
particular controlled case. They do not rule out a lifecycle regression in other
conditions, nor prove that a 20-second answer delay is safe on physical devices.
## Next discriminating evidence
Use matching first/current versions on both physical devices, with the same
sender direction, STUN provider and page origin/browser profile. Record whether
the actual receiver obtains the full file. Compare local/remote candidate types,
selected pairs and check counters; the current UI now retains these after
failure. A missing public candidate, an absence of candidate pairs, and checks
sent with no responses are distinct observations, not diagnoses by themselves.
Do not change firewall rules or shorten user copy/paste time based only on the
same-machine tests. The original/current comparison has not yet identified a
code change that demonstrably explains the user's physical-device failures.
+10
View File
@@ -200,6 +200,13 @@ try {
return { length: bytes.length, valid: bytes.every(b => b === 123) };
});
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
await wait(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
const diagnostics = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value);
assert.match(diagnostics, /local code: host=\d+/);
assert.match(diagnostics, /remote code: host=\d+/);
assert.match(diagnostics, /requestsSent=/);
assert.match(diagnostics, /transfer done/);
assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/);
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
await click(sender, 'Reset'); await click(receiver, 'Reset');
@@ -213,6 +220,9 @@ try {
await click(sender, 'Receive');
await wait(receiver, () => window.__hellcon.aborted);
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
await wait(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
assert.match(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value), /session failed/);
console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.');
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
await click(sender, 'Send'); await click(receiver, 'Reset');
await connect(sender, receiver, 2048);
+87
View File
@@ -0,0 +1,87 @@
import { createServer } from 'node:http';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { execFileSync, spawn } from 'node:child_process';
import { stripTypeScriptTypes } from 'node:module';
import { createSocket } from 'node:dgram';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
// A controlled ICE experiment, not a cross-device transfer test. Reads the
// original signaling helpers from git without checking out or editing files.
const root = fileURLToPath(new URL('..', import.meta.url));
const legacy = execFileSync('git', ['show', 'd198332:src/lib/webrtc.js'], { cwd: root, encoding: 'utf8' });
const current = stripTypeScriptTypes(await readFile(root + '/src/lib/webrtc.ts', 'utf8'));
const validation = stripTypeScriptTypes(await readFile(root + '/src/lib/validation.ts', 'utf8'));
const udp = createSocket('udp4');
await new Promise(resolve => udp.bind(0, '127.0.0.1', resolve));
const stunUrl = process.argv.includes('--slow-stun') ? 'stun:127.0.0.1:' + udp.address().port : null;
const rewritePorts = !process.argv.includes('--normal-candidates');
const browserCode = String.raw`
import * as old from '/old.js';
import * as current from '/current.js';
async function run(mode) {
const api = mode === 'original' ? old : current;
const start = performance.now();
const events = [];
const log = (event) => events.push([Math.round(performance.now()-start),event]);
const {stunUrl,rewritePorts} = await (await fetch('/config')).json();
const a = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
const b = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
if(mode !== 'original') { a.setConfiguration(current.iceConfiguration({stunUrl})); b.setConfiguration(current.iceConfiguration({stunUrl})); }
let received = false;
for(const [role,pc] of [['sender',a],['receiver',b]]) {
pc.oniceconnectionstatechange = () => log(role + ' ICE ' + pc.iceConnectionState);
pc.onconnectionstatechange = () => {
log(role + ' PC ' + pc.connectionState);
if(mode === 'current' && pc.connectionState === 'failed') pc.close();
};
}
const dc = a.createDataChannel('file');
dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); };
b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; };
try {
const offer = await api.createOfferCode(a);
let sdp = api.decodeSignal(offer);
// Deliberately unusable advertised ports: only sender-initiated checks
// after the answer can discover the real sender. No host firewall changes.
if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{
if(!l.startsWith('a=candidate:'))return l;
const fields=l.split(' '); fields[5]='9'; return fields.join(' ');
}).join('\r\n');
log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates'));
const answer = await api.createAnswerCode(b, api.encodeSignal(sdp));
log('answer ready');
await new Promise(r=>setTimeout(r,20000));
log('apply answer');
await api.acceptAnswerCode(a,answer);
await new Promise(r=>setTimeout(r,12000));
return {mode,received,events};
} catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; }
finally {a.close();b.close();}
}
const results = await Promise.all(['original','current','current-keep'].map(run));
await fetch('/result',{method:'POST',body:JSON.stringify(results)});
`;
let done;
const finished = new Promise(resolve=>done=resolve);
const server = createServer(async(req,res)=>{
if(req.url === '/config') { res.setHeader('Content-Type','application/json');res.end(JSON.stringify({stunUrl,rewritePorts}));return; }
if(req.url === '/result') {let body=''; for await(const part of req)body+=part; console.log(body);res.end('ok');done();return;}
res.setHeader('Content-Type',req.url==='/'?'text/html':'text/javascript');
res.end(({'/':'<script type="module" src="/run.js"></script>','/old.js':legacy,'/current.js':current,'/validation.ts':validation,'/run.js':browserCode})[req.url] || '');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const profile=await mkdtemp(join(tmpdir(), 'hellcon-ice-comparison-'));
const name=process.argv[2] || 'firefox';
const url='http://127.0.0.1:'+server.address().port;
const args=name==='firefox'?['--headless','--no-remote','--profile',profile,url]:['--headless','--no-sandbox','--disable-gpu','--no-first-run','--user-data-dir='+profile,url];
const child=spawn('/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});
child.on('error',()=>{console.error('Could not launch browser');process.exitCode=1;done();});
let errors='';child.stderr.on('data',chunk=>errors+=chunk);
const timer=setTimeout(()=>{console.log('Comparison timed out');process.exitCode=1;done();},85000);
try {await finished;} finally {
clearTimeout(timer);child.kill();
if(child.pid && child.exitCode===null && child.signalCode===null) await new Promise(resolve=>child.once('exit',resolve));
server.closeAllConnections();server.close();udp.close();
await rm(profile,{recursive:true,force:true,maxRetries:3});
}
+28 -4
View File
@@ -6,6 +6,7 @@ import { computed, onBeforeUnmount, ref } from 'vue';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
@@ -14,6 +15,7 @@ interface Session {
file: File | null;
controller: AbortController;
transfer: Transfer | null;
diagnostics: ConnectionDiagnostics;
timer?: ReturnType<typeof setTimeout>;
}
@@ -31,6 +33,8 @@ const incoming = ref<FileMetadata | null>(null);
const downloadUrl = ref('');
const choosing = ref(false);
const dragover = ref(false);
const diagnosticLines = ref<string[]>([]);
let latestDiagnostics: ConnectionDiagnostics | null = null;
const iceEndpoint = location.protocol === 'file:' ? '' : import.meta.env.VITE_ICE_ENDPOINT || '';
const defaultStun = location.protocol === 'file:' ? '' : import.meta.env.VITE_STUN_URL || '';
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
@@ -64,13 +68,16 @@ function dispose() {
active = null;
if (!old) return;
clearTimeout(old.timer);
// Start the snapshot before aborting/closing anything; close the peer after
// stats resolve (bounded to 300 ms), so failure evidence remains available.
void old.diagnostics.finish(() => old.pc.close());
old.controller.abort();
old.transfer?.close();
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
old.pc.close();
}
function reset(keepNetwork = false) {
dispose(); revokeDownload(); clearTimeout(copyTimer);
latestDiagnostics = null; diagnosticLines.value = [];
managedCredentials.value = null;
if (!keepNetwork) settings.value.allowTurn = false;
inputCode.value = outputCode.value = error.value = '';
@@ -80,6 +87,7 @@ function reset(keepNetwork = false) {
}
function fail(session: Session, err: unknown) {
if (active !== session) return;
session.diagnostics.record('session failed');
dispose(); revokeDownload();
managedCredentials.value = null;
fps.value = incoming.value = null;
@@ -102,7 +110,7 @@ function attach(session: Session, channel: RTCDataChannel) {
}
session.transfer = new Transfer(channel, {
file: props.sending ? session.file : null,
onState: state => { if (active === session) step.value = state; },
onState: state => { if (active === session) { step.value = state; session.diagnostics.record(`transfer ${state}`); } },
onMeta: meta => { if (active === session) incoming.value = meta; },
onProgress: (bytes, size) => { if (active === session) progress.value = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100)); },
onComplete: ({ blob }) => {
@@ -131,7 +139,12 @@ function start() {
};
// Fetch managed credentials before gathering, while retaining normal cancellation.
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
let diagnostics: ConnectionDiagnostics;
diagnostics = new ConnectionDiagnostics(pc, lines => {
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
});
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null, diagnostics };
active = session;
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
pc.ondatachannel = event => attach(session, event.channel);
@@ -163,6 +176,8 @@ async function createCode() {
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
if (active !== session) return;
outputCode.value = code;
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
session.diagnostics.descriptions();
if (!props.sending) fps.value = getFingerprints(session.pc, options);
step.value = props.sending ? 'offer-ready' : 'answer-ready';
} catch (err) {
@@ -178,6 +193,9 @@ async function useAnswer() {
try {
await acceptAnswerCode(session.pc, inputCode.value, session.options);
if (active !== session) return;
session.diagnostics.record('answer applied');
session.diagnostics.descriptions();
void session.diagnostics.capture();
fps.value = getFingerprints(session.pc, session.options);
} catch (err) {
if (active !== session) return;
@@ -281,8 +299,14 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
<p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<details v-if="diagnosticLines.length">
<summary>Connection diagnostics</summary>
<p class="status">Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.</p>
<label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label>
<textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" />
</details>
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
<p class="status">Switching HellCon’s Send/Receive mode cancels the connection. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div>
</template>
+107
View File
@@ -0,0 +1,107 @@
// Only allowlisted categories and numbers leave this module. Never retain raw
// SDP, candidate addresses/IDs, URLs, credentials, filenames or browser errors.
const candidateTypes = ['host', 'srflx', 'prflx', 'relay'] as const;
const protocols = ['udp', 'tcp'] as const;
const pairStates = ['frozen', 'waiting', 'in-progress', 'failed', 'succeeded'] as const;
const counters = ['requestsSent', 'requestsReceived', 'responsesSent', 'responsesReceived'] as const;
type StatsEntry = Record<string, unknown>;
type Stats = Pick<RTCStatsReport, 'forEach' | 'get'>;
const category = (value: unknown, allowed: readonly string[]) => typeof value === 'string' && allowed.includes(value) ? value : 'unknown';
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';
export function summarizeCandidates(sdp: string | undefined): string {
const counts = { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 };
for (const line of sdp?.split(/\r?\n/) ?? []) {
if (!line.startsWith('a=candidate:')) continue;
const type = category(line.match(/\styp\s+(\S+)/)?.[1], candidateTypes) as keyof typeof counts;
counts[type]++;
}
return Object.entries(counts).map(([type, n]) => `${type}=${n}`).join(' ') +
` end=${sdp?.split(/\r?\n/).includes('a=end-of-candidates') ? 'yes' : 'no'}`;
}
export function summarizeStats(stats: Stats): string[] {
const pairs: StatsEntry[] = [];
const selected = new Set<string>();
const candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 } };
stats.forEach((entry: StatsEntry) => {
if (entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string') selected.add(entry.selectedCandidatePairId);
if (entry.type === 'candidate-pair') pairs.push(entry);
const side = entry.type === 'local-candidate' ? 'local' : entry.type === 'remote-candidate' ? 'remote' : null;
if (side) candidates[side][category(entry.candidateType, candidateTypes) as keyof typeof candidates.local]++;
});
const endpoint = (id: unknown) => {
const entry = typeof id === 'string' ? stats.get(id) as StatsEntry | undefined : undefined;
return `${category(entry?.candidateType, candidateTypes)}/${category(entry?.protocol, protocols)}`;
};
const lines = (['local', 'remote'] as const).map(side => `${side} stats: ` + Object.entries(candidates[side]).map(([type, n]) => `${type}=${n}`).join(' '));
lines.push(`pairs=${pairs.length}`);
// Put a selected route first, cap output on machines with many interfaces.
const isSelected = (pair: StatsEntry) => typeof pair.id === 'string' && selected.has(pair.id) || pair.selected === true;
pairs.sort((a, b) => Number(isSelected(b)) - Number(isSelected(a)));
for (const pair of pairs.slice(0, 12)) {
lines.push(`pair ${endpoint(pair.localCandidateId)} → ${endpoint(pair.remoteCandidateId)} ${category(pair.state, pairStates)}` +
` selected=${isSelected(pair)} nominated=${pair.nominated === true} ` + counters.map(key => `${key}=${count(pair[key])}`).join(' '));
}
if (pairs.length > 12) lines.push(`pairs omitted=${pairs.length - 12}`);
return lines;
}
export class ConnectionDiagnostics {
readonly lines: string[] = [];
private readonly started = performance.now();
private stopped = false;
private finishing: Promise<void> | undefined;
private readonly listeners: Array<[EventTarget, string, EventListener]> = [];
private readonly pc: RTCPeerConnection;
private readonly update: (lines: string[]) => void;
constructor(pc: RTCPeerConnection, update: (lines: string[]) => void) {
this.pc = pc; this.update = update;
const listen = (target: EventTarget, event: string, listener: EventListener) => {
target.addEventListener(event, listener);
this.listeners.push([target, event, listener]);
};
const state = () => {
this.record(`pc=${category(pc.connectionState, ['new', 'connecting', 'connected', 'disconnected', 'failed', 'closed'])} ice=${category(pc.iceConnectionState, ['new', 'checking', 'connected', 'completed', 'disconnected', 'failed', 'closed'])} gathering=${category(pc.iceGatheringState, ['new', 'gathering', 'complete'])}`);
};
for (const event of ['connectionstatechange', 'iceconnectionstatechange', 'icegatheringstatechange']) listen(pc, event, state);
listen(pc, 'icecandidateerror', event => this.record(`ICE server error=${count((event as RTCPeerConnectionIceErrorEvent).errorCode)}`));
if (typeof document !== 'undefined') {
const visibility = () => this.record(`page=${category(document.visibilityState, ['visible', 'hidden'])}`);
listen(document, 'visibilitychange', visibility);
visibility();
}
state();
}
record(message: string) {
if (this.stopped) return;
this.lines.push(`${((performance.now() - this.started) / 1000).toFixed(1)}s ${message}`);
this.lines.splice(0, Math.max(0, this.lines.length - 80));
this.update([...this.lines]);
}
descriptions() {
this.record(`local code: ${summarizeCandidates(this.pc.localDescription?.sdp)}`);
this.record(`remote code: ${summarizeCandidates(this.pc.remoteDescription?.sdp)}`);
}
async capture() {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const stats = await Promise.race([
this.pc.getStats(),
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 300); }),
]);
if (stats) for (const line of summarizeStats(stats)) this.record(line);
else this.record('stats unavailable: deadline');
} catch { this.record('stats unavailable'); }
finally { clearTimeout(timer); }
}
// Request final stats while the connection is alive. Always close, even when
// getStats rejects or hangs. Reset can start a new session during this wait.
finish(close: () => void) {
return this.finishing ??= this.capture().finally(() => {
this.stopped = true;
for (const [target, event, listener] of this.listeners) target.removeEventListener(event, listener);
close();
});
}
}
+73
View File
@@ -0,0 +1,73 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { ConnectionDiagnostics, summarizeCandidates, summarizeStats } from '../src/lib/connection-diagnostics.ts';
test('candidate summaries keep types and end marker, never addresses or SDP secrets', () => {
const sdp = 'a=ice-pwd:private-password\r\na=fingerprint:sha-256 SECRET\r\n' +
'a=candidate:private-id 1 udp 123 192.0.2.20 5000 typ host\r\n' +
'a=candidate:other-id 1 udp 123 example.local 5000 typ host\r\n' +
'a=candidate:another-id 1 udp 123 2001:db8::1 5000 typ srflx\r\n' +
'a=candidate:last-id 1 udp 123 192.0.2.22 5000 typ private-value\r\na=end-of-candidates\r\n';
assert.equal(summarizeCandidates(sdp), 'host=2 srflx=1 prflx=0 relay=0 unknown=1 end=yes');
assert.equal(summarizeCandidates(undefined), 'host=0 srflx=0 prflx=0 relay=0 unknown=0 end=no');
});
test('stats use only allowlisted types, pair states and nonnegative integer counters', () => {
const stats = new Map([
['private-local-id', { type: 'local-candidate', candidateType: 'srflx', protocol: 'udp', address: '192.0.2.20', usernameFragment: 'private-user' }],
['private-remote-id', { type: 'remote-candidate', candidateType: 'host', protocol: 'private-protocol', address: '192.0.2.21' }],
['private-pair-id', { id: 'private-pair-id', type: 'candidate-pair', localCandidateId: 'private-local-id', remoteCandidateId: 'private-remote-id', state: 'failed', nominated: false, requestsSent: 8, requestsReceived: 0, responsesReceived: -1, responsesSent: 'private-text' }],
['transport', { type: 'transport', selectedCandidatePairId: 'private-pair-id' }],
]);
const lines = summarizeStats(stats);
assert.equal(lines[3], 'pair srflx/udp → host/unknown failed selected=true nominated=false requestsSent=8 requestsReceived=0 responsesSent=? responsesReceived=?');
assert.doesNotMatch(lines.join('\n'), /private|192\.0\.2/);
});
class Peer extends EventTarget {
connectionState = 'failed';
iceConnectionState = 'failed';
iceGatheringState = 'complete';
closed = false;
getStats: () => Promise<Map<string, Record<string, unknown>>> = async () => new Map();
}
const diagnose = (peer: Peer) => new ConnectionDiagnostics(peer as unknown as RTCPeerConnection, () => {});
test('final stats are collected before close, close is called once, and listeners stop', async () => {
const peer = new Peer();
let resolve!: (stats: Map<string, Record<string, unknown>>) => void;
peer.getStats = () => {
assert.equal(peer.closed, false);
return new Promise(done => { resolve = done; });
};
const diagnostics = diagnose(peer);
let closes = 0;
const close = () => { peer.closed = true; closes++; };
const finishing = diagnostics.finish(close);
assert.equal(diagnostics.finish(close), finishing);
assert.equal(closes, 0);
resolve(new Map());
await finishing;
assert.equal(closes, 1);
assert.ok(diagnostics.lines.some(line => line.endsWith('pairs=0')));
const saved = [...diagnostics.lines];
peer.dispatchEvent(new Event('connectionstatechange'));
assert.deepEqual(diagnostics.lines, saved);
});
test('rejected and hung stats cannot prevent peer cleanup or leak error details', async () => {
for (const getStats of [async () => { throw new Error('private credential'); }, () => new Promise<Map<string, Record<string, unknown>>>(() => {})]) {
const peer = new Peer(); peer.getStats = getStats;
const diagnostics = diagnose(peer);
await diagnostics.finish(() => { peer.closed = true; });
assert.equal(peer.closed, true);
assert.match(diagnostics.lines.join('\n'), /stats unavailable/);
assert.doesNotMatch(diagnostics.lines.join('\n'), /private credential/);
}
});
test('event history remains bounded', () => {
const peer = new Peer(); const diagnostics = diagnose(peer);
for (let i = 0; i < 100; i++) peer.dispatchEvent(new Event('iceconnectionstatechange'));
assert.equal(diagnostics.lines.length, 80);
});