AtlatestRepositorysigil-http3
sigil-http3 / tree / spikes / webrtcwebrtc.html
1
<!doctype html>2
<html lang="en">3
<meta charset="utf-8">4
<meta name="viewport" content="width=device-width, initial-scale=1">5
<meta name="referrer" content="no-referrer">6
<link rel="icon" href="data:,">7
<title>Sigil WebRTC feasibility</title>8
<style>9
:root { color-scheme: light dark; font: 16px system-ui, sans-serif; }10
body { max-width: 48rem; margin: auto; padding: 1rem; }11
button { padding: .8rem; margin: .3rem; font: inherit; }12
#network { padding: 1rem; border: 3px solid currentColor; font-weight: bold; font-size: 1.2rem; }13
#network[data-online="false"] { color: #c43c35; }14
pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 24rem; overflow: auto; }15
dl { display: grid; grid-template-columns: 1fr 1fr; gap: .6rem; }16
dd { margin: 0; }17
</style>18
<h1>WebRTC data-channel test</h1>19
<p>Cellular arm: VPN and Wi-Fi off. Start chrome://net-export before Connect. Use a fresh session link for each arm. For the separate sanity arm, use the same Wi-Fi as Phantom.</p>20
<p id="network" role="status" aria-live="polite">Checking network…</p>21
<p>Browser discovery: Google STUN. Phantom: IPv6 host candidates only. No TURN. ONLINE is a browser hint; the selected pair and echo establish connectivity.</p>22
<button id="connect" disabled>Connect</button><button id="stop" disabled>Stop</button><button id="save">Save log</button>23
<dl aria-live="polite">24
<dt>State</dt><dd id="state">idle</dd>25
<dt>Echoes / sent</dt><dd id="counts">0 / 0</dd>26
<dt>RTT / maximum</dt><dd id="rtt">—</dd>27
<dt>Candidate counts</dt><dd id="candidates">—</dd>28
</dl>29
<p>Selected pair / transport statistics</p><pre id="pair">No pair selected.</pre>30
<pre id="events" aria-label="Event log"></pre>31
<script>32
'use strict';33
(() => {34
const el = id => document.getElementById(id);35
const started = performance.now(), entries = [], samples = [], candidates = [];36
const fragment = new URLSearchParams(location.hash.slice(1));37
const token = fragment.get('session');38
const validToken = fragment.getAll('session').length === 1 && /^[0-9a-f]{64}$/.test(token ?? '');39
history.replaceState(null, '', location.pathname + location.search);40
let pc, channel, used = false, stopped = false, pingTimer, statsTimer, iceTimer, lifetimeTimer;41
let sent = 0, received = 0, maximum = 0, sequence = 0, statsBusy = false;42
let selectedPair = null;43
const pending = new Map(), counts = {};44
const timers = new Set();45
const log = (kind, detail = {}) => {46
entries.push({ utc: new Date().toISOString(), elapsedMs: +(performance.now() - started).toFixed(1), kind, ...detail });47
if (entries.length > 2000) entries.shift();48
el('events').textContent = entries.slice(-60).map(v => JSON.stringify(v)).join('\n');49
};50
const state = value => { el('state').textContent = value; };51
function controls() {52
el('connect').disabled = used || !validToken || !navigator.onLine;53
el('stop').disabled = !pc || stopped;54
}55
function network(event) {56
const value = { online: navigator.onLine, type: navigator.connection?.type ?? 'unknown',57
effectiveType: navigator.connection?.effectiveType ?? 'unknown', visibility: document.visibilityState,58
source: event?.type ?? 'initial' };59
el('network').textContent = `${value.online ? 'ONLINE' : 'OFFLINE'} · connection: ${value.type} · ${value.effectiveType}`;60
el('network').dataset.online = String(value.online);61
log('network', value); controls();62
}63
async function snapshot() {64
if (!pc || statsBusy) return;65
statsBusy = true;66
try {67
const report = await pc.getStats();68
const items = [...report.values()];69
const transport = items.find(s => s.type === 'transport' && s.selectedCandidatePairId);70
const pair = transport ? report.get(transport.selectedCandidatePairId) :71
items.find(s => s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded');72
selectedPair = pair ? { pair, local: report.get(pair.localCandidateId), remote: report.get(pair.remoteCandidateId), transport } : null;73
el('pair').textContent = JSON.stringify(selectedPair ?? { ice: pc.iceConnectionState, connection: pc.connectionState }, null, 2);74
const data = items.filter(s => ['candidate-pair', 'local-candidate', 'remote-candidate', 'transport', 'data-channel'].includes(s.type));75
log('stats', { selectedPair, report: data });76
} catch (error) { log('stats-error', { name: error.name, message: error.message }); }77
finally { statsBusy = false; }78
}79
async function finish(reason, failure = false) {80
if (stopped) return;81
stopped = true;82
clearInterval(pingTimer); clearInterval(statsTimer); clearTimeout(iceTimer); clearTimeout(lifetimeTimer);83
for (const timer of timers) clearTimeout(timer);84
timers.clear();85
await snapshot();86
log(failure ? 'failed' : 'stopped', { reason, sent, received });87
channel?.close(); pc?.close(); state(failure ? 'failed' : 'stopped'); controls();88
}89
async function bounded(promise, milliseconds, label) {90
let timer;91
try { return await Promise.race([promise, new Promise((_, reject) => {92
timer = setTimeout(() => reject(new Error(label + ' deadline')), milliseconds); timers.add(timer);93
})]); } finally { clearTimeout(timer); timers.delete(timer); }94
}95
function gathering() {96
if (pc.iceGatheringState === 'complete') return Promise.resolve();97
return new Promise(resolve => {98
const check = () => { if (pc.iceGatheringState === 'complete') { pc.removeEventListener('icegatheringstatechange', check); resolve(); } };99
pc.addEventListener('icegatheringstatechange', check); check();100
});101
}102
async function connect() {103
if (used) return;104
network({ type: 'before-connect' });105
if (!navigator.onLine || !validToken || !isSecureContext || !window.RTCPeerConnection) {106
log('connect-refused', { reason: 'Need ONLINE, secure context, WebRTC and a fresh valid session link' }); return;107
}108
used = true; controls(); state('gathering');109
try {110
pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], iceTransportPolicy: 'all' });111
lifetimeTimer = setTimeout(() => void finish('90-second session limit'), 90000);112
for (const event of ['iceconnectionstatechange', 'connectionstatechange', 'signalingstatechange', 'icegatheringstatechange'])113
pc.addEventListener(event, () => {114
log(event, { ice: pc.iceConnectionState, connection: pc.connectionState, gathering: pc.iceGatheringState, signaling: pc.signalingState });115
if (pc.connectionState === 'failed') void finish('Peer connection failed', true);116
});117
pc.addEventListener('icecandidateerror', e => log('ice-candidate-error', { code: e.errorCode, text: e.errorText, url: e.url }));118
pc.addEventListener('icecandidate', e => {119
if (!e.candidate) { log('end-of-candidates'); return; }120
const c = e.candidate;121
const value = { ...c.toJSON(), type: c.type, protocol: c.protocol, address: c.address, port: c.port };122
candidates.push(value);123
const kind = c.type === 'host' && /\.local\b/.test(c.candidate) ? 'host-mDNS' : c.type;124
counts[kind] = (counts[kind] ?? 0) + 1;125
el('candidates').textContent = JSON.stringify(counts); log('candidate', value);126
});127
channel = pc.createDataChannel('sigil-echo', { ordered: true }); channel.binaryType = 'arraybuffer';128
channel.onopen = () => {129
clearTimeout(iceTimer); state('open'); log('channel-open');130
const ping = () => {131
if (stopped || channel.readyState !== 'open' || channel.bufferedAmount > 4096 || pending.size >= 128) return;132
const bytes = new ArrayBuffer(16), view = new DataView(bytes), id = ++sequence, now = performance.now();133
view.setUint32(0, id); view.setFloat64(4, now); view.setUint32(12, 0x53474932);134
pending.set(id, now); channel.send(bytes); sent++; el('counts').textContent = `${received} / ${sent}`;135
};136
ping(); pingTimer = setInterval(ping, 250); void snapshot();137
};138
channel.onmessage = e => {139
if (!(e.data instanceof ArrayBuffer) || e.data.byteLength !== 16) { void finish('Invalid echo payload', true); return; }140
const view = new DataView(e.data), id = view.getUint32(0), start = pending.get(id);141
if (start === undefined || view.getUint32(12) !== 0x53474932) return;142
pending.delete(id); received++;143
const rtt = performance.now() - start; maximum = Math.max(maximum, rtt);144
samples.push({ utc: new Date().toISOString(), id, rtt }); if (samples.length > 512) samples.shift();145
el('rtt').textContent = `${rtt.toFixed(1)} / ${maximum.toFixed(1)} ms`; el('counts').textContent = `${received} / ${sent}`;146
};147
channel.onerror = e => { log('channel-error', { message: e.error?.message ?? 'Data channel error' }); void finish('Data channel error', true); };148
channel.onclose = () => { log('channel-closed'); if (!stopped) void finish('Data channel closed'); };149
await pc.setLocalDescription(await pc.createOffer());150
await bounded(gathering(), 5000, 'ICE gathering');151
log('offer-ready', { candidateCounts: counts }); state('signaling');152
const abort = new AbortController();153
const deadline = setTimeout(() => abort.abort(), 10000); timers.add(deadline);154
let response;155
try { response = await fetch('/wt-spike/signal', { method: 'POST', credentials: 'omit', cache: 'no-store', redirect: 'error',156
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },157
body: JSON.stringify({ type: pc.localDescription.type, sdp: pc.localDescription.sdp }), signal: abort.signal }); }158
finally { clearTimeout(deadline); timers.delete(deadline); }159
if (!response.ok) throw new Error(`Signaling HTTP ${response.status}`);160
const text = await bounded(response.text(), 3000, 'Answer body');161
if (text.length > 65536) throw new Error('Answer exceeds limit');162
const answer = JSON.parse(text);163
if (answer.type !== 'answer' || typeof answer.sdp !== 'string') throw new Error('Invalid answer');164
await pc.setRemoteDescription(answer); log('answer-applied'); state('checking');165
statsTimer = setInterval(() => void snapshot(), 1000);166
iceTimer = setTimeout(() => void finish('30-second ICE deadline', true), 30000);167
controls();168
} catch (error) { log('error', { name: error.name, message: error.message }); await finish(error.message, true); }169
}170
el('connect').onclick = () => void connect(); el('stop').onclick = () => void finish('User stop');171
el('save').onclick = async () => {172
await snapshot();173
const value = { capturedAt: new Date().toISOString(), userAgent: navigator.userAgent, secureContext: isSecureContext,174
state: el('state').textContent, sent, received, candidates, selectedPair, samples, events: entries };175
const link = document.createElement('a'), url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' }));176
link.href = url; link.download = `sigil-webrtc-${Date.now()}.json`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);177
};178
for (const event of ['online', 'offline']) window.addEventListener(event, network);179
navigator.connection?.addEventListener('change', network); document.addEventListener('visibilitychange', network);180
window.addEventListener('pagehide', () => { channel?.close(); pc?.close(); });181
network(); if (!validToken) log('configuration-error', { reason: 'Use a fresh private session link' });182
window.__rtcSpike = () => ({ state: el('state').textContent, sent, received, selectedPair, candidates, events: entries, samples });183
})();184
</script>185
</html>