Commit02dfff98Recorded19 Oct 2026Repositorysigil-http3

Add bounded IPv6 WebRTC peer, automatic signaling page and Chrome gate

Changed
 scripts/phantom-webrtc-gate.sh  |  10 ++++
 spikes/webrtc/gate.mjs          | 128 +++++++++++++++++++++++++++++++++++++++++
 spikes/webrtc/package-lock.json | 498 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 spikes/webrtc/peer.mjs          | 209 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 spikes/webrtc/webrtc.html       | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 1030 insertions(+)
Diff
scripts/phantom-webrtc-gate.shadded
@@ -0,0 +1,10 @@
+1
#!/usr/bin/env bash
+2
set -euo pipefail
+3
cd "$(dirname "$0")/.."
+4
umask 077
+5
mkdir -p build/webrtc-gate
+6
trap 'printf "RESULT webrtc-gate rc=%s\n" "$?"' EXIT
+7
node --check spikes/webrtc/peer.mjs
+8
node --check spikes/webrtc/gate.mjs
+9
(cd spikes/webrtc && timeout --foreground 300 npm ci --ignore-scripts --no-audit --no-fund) > build/webrtc-gate/npm-ci.log 2>&1
+10
timeout --foreground 80 node spikes/webrtc/gate.mjs
spikes/webrtc/gate.mjsadded
@@ -0,0 +1,128 @@
+1
// Linux real Chrome gate. No public-host connection, tunnel or root rule.
+2
import assert from 'node:assert/strict';
+3
import { spawn, execFileSync } from 'node:child_process';
+4
import { accessSync, constants, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+5
import { hostname, networkInterfaces } from 'node:os';
+6
import { resolve, join } from 'node:path';
+7
import { identity, sameIdentity } from '../../scripts/echo-lifecycle.mjs';
+8
import { startPeer, candidateInventory } from './peer.mjs';
+9
+10
const directory = resolve('build/webrtc-gate'); mkdirSync(directory, { mode: 0o700 });
+11
const pause = ms => new Promise(done => setTimeout(done, ms));
+12
let interrupted = false, app, browser, closed = false, browserError = '', admissionTimer;
+13
const interrupt = () => { interrupted = true; };
+14
process.on('SIGTERM', interrupt); process.on('SIGINT', interrupt);
+15
const timeout = setTimeout(interrupt, 60000);
+16
const admitted = new Map();
+17
function admit(pid) {
+18
const value = identity(pid); if (!value || value.uid !== process.getuid()) return;
+19
const previous = admitted.get(pid); if (previous && !sameIdentity(previous, value)) return;
+20
admitted.set(pid, value);
+21
try { for (const child of readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8').trim().split(/\s+/).filter(Boolean)) admit(Number(child)); } catch {}
+22
}
+23
function signalTree(signal) {
+24
for (const value of [...admitted.values()].reverse()) {
+25
const now = identity(value.pid);
+26
if (sameIdentity(value, now) && now.state !== 'Z') try { process.kill(value.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+27
}
+28
}
+29
const receipt = { mode: 'real-chrome-webrtc', passed: false, sourceRevision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() };
+30
let browserDone;
+31
try {
+32
const sample = 'v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=candidate:1 1 UDP 1 test.local 45000 typ host\r\na=candidate:2 1 UDP 2 192.0.2.1 45001 typ srflx\r\na=candidate:3 1 UDP 3 2001:db8::1 45002 typ srflx\r\na=candidate:4 1 UDP 4 2001:db8::2 45003 typ host\r\n';
+33
const filtered = candidateInventory(sample, address => address === '2001:db8::1');
+34
assert.equal(filtered.inventory.filter(c => c.accepted).length, 1);
+35
assert.ok(filtered.sdp.includes('2001:db8::1') && !filtered.sdp.includes('test.local') && !filtered.sdp.includes('2001:db8::2'));
+36
const bindAddress = networkInterfaces()[process.env.HTTP3_INTERFACE]?.find(a => a.family === 'IPv6' && /^[23]/.test(a.address) && !a.internal)?.address;
+37
assert.ok(bindAddress, 'No global IPv6 on configured physical interface');
+38
app = await startPeer({ scope: 'gate', bindAddress, signalPort: 0, directory: join(directory, 'peer'), lifetimeSeconds: 60 });
+39
const arm = app.armSession({ name: 'phantom-chrome', address: bindAddress });
+40
assert.ok(Date.parse(arm.expiresAt) <= Date.now() + 300000);
+41
const chrome = ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']
+42
.flatMap(n => process.env.PATH.split(':').map(p => join(p, n)))
+43
.find(p => { try { accessSync(p, constants.X_OK); return true; } catch { return false; } });
+44
assert.ok(chrome, 'Chrome not found');
+45
browser = spawn(chrome, ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run',
+46
'--no-default-browser-check', '--disable-background-networking', '--disable-breakpad', '--disable-crash-reporter',
+47
'--remote-debugging-pipe', `--user-data-dir=${directory}/profile`, `--log-net-log=${directory}/net-export.json`,
+48
'--net-log-capture-mode=Default'], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
+49
browserDone = new Promise(done => browser.once('close', () => { closed = true; done(); }));
+50
browser.on('error', error => { browserError += error.message; interrupt(); });
+51
browser.stderr.on('data', bytes => { browserError += bytes.toString().slice(0, Math.max(0, 1048576 - browserError.length)); });
+52
admit(browser.pid); admissionTimer = setInterval(() => admit(browser.pid), 100);
+53
let sequence = 0, pending = ''; const requests = new Map();
+54
browser.stdio[3].on('error', interrupt);
+55
browser.stdio[4].on('data', bytes => {
+56
pending += bytes.toString();
+57
if (pending.length > 4194304) { interrupt(); return; }
+58
for (;;) {
+59
const end = pending.indexOf('\0'); if (end < 0) break;
+60
const message = JSON.parse(pending.slice(0, end)); pending = pending.slice(end + 1);
+61
const request = requests.get(message.id);
+62
if (request) { requests.delete(message.id); clearTimeout(request.timer); message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.done(message.result); }
+63
}
+64
});
+65
const cdp = (method, params = {}, sessionId) => new Promise((done, reject) => {
+66
const id = ++sequence, timer = setTimeout(() => { requests.delete(id); reject(new Error('DevTools deadline: ' + method)); }, 8000);
+67
requests.set(id, { done, reject, timer });
+68
browser.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
+69
});
+70
receipt.browser = await cdp('Browser.getVersion');
+71
const target = await cdp('Target.createTarget', { url: 'about:blank' });
+72
const { sessionId } = await cdp('Target.attachToTarget', { targetId: target.targetId, flatten: true });
+73
const evaluate = async expression => {
+74
const r = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId);
+75
if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails)); return r.result?.value;
+76
};
+77
await cdp('Page.enable', {}, sessionId);
+78
await cdp('Page.navigate', { url: arm.phoneURL }, sessionId);
+79
const waitFor = async predicate => {
+80
const end = Date.now() + 35000; let value;
+81
while (!interrupted && !closed && Date.now() < end) {
+82
value = await evaluate('window.__rtcSpike?.()');
+83
if (predicate(value)) return value;
+84
if (value?.state === 'failed') throw new Error('Page failed: ' + JSON.stringify(value.events.slice(-6)));
+85
await pause(100);
+86
}
+87
throw new Error('WebRTC Chrome gate deadline: ' + JSON.stringify(value));
+88
};
+89
await waitFor(v => v?.state === 'idle');
+90
await evaluate(`Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => false }); window.dispatchEvent(new Event('offline'))`);
+91
assert.equal(await evaluate("document.getElementById('connect').disabled"), true);
+92
await evaluate("document.getElementById('connect').dispatchEvent(new Event('click'))");
+93
assert.equal(await evaluate('window.__rtcSpike().events.some(e => e.kind === "offer-ready")'), false);
+94
await evaluate(`Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => true }); window.dispatchEvent(new Event('online'))`);
+95
assert.equal(await evaluate("document.getElementById('connect').disabled"), false);
+96
await evaluate("document.getElementById('connect').click()");
+97
receipt.page = await waitFor(v => v?.state === 'open' && v.received >= 8 && v.selectedPair);
+98
assert.equal(receipt.page.selectedPair.remote.candidateType, 'host');
+99
assert.equal(receipt.page.selectedPair.remote.protocol, 'udp');
+100
assert.ok(receipt.page.selectedPair.remote.address?.includes(':'));
+101
const replay = await fetch(app.origin + '/wt-spike/signal', { method: 'POST', headers: { Origin: app.origin,
+102
'Content-Type': 'application/json', Authorization: 'Bearer ' + arm.token }, body: '{}' });
+103
assert.equal(replay.status, 401, 'Session token was reused');
+104
await evaluate("document.getElementById('stop').click()");
+105
await waitFor(v => v?.state === 'stopped');
+106
assert.ok(app.counters.echoMessages >= 8);
+107
assert.ok(app.counters.txChecks > 0 && app.counters.rxChecks > 0 && app.counters.txResponses > 0 && app.counters.rxResponses > 0);
+108
assert.ok(app.selected);
+109
receipt.tokenReplayRejected = true; receipt.offlineGate = true; receipt.onlineRecovery = true;
+110
receipt.passed = true;
+111
} catch (error) { receipt.error = error.message; process.exitCode = 1; }
+112
finally {
+113
clearTimeout(timeout); clearInterval(admissionTimer);
+114
if (browser) {
+115
admit(browser.pid);
+116
if (!closed) { signalTree('SIGTERM'); await Promise.race([browserDone, pause(2000)]); }
+117
signalTree('SIGKILL');
+118
await Promise.race([browserDone, pause(2000)]);
+119
receipt.chromeReaped = closed && [...admitted.values()].every(v => { const now = identity(v.pid); return !sameIdentity(v, now) || now.state === 'Z'; });
+120
}
+121
try { receipt.peer = await app?.close(); } catch (error) { receipt.cleanupError = error.message; process.exitCode = 1; }
+122
receipt.peerClosed = receipt.peer?.socketsClosed === true;
+123
if (!receipt.chromeReaped || !receipt.peerClosed) { receipt.passed = false; process.exitCode = 1; }
+124
writeFileSync(join(directory, 'chrome.stderr'), browserError, { mode: 0o600 });
+125
writeFileSync(join(directory, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n', { mode: 0o600 });
+126
process.off('SIGTERM', interrupt); process.off('SIGINT', interrupt);
+127
console.log(`RESULT webrtc-chrome passed=${receipt.passed} chrome-reaped=${receipt.chromeReaped} peer-closed=${receipt.peerClosed}`);
+128
}
spikes/webrtc/package-lock.jsonadded
@@ -0,0 +1,498 @@
+1
{
+2
"name": "sigil-webrtc-feasibility-spike",
+3
"version": "0.0.0",
+4
"lockfileVersion": 3,
+5
"requires": true,
+6
"packages": {
+7
"": {
+8
"name": "sigil-webrtc-feasibility-spike",
+9
"version": "0.0.0",
+10
"dependencies": {
+11
"werift": "0.25.1"
+12
},
+13
"engines": {
+14
"node": "22.14.0"
+15
}
+16
},
+17
"node_modules/@fidm/asn1": {
+18
"version": "1.0.4",
+19
"resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
+20
"integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",
+21
"license": "MIT",
+22
"engines": {
+23
"node": ">= 8"
+24
}
+25
},
+26
"node_modules/@fidm/x509": {
+27
"version": "1.2.1",
+28
"resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",
+29
"integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",
+30
"license": "MIT",
+31
"dependencies": {
+32
"@fidm/asn1": "^1.0.4",
+33
"tweetnacl": "^1.0.1"
+34
},
+35
"engines": {
+36
"node": ">= 8"
+37
}
+38
},
+39
"node_modules/@leichtgewicht/ip-codec": {
+40
"version": "2.0.5",
+41
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
+42
"integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
+43
"license": "MIT"
+44
},
+45
"node_modules/@noble/curves": {
+46
"version": "1.9.7",
+47
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
+48
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
+49
"license": "MIT",
+50
"dependencies": {
+51
"@noble/hashes": "1.8.0"
+52
},
+53
"engines": {
+54
"node": "^14.21.3 || >=16"
+55
},
+56
"funding": {
+57
"url": "https://paulmillr.com/funding/"
+58
}
+59
},
+60
"node_modules/@noble/hashes": {
+61
"version": "1.8.0",
+62
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+63
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
+64
"license": "MIT",
+65
"engines": {
+66
"node": "^14.21.3 || >=16"
+67
},
+68
"funding": {
+69
"url": "https://paulmillr.com/funding/"
+70
}
+71
},
+72
"node_modules/@peculiar/asn1-cms": {
+73
"version": "2.11.0",
+74
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.11.0.tgz",
+75
"integrity": "sha512-SlAiDoT/Cd8qaNmbTt78gqyaEvu2fQd6ML6KWJkdjXGrgDKnHHrusVkfQUelkfinL2p665IIADb0JBixtT8W1g==",
+76
"license": "MIT",
+77
"dependencies": {
+78
"@peculiar/asn1-schema": "^2.11.0",
+79
"@peculiar/asn1-x509": "^2.11.0",
+80
"@peculiar/asn1-x509-attr": "^2.11.0",
+81
"asn1js": "^3.0.10",
+82
"tslib": "^2.8.1"
+83
},
+84
"engines": {
+85
"node": ">=14"
+86
}
+87
},
+88
"node_modules/@peculiar/asn1-csr": {
+89
"version": "2.11.0",
+90
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.11.0.tgz",
+91
"integrity": "sha512-M/ED0yJ05qMK+UADPKnIa8vhAeewOJALSxTAZB7RQ/batRHhIJZkwznCcWAbFO5saHJ1yEQ+m4lncEcG9RnQSg==",
+92
"license": "MIT",
+93
"dependencies": {
+94
"@peculiar/asn1-schema": "^2.11.0",
+95
"@peculiar/asn1-x509": "^2.11.0",
+96
"asn1js": "^3.0.10",
+97
"tslib": "^2.8.1"
+98
},
+99
"engines": {
+100
"node": ">=14"
+101
}
+102
},
+103
"node_modules/@peculiar/asn1-ecc": {
+104
"version": "2.11.0",
+105
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.11.0.tgz",
+106
"integrity": "sha512-jj1alGEKev7/un+cI+exyVK9m31lmP7cCBMCZuCb0wkFQH2zmKmJzNiG4wqXFNzlcP8timHLnzf3lV3OxBpb/Q==",
+107
"license": "MIT",
+108
"dependencies": {
+109
"@peculiar/asn1-schema": "^2.11.0",
+110
"@peculiar/asn1-x509": "^2.11.0",
+111
"asn1js": "^3.0.10",
+112
"tslib": "^2.8.1"
+113
},
+114
"engines": {
+115
"node": ">=14"
+116
}
+117
},
+118
"node_modules/@peculiar/asn1-pfx": {
+119
"version": "2.11.0",
+120
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.11.0.tgz",
+121
"integrity": "sha512-ykSAWRu8KkmzU8LRpk9ZQC3zuLmBEtoSMjIv9XHVamD5W7amqreV5wttKqnvtjWOzzSJQxA/HVT8/tHwpEEGSQ==",
+122
"license": "MIT",
+123
"dependencies": {
+124
"@peculiar/asn1-cms": "^2.11.0",
+125
"@peculiar/asn1-pkcs8": "^2.11.0",
+126
"@peculiar/asn1-rsa": "^2.11.0",
+127
"@peculiar/asn1-schema": "^2.11.0",
+128
"asn1js": "^3.0.10",
+129
"tslib": "^2.8.1"
+130
},
+131
"engines": {
+132
"node": ">=14"
+133
}
+134
},
+135
"node_modules/@peculiar/asn1-pkcs8": {
+136
"version": "2.11.0",
+137
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.11.0.tgz",
+138
"integrity": "sha512-lragjkjQGnQ5luxC+sxoAfAO/jBiQ7hOEGlDKJUk7MC5zY3AzjB2DU0GyPUH1Sswdv10t7DurY0zylOYMLb88w==",
+139
"license": "MIT",
+140
"dependencies": {
+141
"@peculiar/asn1-schema": "^2.11.0",
+142
"@peculiar/asn1-x509": "^2.11.0",
+143
"asn1js": "^3.0.10",
+144
"tslib": "^2.8.1"
+145
},
+146
"engines": {
+147
"node": ">=14"
+148
}
+149
},
+150
"node_modules/@peculiar/asn1-pkcs9": {
+151
"version": "2.11.0",
+152
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.11.0.tgz",
+153
"integrity": "sha512-gDdFjpqV0weJjgNUvueUVf4D8uVbpq+VbG0TsxLAY2QGljAkJyL9qwQ7avol9j0jaYSJ7Ey7v7RZp0M3GTcQSA==",
+154
"license": "MIT",
+155
"dependencies": {
+156
"@peculiar/asn1-cms": "^2.11.0",
+157
"@peculiar/asn1-pfx": "^2.11.0",
+158
"@peculiar/asn1-pkcs8": "^2.11.0",
+159
"@peculiar/asn1-schema": "^2.11.0",
+160
"@peculiar/asn1-x509": "^2.11.0",
+161
"@peculiar/asn1-x509-attr": "^2.11.0",
+162
"asn1js": "^3.0.10",
+163
"tslib": "^2.8.1"
+164
},
+165
"engines": {
+166
"node": ">=14"
+167
}
+168
},
+169
"node_modules/@peculiar/asn1-rsa": {
+170
"version": "2.11.0",
+171
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.11.0.tgz",
+172
"integrity": "sha512-S2sBJmbfI09Kzdt9cEhE6pDNjHpVTkURs+811+PxS8AvsTLxC4woMNRhxHYaIbClkkNfAVt0tZxJdINVfUmzuA==",
+173
"license": "MIT",
+174
"dependencies": {
+175
"@peculiar/asn1-schema": "^2.11.0",
+176
"@peculiar/asn1-x509": "^2.11.0",
+177
"asn1js": "^3.0.10",
+178
"tslib": "^2.8.1"
+179
},
+180
"engines": {
+181
"node": ">=14"
+182
}
+183
},
+184
"node_modules/@peculiar/asn1-schema": {
+185
"version": "2.11.0",
+186
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.0.tgz",
+187
"integrity": "sha512-8xh4avo53/vXO6UEv9yaoJ83hY581geaLTygf61NPIXP5AeIZCPjJhpTaYU23IZkG+NpLN/C9FYzWp7hphIT9A==",
+188
"license": "MIT",
+189
"dependencies": {
+190
"@peculiar/utils": "^2.0.2",
+191
"asn1js": "^3.0.10",
+192
"tslib": "^2.8.1"
+193
},
+194
"engines": {
+195
"node": ">=14"
+196
}
+197
},
+198
"node_modules/@peculiar/asn1-x509": {
+199
"version": "2.11.0",
+200
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.11.0.tgz",
+201
"integrity": "sha512-J1sHAwGNlk+8J+FeR1eLVc6Gq0T9f9ITc3HWyPYgJraoW6U8AJuQiWVJ3SCEpltfTdpOY7fHdHT5oKAsbK/jww==",
+202
"license": "MIT",
+203
"dependencies": {
+204
"@peculiar/asn1-schema": "^2.11.0",
+205
"@peculiar/utils": "^2.0.2",
+206
"asn1js": "^3.0.10",
+207
"tslib": "^2.8.1"
+208
},
+209
"engines": {
+210
"node": ">=14"
+211
}
+212
},
+213
"node_modules/@peculiar/asn1-x509-attr": {
+214
"version": "2.11.0",
+215
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.11.0.tgz",
+216
"integrity": "sha512-Fgvnd9REmLxEj/4cbDP54dNUNUXkzUksXLqEHqs1mHBuSRjSTCUSPM/WQIZYSvrdG7ND9CX1AQtPoIBekhgQSA==",
+217
"license": "MIT",
+218
"dependencies": {
+219
"@peculiar/asn1-schema": "^2.11.0",
+220
"@peculiar/asn1-x509": "^2.11.0",
+221
"asn1js": "^3.0.10",
+222
"tslib": "^2.8.1"
+223
},
+224
"engines": {
+225
"node": ">=14"
+226
}
+227
},
+228
"node_modules/@peculiar/utils": {
+229
"version": "2.0.3",
+230
"resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",
+231
"integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",
+232
"license": "MIT",
+233
"dependencies": {
+234
"tslib": "^2.8.1"
+235
}
+236
},
+237
"node_modules/@peculiar/x509": {
+238
"version": "1.14.3",
+239
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
+240
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
+241
"license": "MIT",
+242
"dependencies": {
+243
"@peculiar/asn1-cms": "^2.6.0",
+244
"@peculiar/asn1-csr": "^2.6.0",
+245
"@peculiar/asn1-ecc": "^2.6.0",
+246
"@peculiar/asn1-pkcs9": "^2.6.0",
+247
"@peculiar/asn1-rsa": "^2.6.0",
+248
"@peculiar/asn1-schema": "^2.6.0",
+249
"@peculiar/asn1-x509": "^2.6.0",
+250
"pvtsutils": "^1.3.6",
+251
"reflect-metadata": "^0.2.2",
+252
"tslib": "^2.8.1",
+253
"tsyringe": "^4.10.0"
+254
},
+255
"engines": {
+256
"node": ">=20.0.0"
+257
}
+258
},
+259
"node_modules/@types/dom-mediacapture-transform": {
+260
"version": "0.1.12",
+261
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
+262
"integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
+263
"license": "MIT",
+264
"dependencies": {
+265
"@types/dom-webcodecs": "*"
+266
}
+267
},
+268
"node_modules/@types/dom-webcodecs": {
+269
"version": "0.1.13",
+270
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
+271
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
+272
"license": "MIT"
+273
},
+274
"node_modules/asn1js": {
+275
"version": "3.1.0",
+276
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
+277
"integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==",
+278
"license": "BSD-3-Clause",
+279
"dependencies": {
+280
"pvtsutils": "^1.3.6",
+281
"pvutils": "^1.2.0",
+282
"tslib": "^2.8.1"
+283
},
+284
"engines": {
+285
"node": ">=12.0.0"
+286
}
+287
},
+288
"node_modules/base64-js": {
+289
"version": "1.5.1",
+290
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+291
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+292
"funding": [
+293
{
+294
"type": "github",
+295
"url": "https://github.com/sponsors/feross"
+296
},
+297
{
+298
"type": "patreon",
+299
"url": "https://www.patreon.com/feross"
+300
},
+301
{
+302
"type": "consulting",
+303
"url": "https://feross.org/support"
+304
}
+305
],
+306
"license": "MIT"
+307
},
+308
"node_modules/buffer": {
+309
"version": "6.0.3",
+310
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+311
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+312
"funding": [
+313
{
+314
"type": "github",
+315
"url": "https://github.com/sponsors/feross"
+316
},
+317
{
+318
"type": "patreon",
+319
"url": "https://www.patreon.com/feross"
+320
},
+321
{
+322
"type": "consulting",
+323
"url": "https://feross.org/support"
+324
}
+325
],
+326
"license": "MIT",
+327
"dependencies": {
+328
"base64-js": "^1.3.1",
+329
"ieee754": "^1.2.1"
+330
}
+331
},
+332
"node_modules/debug": {
+333
"version": "4.4.0",
+334
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
+335
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
+336
"license": "MIT",
+337
"dependencies": {
+338
"ms": "^2.1.3"
+339
},
+340
"engines": {
+341
"node": ">=6.0"
+342
},
+343
"peerDependenciesMeta": {
+344
"supports-color": {
+345
"optional": true
+346
}
+347
}
+348
},
+349
"node_modules/dns-packet": {
+350
"version": "5.6.1",
+351
"resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
+352
"integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
+353
"license": "MIT",
+354
"dependencies": {
+355
"@leichtgewicht/ip-codec": "^2.0.1"
+356
},
+357
"engines": {
+358
"node": ">=6"
+359
}
+360
},
+361
"node_modules/ieee754": {
+362
"version": "1.2.1",
+363
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+364
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+365
"funding": [
+366
{
+367
"type": "github",
+368
"url": "https://github.com/sponsors/feross"
+369
},
+370
{
+371
"type": "patreon",
+372
"url": "https://www.patreon.com/feross"
+373
},
+374
{
+375
"type": "consulting",
+376
"url": "https://feross.org/support"
+377
}
+378
],
+379
"license": "BSD-3-Clause"
+380
},
+381
"node_modules/mediabunny": {
+382
"version": "1.61.6",
+383
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.61.6.tgz",
+384
"integrity": "sha512-VHEZ53/7jGl4dQ+uOdndsZufFYwEUFWv9UXgvrGun3OapyzoqI9iaPOD7z3xxY/nAttLZBNwswgJzMtGJAquOQ==",
+385
"license": "MPL-2.0",
+386
"workspaces": [
+387
".",
+388
"packages/*"
+389
],
+390
"dependencies": {
+391
"@types/dom-mediacapture-transform": "^0.1.11",
+392
"@types/dom-webcodecs": "0.1.13"
+393
},
+394
"funding": {
+395
"type": "individual",
+396
"url": "https://github.com/sponsors/Vanilagy"
+397
}
+398
},
+399
"node_modules/ms": {
+400
"version": "2.1.3",
+401
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+402
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+403
"license": "MIT"
+404
},
+405
"node_modules/multicast-dns": {
+406
"version": "7.2.5",
+407
"resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",
+408
"integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",
+409
"license": "MIT",
+410
"dependencies": {
+411
"dns-packet": "^5.2.2",
+412
"thunky": "^1.0.2"
+413
},
+414
"bin": {
+415
"multicast-dns": "cli.js"
+416
}
+417
},
+418
"node_modules/pvtsutils": {
+419
"version": "1.3.6",
+420
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
+421
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
+422
"license": "MIT",
+423
"dependencies": {
+424
"tslib": "^2.8.1"
+425
}
+426
},
+427
"node_modules/pvutils": {
+428
"version": "1.2.0",
+429
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
+430
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
+431
"license": "MIT",
+432
"engines": {
+433
"node": ">=16.0.0"
+434
}
+435
},
+436
"node_modules/reflect-metadata": {
+437
"version": "0.2.2",
+438
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
+439
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
+440
"license": "Apache-2.0"
+441
},
+442
"node_modules/thunky": {
+443
"version": "1.1.0",
+444
"resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
+445
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
+446
"license": "MIT"
+447
},
+448
"node_modules/tslib": {
+449
"version": "2.8.1",
+450
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+451
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+452
"license": "0BSD"
+453
},
+454
"node_modules/tsyringe": {
+455
"version": "4.10.0",
+456
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
+457
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
+458
"license": "MIT",
+459
"dependencies": {
+460
"tslib": "^1.9.3"
+461
},
+462
"engines": {
+463
"node": ">= 6.0.0"
+464
}
+465
},
+466
"node_modules/tsyringe/node_modules/tslib": {
+467
"version": "1.14.1",
+468
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
+469
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
+470
"license": "0BSD"
+471
},
+472
"node_modules/tweetnacl": {
+473
"version": "1.0.3",
+474
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
+475
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
+476
"license": "Unlicense"
+477
},
+478
"node_modules/werift": {
+479
"version": "0.25.1",
+480
"resolved": "https://registry.npmjs.org/werift/-/werift-0.25.1.tgz",
+481
"integrity": "sha512-S46MVcqeSKKoOrQJI2mRkVB2oCmsYzTEs6S86BBgZ5YIZtAf7uAhO8XedBl/Jp6pYUt8aXfLuAYpcxSzMpxTMA==",
+482
"license": "MIT",
+483
"dependencies": {
+484
"@fidm/x509": "^1.2.1",
+485
"@noble/curves": "^1.8.1",
+486
"@peculiar/x509": "^1.12.3",
+487
"buffer": "^6.0.3",
+488
"debug": "4.4.0",
+489
"mediabunny": "^1.45.2",
+490
"multicast-dns": "^7.2.5",
+491
"tweetnacl": "^1.0.3"
+492
},
+493
"engines": {
+494
"node": ">=22"
+495
}
+496
}
+497
}
+498
}
spikes/webrtc/peer.mjsadded
@@ -0,0 +1,209 @@
+1
// The package supplies ICE/DTLS/SCTP/DCEP. This file supplies bounded spike policy.
+2
import { createServer } from 'node:http';
+3
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
+4
import { BlockList, isIP } from 'node:net';
+5
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+6
import { join, resolve } from 'node:path';
+7
import { RTCPeerConnection, UdpTransport } from 'werift';
+8
+9
const check = (value, message) => { if (!value) throw new Error(message); };
+10
const hash = value => createHash('sha256').update(value).digest('hex');
+11
const pause = ms => new Promise(done => setTimeout(done, ms));
+12
export const icePorts = Object.freeze([44000, 44009]);
+13
+14
export function candidateInventory(sdp, allowed) {
+15
check(typeof sdp === 'string' && Buffer.byteLength(sdp) <= 65536, 'SDP exceeds limit');
+16
check(sdp.split('\n').filter(l => l.startsWith('m=')).length === 1 && /^m=application /m.test(sdp), 'One data-only media section required');
+17
let count = 0;
+18
const inventory = [], kept = [];
+19
for (const line of sdp.split(/\r?\n/)) {
+20
if (!line.startsWith('a=candidate:')) { kept.push(line); continue; }
+21
check(++count <= 32 && line.length <= 2048, 'Too many/oversized candidates');
+22
const parts = line.slice(12).trim().split(/\s+/);
+23
const [foundation, component, protocol, priority, address, port, typ, type] = parts;
+24
const accepted = component === '1' && protocol?.toLowerCase() === 'udp' && typ === 'typ' &&
+25
['host', 'srflx', 'prflx'].includes(type) && /^[0-9]+$/.test(port ?? '') &&
+26
Number(port) >= 1024 && Number(port) <= 65535 && isIP(address) === 6 && allowed(address);
+27
inventory.push({ foundation, component, protocol, priority, address, port: Number(port), type,
+28
mdns: address?.endsWith('.local') ?? false, accepted });
+29
if (accepted) kept.push(line);
+30
}
+31
return { sdp: kept.join('\r\n'), inventory };
+32
}
+33
+34
export async function startPeer(config) {
+35
check(isIP(config.bindAddress) === 6 && ((config.scope === 'gate' && config.bindAddress === '::1') ||
+36
/^[23][0-9a-f:]+$/i.test(config.bindAddress)), 'Expected configured numeric IPv6 bind');
+37
check(config.scope === 'gate' || config.scope === 'phone', 'Invalid peer scope');
+38
check(config.lifetimeSeconds >= 1 && config.lifetimeSeconds <= 3600, 'Invalid helper lifetime');
+39
const directory = resolve(config.directory); mkdirSync(directory, { mode: 0o700 });
+40
const baseline = performance.now(), records = [], sockets = new Set(), counters = { txChecks: 0, rxChecks: 0, txResponses: 0, rxResponses: 0, udpReceived: 0, echoMessages: 0, echoBytes: 0 };
+41
let stopped = false, fatal, arm, active, selected = null, origin, writeCount = 0;
+42
const logPath = join(directory, 'events.jsonl'); writeFileSync(logPath, '', { mode: 0o600, flag: 'wx' });
+43
const log = (kind, details = {}) => {
+44
if (++writeCount > 20000) { fatal ??= new Error('Trace exhausted'); setImmediate(() => void close()); return; }
+45
const row = { utc: new Date().toISOString(), elapsedMs: +(performance.now() - baseline).toFixed(3), kind, ...details };
+46
records.push(row); appendFileSync(logPath, JSON.stringify(row) + '\n');
+47
};
+48
const allowed = address => active?.allow?.check(address, 'ipv6') === true;
+49
function packet(direction, socket, bytes, remote, result) {
+50
const local = socket.address();
+51
const stun = bytes.length >= 20 && (bytes[0] & 0xc0) === 0 && bytes.readUInt32BE(4) === 0x2112a442;
+52
const type = stun ? bytes.readUInt16BE(0) : null;
+53
if (direction === 'rx') counters.udpReceived++;
+54
if (type === 1) counters[direction === 'tx' ? 'txChecks' : 'rxChecks']++;
+55
if (type === 0x101 || type === 0x111) counters[direction === 'tx' ? 'txResponses' : 'rxResponses']++;
+56
log('udp-' + direction, { local: [local.address, local.port], remote, bytes: bytes.length,
+57
stunType: type, transactionId: stun ? bytes.subarray(8, 20).toString('hex') : null, result });
+58
}
+59
// Observe the pinned library's real UDP socket; no ICE/crypto algorithm patch.
+60
const originalInit = UdpTransport.init;
+61
const tracedInit = async function (...args) {
+62
const transport = await originalInit.apply(this, args);
+63
const socket = transport.socket, local = socket.address();
+64
if (args[0] !== 'udp6' || local.address !== config.bindAddress || local.port < icePorts[0] || local.port > icePorts[1]) {
+65
await transport.close(); throw new Error('ICE socket exceeded configured bind/range');
+66
}
+67
sockets.add(socket); socket.once('close', () => sockets.delete(socket));
+68
log('socket-bound', { local: [local.address, local.port] });
+69
const send = socket.send;
+70
socket.send = function (bytes, port, address, callback) {
+71
check(Buffer.isBuffer(bytes) && isIP(address) === 6 && allowed(address), 'ICE output outside armed peer scope');
+72
packet('tx', socket, bytes, [address, port], 'submitted');
+73
return send.call(this, bytes, port, address, (error, size) => {
+74
log('udp-send-result', { local: [local.address, local.port], remote: [address, port], bytes: bytes.length,
+75
result: error ? 'error' : size, code: error?.code });
+76
if (error) { fatal ??= error; void close(); }
+77
callback?.(error, size);
+78
});
+79
};
+80
socket.prependListener('message', (bytes, peer) => packet('rx', socket, bytes, [peer.address, peer.port]));
+81
socket.on('error', error => { log('socket-error', { code: error.code }); fatal ??= error; void close(); });
+82
return transport;
+83
};
+84
let peerTimer, iceTimer, statsTimer;
+85
async function selectedStats() {
+86
if (!active?.pc) return;
+87
for (const transport of active.pc.iceTransports) {
+88
const pair = transport.getSelectedCandidatePair();
+89
if (pair) {
+90
const value = JSON.stringify(pair);
+91
if (value !== JSON.stringify(selected)) { selected = pair; log('selected-pair', { pair }); }
+92
}
+93
const connection = transport.connection;
+94
log('ice-state', { state: transport.state, candidates: connection.remoteCandidates.map(c => ({ address: c.host, port: c.port, type: c.type })) });
+95
}
+96
}
+97
async function closePeer(reason) {
+98
clearTimeout(peerTimer); clearTimeout(iceTimer); clearInterval(statsTimer);
+99
if (!active) return;
+100
const pc = active.pc;
+101
if (pc) {
+102
await selectedStats().catch(() => {});
+103
active.pc = null;
+104
await pc.close(); log('peer-closed', { reason });
+105
}
+106
active = null;
+107
}
+108
const httpSockets = new Set();
+109
let closePromise;
+110
async function close() {
+111
if (closePromise) return closePromise;
+112
stopped = true;
+113
closePromise = (async () => {
+114
clearTimeout(lifetime);
+115
await closePeer(fatal?.message ?? 'helper-stop');
+116
await new Promise(done => { server.close(done); for (const socket of httpSockets) socket.destroy(); });
+117
UdpTransport.init = originalInit;
+118
check(sockets.size === 0, 'ICE socket not reaped');
+119
const summary = { stopped: true, fatal: fatal?.message, counters, selected, records: records.length, socketsClosed: true };
+120
writeFileSync(join(directory, 'result.json'), JSON.stringify(summary, null, 2) + '\n', { mode: 0o600 });
+121
return summary;
+122
})();
+123
return closePromise;
+124
}
+125
const server = createServer(async (request, response) => {
+126
const reply = (code, value) => {
+127
if (response.destroyed) return;
+128
response.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
+129
response.end(JSON.stringify(value));
+130
};
+131
if (config.scope === 'gate' && request.method === 'GET' && request.url === '/wt-spike/webrtc.html') {
+132
response.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store' });
+133
response.end(readFileSync(new URL('./webrtc.html', import.meta.url))); return;
+134
}
+135
if (request.url !== '/wt-spike/signal') { reply(404, {}); return; }
+136
if (request.method !== 'POST') { reply(405, {}); return; }
+137
if (request.headers.origin !== origin || request.headers['content-type'] !== 'application/json') { reply(403, {}); return; }
+138
const supplied = request.headers.authorization?.match(/^Bearer ([0-9a-f]{64})$/)?.[1];
+139
if (!arm || arm.used || arm.expiresAt < Date.now() || !supplied ||
+140
!timingSafeEqual(Buffer.from(supplied, 'hex'), arm.token)) { reply(401, {}); return; }
+141
if (active || stopped) { reply(409, {}); return; }
+142
arm.used = true; // Consume before asynchronous body/SDP handling.
+143
let bytes = 0; const chunks = [];
+144
try {
+145
for await (const chunk of request) { bytes += chunk.length; check(bytes <= 73728, 'Request body exceeds limit'); chunks.push(chunk); }
+146
const offer = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+147
check(offer.type === 'offer', 'Expected offer');
+148
writeFileSync(join(directory, arm.id + '-offer.json'), JSON.stringify(offer), { mode: 0o600, flag: 'wx' });
+149
const value = candidateInventory(offer.sdp, ip => arm.allow.check(ip, 'ipv6'));
+150
log('phone-candidates', { inventory: value.inventory, arm: arm.name });
+151
check(value.inventory.some(c => c.accepted), 'No usable configured UDP IPv6 candidate');
+152
const pc = new RTCPeerConnection({ iceServers: [], iceUseIpv4: false, iceUseIpv6: true,
+153
iceUseTcp: false, iceTcpPassive: false, iceInterfaceAddresses: { udp6: config.bindAddress },
+154
icePortRange: [...icePorts], maxMessageSize: 1024, codecs: { audio: [], video: [] } });
+155
active = { pc, allow: arm.allow, arm: arm.name, echoMessages: 0 };
+156
peerTimer = setTimeout(() => void closePeer('90-second peer limit'), 90000);
+157
iceTimer = setTimeout(() => void closePeer('30-second ICE limit'), 30000);
+158
pc.onDataChannel.subscribe(channel => {
+159
if (channel.label !== 'sigil-echo') { void closePeer('Unexpected channel label'); return; }
+160
log('data-channel', { label: channel.label });
+161
channel.stateChange.subscribe(value => {
+162
log('channel-state', { state: value });
+163
if (value === 'open') clearTimeout(iceTimer);
+164
});
+165
channel.onMessage.subscribe(message => {
+166
if (!active?.pc || !Buffer.isBuffer(message) || message.length !== 16 || active.echoMessages >= 512 || channel.bufferedAmount > 8192) {
+167
void closePeer('Echo bound exceeded'); return;
+168
}
+169
active.echoMessages++; counters.echoMessages++; counters.echoBytes += message.length; channel.send(message);
+170
log('echo', { bytes: message.length, count: counters.echoMessages });
+171
});
+172
});
+173
const snapshot = () => void selectedStats().catch(error => { fatal ??= error; void close(); });
+174
pc.connectionStateChange.subscribe(state => { log('connection-state', { state }); snapshot(); });
+175
await pc.setRemoteDescription({ type: 'offer', sdp: value.sdp });
+176
check(pc.iceTransports.every(t => !t.connection.stunServer && !t.connection.turnServer), 'Phantom STUN/TURN discovery must be absent');
+177
const answer = await pc.createAnswer();
+178
await Promise.race([pc.setLocalDescription(answer), pause(5000).then(() => { throw new Error('Phantom gather deadline'); })]);
+179
const local = pc.iceTransports.flatMap(t => t.localCandidates);
+180
check(local.length > 0 && local.every(c => c.type === 'host' && c.ip === config.bindAddress && c.protocol === 'udp' &&
+181
c.port >= icePorts[0] && c.port <= icePorts[1]), 'Unexpected Phantom candidate');
+182
log('phantom-candidates', { candidates: local });
+183
const result = { type: pc.localDescription.type, sdp: pc.localDescription.sdp };
+184
writeFileSync(join(directory, arm.id + '-answer.json'), JSON.stringify(result), { mode: 0o600, flag: 'wx' });
+185
statsTimer = setInterval(snapshot, 1000);
+186
reply(200, result);
+187
} catch (error) {
+188
log('signaling-error', { message: error.message }); await closePeer('Signaling failure'); reply(422, { error: error.message });
+189
}
+190
});
+191
server.headersTimeout = 5000; server.requestTimeout = 10000; server.keepAliveTimeout = 1000; server.maxConnections = 8;
+192
server.on('connection', socket => { httpSockets.add(socket); socket.once('close', () => httpSockets.delete(socket)); socket.setTimeout(12000, () => socket.destroy()); });
+193
await new Promise((done, reject) => { server.once('error', reject); server.listen(config.signalPort ?? 0, '127.0.0.1', done); });
+194
origin = config.scope === 'gate' ? `http://127.0.0.1:${server.address().port}` : 'https://example.com';
+195
UdpTransport.init = tracedInit;
+196
const lifetime = setTimeout(() => void close(), config.lifetimeSeconds * 1000);
+197
function armSession({ name, address, homePrefix = false }) {
+198
check(!stopped && !active && (!arm || arm.used || arm.expiresAt < Date.now()), 'Peer/session is busy');
+199
check(isIP(address) === 6 && (config.scope === 'gate' || /^[23]/.test(address)), 'Expected current configured peer IPv6');
+200
const allow = new BlockList(); if (homePrefix) allow.addSubnet(address, 64, 'ipv6'); else allow.addAddress(address, 'ipv6');
+201
const token = randomBytes(32), id = hash(token).slice(0, 16);
+202
arm = { token, allow, id, name, used: false, expiresAt: Date.now() + 300000 };
+203
log('session-armed', { id, arm: name, expiresAt: new Date(arm.expiresAt).toISOString() });
+204
return { token: token.toString('hex'), expiresAt: new Date(arm.expiresAt).toISOString(), id,
+205
phoneURL: origin + '/wt-spike/webrtc.html#session=' + token.toString('hex') };
+206
}
+207
return { server, origin, armSession, close, closePeer, records, counters,
+208
get selected() { return selected; }, get fatal() { return fatal; } };
+209
}
spikes/webrtc/webrtc.htmladded
@@ -0,0 +1,185 @@
+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>