From b7f47531b7194a8154587cda952e089aabbd0d1a Mon Sep 17 00:00:00 2001 From: Schluffe Date: Fri, 16 Oct 2026 12:01:43 +0200 Subject: [PATCH] fix timeout issue (maybe?) --- README.md | 26 ++++++- docs/connection-investigation.md | 67 +++++++++++++++++ scripts/browser-check.ts | 10 +++ scripts/compare-ice.mjs | 87 ++++++++++++++++++++++ src/components/TransferPanel.vue | 32 +++++++- src/lib/connection-diagnostics.ts | 107 +++++++++++++++++++++++++++ tests/connection-diagnostics.test.ts | 73 ++++++++++++++++++ 7 files changed, 397 insertions(+), 5 deletions(-) create mode 100644 docs/connection-investigation.md create mode 100644 scripts/compare-ice.mjs create mode 100644 src/lib/connection-diagnostics.ts create mode 100644 tests/connection-diagnostics.test.ts diff --git a/README.md b/README.md index 9154df0..290a36f 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/connection-investigation.md b/docs/connection-investigation.md new file mode 100644 index 0000000..eec6d83 --- /dev/null +++ b/docs/connection-investigation.md @@ -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. diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index f7a0e46..8a775f4 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -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('#connection-diagnostics').value.includes('pairs=')); + const diagnostics = await evaluate(sender, () => window.__hellcon.element('#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('#connection-diagnostics').value.includes('pairs=')); + assert.match(await evaluate(receiver, () => window.__hellcon.element('#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); diff --git a/scripts/compare-ice.mjs b/scripts/compare-ice.mjs new file mode 100644 index 0000000..e394652 --- /dev/null +++ b/scripts/compare-ice.mjs @@ -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(({'/':'','/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}); +} diff --git a/src/components/TransferPanel.vue b/src/components/TransferPanel.vue index 756fb9b..f879956 100644 --- a/src/components/TransferPanel.vue +++ b/src/components/TransferPanel.vue @@ -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; } @@ -31,6 +33,8 @@ const incoming = ref(null); const downloadUrl = ref(''); const choosing = ref(false); const dragover = ref(false); +const diagnosticLines = ref([]); +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({ 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); })

{{ status }}

+
+ Connection diagnostics +

Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.

+ +