AtlatestRepositorysigil-nat
1
import { createSocket } from 'node:dgram';2
import { randomBytes } from 'node:crypto';3
import { once } from 'node:events';4
import { isIP } from 'node:net';5
import { closeUdpSocket } from './socket-cleanup.mjs';6
import { decodeProbeMessage, encodeProbeMessage, sameEndpoint, probeEndpoint,7
probeOperations as op } from './nat-probe-wire.mjs';9
export async function openNatProbeSocket({ localAddress, token, usedPorts = new Set(), signal }) {10
if (isIP(localAddress) !== 4 || !Buffer.isBuffer(token) || token.length !== 32)11
throw new Error('Invalid NAT probe socket configuration');12
for (let attempt = 0; attempt < 8; attempt += 1) {13
signal?.throwIfAborted();14
const port = 49152 + randomBytes(2).readUInt16BE(0) % 16384;15
if (usedPorts.has(port)) continue;16
const socket = createSocket('udp4');17
const watchers = new Map();18
const counts = { outbound: 0, received: 0, ignored: 0 };19
let fault;20
let closing;21
const stopWatchers = () => { for (const watcher of [...watchers.values()]) watcher.finish(); };22
const close = () => {23
if (closing) return closing;24
stopWatchers();25
signal?.removeEventListener('abort', aborted);26
closing = closeUdpSocket(socket);27
return closing;28
};29
const aborted = () => { fault = signal.reason; void close(); };30
socket.on('error', error => { fault = error; stopWatchers(); });31
socket.on('message', (bytes, source) => {32
counts.received += 1;33
if (counts.received > 128) { fault = new Error('Probe receive budget'); void close(); return; }34
let message;35
try { message = decodeProbeMessage(bytes, token); }36
catch { counts.ignored += 1; return; }37
const watcher = watchers.get(message.transaction.toString('hex'));38
const expected = watcher?.expected[message.operation];39
if (!watcher || !sameEndpoint(expected, source) ||40
(message.operation === op.observed ? !message.endpoint : Boolean(message.endpoint))) {41
counts.ignored += 1; return;42
}43
watcher.messages[message.operation] = message;44
if (watcher.required.every(operation => watcher.messages[operation])) watcher.finish();45
});46
try {47
socket.bind(port, localAddress);48
await once(socket, 'listening');49
} catch (error) {50
await close();51
if (error.code === 'EADDRINUSE') continue;52
throw error;53
}54
usedPorts.add(port);55
signal?.addEventListener('abort', aborted, { once: true });56
if (signal?.aborted) { aborted(); await close(); signal.throwIfAborted(); }57
return { port, counts, close,58
watch({ transaction, expected, required, timeoutMs }) {59
signal?.throwIfAborted();60
if (closing || fault || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000)61
throw new Error('Probe watch unavailable or invalid deadline');62
const id = transaction.toString('hex');63
if (watchers.has(id) || watchers.size >= 8) throw new Error('Duplicate/excessive probe waiter');64
let done;65
const result = new Promise(resolve => { done = resolve; });66
const watcher = { expected, required, messages: {}, timer: undefined,67
finish() {68
if (!watchers.delete(id)) return;69
clearTimeout(watcher.timer);70
done({ messages: watcher.messages, failed: Boolean(fault || closing) });71
} };72
watchers.set(id, watcher);73
watcher.timer = setTimeout(watcher.finish, timeoutMs);74
return result;75
},76
async send(operation, destination, transaction) {77
signal?.throwIfAborted();78
if (closing || fault || counts.outbound >= 32) throw new Error('Probe socket stopped or packet budget exceeded');79
probeEndpoint(destination);80
const packet = encodeProbeMessage({ token, transaction, operation });81
counts.outbound += 1;82
await new Promise((done, reject) => socket.send(packet, destination.port, destination.address,83
error => error ? reject(error) : done()));84
} };85
}86
throw new Error('No unused random source port in bounded allocation attempts');87
}