AtlatestRepositorysigil-http3
1// The package supplies ICE/DTLS/SCTP/DCEP. This file supplies bounded spike policy.
2import { createServer } from 'node:http';
3import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
4import { BlockList, isIP } from 'node:net';
5import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6import { join, resolve } from 'node:path';
7import { RTCPeerConnection, UdpTransport } from 'werift';
8
9const check = (value, message) => { if (!value) throw new Error(message); };
10const hash = value => createHash('sha256').update(value).digest('hex');
11const pause = ms => new Promise(done => setTimeout(done, ms));
12export const icePorts = Object.freeze([44000, 44009]);
14export 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 };
34export 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 if (config.admit && !config.admit()) { reply(503, {}); return; }
139 const supplied = request.headers.authorization?.match(/^Bearer ([0-9a-f]{64})$/)?.[1];
140 if (!arm || arm.used || arm.expiresAt < Date.now() || !supplied ||
141 !timingSafeEqual(Buffer.from(supplied, 'hex'), arm.token)) { reply(401, {}); return; }
142 if (active || stopped) { reply(409, {}); return; }
143 arm.used = true; // Consume before asynchronous body/SDP handling.
144 let bytes = 0; const chunks = [];
145 try {
146 for await (const chunk of request) { bytes += chunk.length; check(bytes <= 73728, 'Request body exceeds limit'); chunks.push(chunk); }
147 const offer = JSON.parse(Buffer.concat(chunks).toString('utf8'));
148 check(!config.admit || config.admit(), 'Host allowance ended before offer admission');
149 check(offer.type === 'offer', 'Expected offer');
150 writeFileSync(join(directory, arm.id + '-offer.json'), JSON.stringify(offer), { mode: 0o600, flag: 'wx' });
151 const value = candidateInventory(offer.sdp, ip => arm.allow.check(ip, 'ipv6'));
152 log('phone-candidates', { inventory: value.inventory, arm: arm.name });
153 check(value.inventory.some(c => c.accepted), 'No usable configured UDP IPv6 candidate');
154 const pc = new RTCPeerConnection({ iceServers: [], iceUseIpv4: false, iceUseIpv6: true,
155 iceUseTcp: false, iceTcpPassive: false, iceInterfaceAddresses: { udp6: config.bindAddress },
156 icePortRange: [...icePorts], maxMessageSize: 1024, codecs: { audio: [], video: [] } });
157 active = { pc, allow: arm.allow, arm: arm.name, echoMessages: 0 };
158 peerTimer = setTimeout(() => void closePeer('90-second peer limit'), 90000);
159 iceTimer = setTimeout(() => void closePeer('30-second ICE limit'), 30000);
160 pc.onDataChannel.subscribe(channel => {
161 if (channel.label !== 'sigil-echo') { void closePeer('Unexpected channel label'); return; }
162 log('data-channel', { label: channel.label });
163 channel.stateChange.subscribe(value => {
164 log('channel-state', { state: value });
165 if (value === 'open') clearTimeout(iceTimer);
166 });
167 channel.onMessage.subscribe(message => {
168 if (!active?.pc || !Buffer.isBuffer(message) || message.length !== 16 || active.echoMessages >= 512 || channel.bufferedAmount > 8192) {
169 void closePeer('Echo bound exceeded'); return;
170 }
171 active.echoMessages++; counters.echoMessages++; counters.echoBytes += message.length; channel.send(message);
172 log('echo', { bytes: message.length, count: counters.echoMessages });
173 });
174 });
175 const snapshot = () => void selectedStats().catch(error => { fatal ??= error; void close(); });
176 pc.connectionStateChange.subscribe(state => { log('connection-state', { state }); snapshot(); });
177 await pc.setRemoteDescription({ type: 'offer', sdp: value.sdp });
178 // werift 0.25.1's setter reintroduces Google when no STUN is specified.
179 // Clear its exposed per-transport discovery fields before gathering.
180 // Keep full ICE and all peer-to-peer connectivity/consent checks enabled.
181 for (const transport of pc.iceTransports) {
182 transport.connection.stunServer = undefined;
183 transport.connection.turnServer = undefined;
184 }
185 check(pc.iceTransports.every(t => !t.connection.stunServer && !t.connection.turnServer), 'Phantom STUN/TURN discovery must be absent');
186 const answer = await pc.createAnswer();
187 await Promise.race([pc.setLocalDescription(answer), pause(5000).then(() => { throw new Error('Phantom gather deadline'); })]);
188 check(pc.iceTransports.every(t => !t.connection.stunServer && !t.connection.turnServer), 'Phantom discovery configuration changed during gathering');
189 const local = pc.iceTransports.flatMap(t => t.localCandidates);
190 check(local.length > 0 && local.every(c => c.type === 'host' && c.ip === config.bindAddress && c.protocol === 'udp' &&
191 c.port >= icePorts[0] && c.port <= icePorts[1]), 'Unexpected Phantom candidate');
192 log('phantom-candidates', { candidates: local });
193 const result = { type: pc.localDescription.type, sdp: pc.localDescription.sdp };
194 writeFileSync(join(directory, arm.id + '-answer.json'), JSON.stringify(result), { mode: 0o600, flag: 'wx' });
195 statsTimer = setInterval(snapshot, 1000);
196 reply(200, result);
197 } catch (error) {
198 log('signaling-error', { message: error.message }); await closePeer('Signaling failure'); reply(422, { error: error.message });
199 }
200 });
201 server.headersTimeout = 5000; server.requestTimeout = 10000; server.keepAliveTimeout = 1000; server.maxConnections = 8;
202 server.on('connection', socket => { httpSockets.add(socket); socket.once('close', () => httpSockets.delete(socket)); socket.setTimeout(12000, () => socket.destroy()); });
203 await new Promise((done, reject) => { server.once('error', reject); server.listen(config.signalPort ?? 0, '127.0.0.1', done); });
204 origin = config.scope === 'gate' ? `http://127.0.0.1:${server.address().port}` : (config.origin ?? process.env.HTTP3_PAGE_ORIGIN ?? 'https://example.com');
205 UdpTransport.init = tracedInit;
206 const lifetime = setTimeout(() => void close(), config.lifetimeSeconds * 1000);
207 function armSession({ name, address, homePrefix = false }) {
208 check(!stopped && !active && (!arm || arm.used || arm.expiresAt < Date.now()), 'Peer/session is busy');
209 check(isIP(address) === 6 && (config.scope === 'gate' || /^[23]/.test(address)), 'Expected current configured peer IPv6');
210 const allow = new BlockList(); if (homePrefix) allow.addSubnet(address, 64, 'ipv6'); else allow.addAddress(address, 'ipv6');
211 const token = randomBytes(32), id = hash(token).slice(0, 16);
212 arm = { token, allow, id, name, used: false, expiresAt: Date.now() + 300000 };
213 log('session-armed', { id, arm: name, expiresAt: new Date(arm.expiresAt).toISOString() });
214 return { token: token.toString('hex'), expiresAt: new Date(arm.expiresAt).toISOString(), id,
215 phoneURL: origin + '/wt-spike/webrtc.html#session=' + token.toString('hex') };
216 }
217 return { server, origin, armSession, close, closePeer, records, counters,
218 get selected() { return selected; }, get fatal() { return fatal; } };