AtlatestRepositorysigil-nat

sigil-nat / tree / tools / natnat-probe.mjs

1// Outbound-only RFC-style observations over the private probe wire protocol.
2import { randomBytes } from 'node:crypto';
3import { performance } from 'node:perf_hooks';
4import { setTimeout as delay } from 'node:timers/promises';
5import { openNatProbeSocket } from './nat-probe-socket.mjs';
6import { validateProbeReflectors, validateSingleHostReflectors, probeOperations as op } from './nat-probe-wire.mjs';
7import { summarizeNatProbe, summarizeSingleHostNatProbe } from './nat-probe-analysis.mjs';
8
9async function lookup(channel, destination, timeoutMs, transaction = randomBytes(12)) {
10 const result = channel.watch({ transaction, expected: { [op.observed]: destination },
11 required: [op.observed], timeoutMs });
12 await channel.send(op.lookup, destination, transaction);
13 const response = await result;
14 return { sent: true, matched: !response.failed && Boolean(response.messages[op.observed]),
15 observed: response.messages[op.observed]?.endpoint, transaction };
17async function alternate(channel, primary, expectedProbe, operation, timeoutMs) {
18 const transaction = randomBytes(12);
19 const result = channel.watch({ transaction,
20 expected: { [op.sent]: primary, [op.probe]: expectedProbe }, required: [op.sent, op.probe], timeoutMs });
21 await channel.send(operation, primary, transaction);
22 const response = await result;
23 return { sent: true, ackMatched: !response.failed && Boolean(response.messages[op.sent]),
24 received: !response.failed && Boolean(response.messages[op.probe]) };
26export async function runNatProbe({ localAddress, reflectors, token, mappingSamples = 3,
27 idleMs = [15000, 30000, 60000, 120000], timeoutMs = 1500, deadlineMs = 180000, signal }) {
28 const singleHost = reflectors?.b === undefined;
29 const topology = singleHost ? validateSingleHostReflectors(reflectors) : validateProbeReflectors(reflectors);
30 if (!Number.isInteger(mappingSamples) || mappingSamples < 3 || mappingSamples > 5 ||
31 !Array.isArray(idleMs) || idleMs.length < 1 || idleMs.length > 4 ||
32 new Set(idleMs).size !== idleMs.length || idleMs.some(value => !Number.isInteger(value) || value < 1 || value > 120000) ||
33 !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000 ||
34 !Number.isInteger(deadlineMs) || deadlineMs < 1 || deadlineMs > 240000)
35 throw new Error('Invalid bounded NAT probe plan');
36 const abort = new AbortController();
37 const cancel = () => abort.abort(signal.reason);
38 signal?.addEventListener('abort', cancel, { once: true });
39 if (signal?.aborted) cancel();
40 const deadline = setTimeout(() => abort.abort(new Error('NAT probe overall deadline')), deadlineMs);
41 const channels = [];
42 const usedPorts = new Set();
43 const started = performance.now();
44 const open = async () => {
45 abort.signal.throwIfAborted();
46 const channel = await openNatProbeSocket({ localAddress, token, usedPorts, signal: abort.signal });
47 channels.push(channel);
48 return channel;
49 };
50 try {
51 const control = await open();
52 const positive = {
53 primary: (await lookup(control, topology.a1, timeoutMs)).matched,
54 alternatePort: (await lookup(control, topology.a2, timeoutMs)).matched,
55 };
56 if (!singleHost) positive.alternateAddress = (await lookup(control, topology.b, timeoutMs)).matched;
57 if (!Object.values(positive).every(Boolean)) {
58 const error = new Error('NAT probe reflector connectivity precondition failed');
59 error.code = 'PROBE_SETUP_FAILED';
60 error.controls = positive;
61 throw error;
62 }
63 const mapping = [], filtering = [];
64 for (let index = 0; index < mappingSamples; index += 1) {
65 const data = await open();
66 const a1 = await lookup(data, topology.a1, timeoutMs);
67 // This source port has contacted A1 only. Control-socket preflights cannot
68 // establish permissions for this separate measured source port.
69 const alternateAddress = singleHost ? undefined
70 : await alternate(data, topology.a1, topology.b, op.alternateAddress, timeoutMs);
71 const alternatePort = await alternate(data, topology.a1, topology.a2, op.alternatePort, timeoutMs);
72 const recoveredPrimary = (await lookup(data, topology.a1, timeoutMs)).matched;
73 filtering.push({ localPort: data.port, controls: { ...positive, primary: a1.matched, recoveredPrimary },
74 alternateAddress, alternatePort, outboundDestinationsBeforeFiltering: ['a1'] });
75 const a2 = await lookup(data, topology.a2, timeoutMs);
76 const b = singleHost ? undefined : await lookup(data, topology.b, timeoutMs);
77 const repeatedA1 = await lookup(data, topology.a1, timeoutMs);
78 mapping.push({ localPort: data.port, a1, a2, b, repeatedA1 });
79 }
80 // Start with distinct data sockets, kept open throughout. Each sends one
81 // lookup, then stays receive-only; probes are requested via control instead.
82 const idlePlans = [];
83 for (const requestedIdleMs of idleMs) {
84 const data = await open();
85 const initial = await lookup(data, topology.a1, timeoutMs);
86 idlePlans.push({ data, initial, requestedIdleMs, idleStart: performance.now() });
87 }
88 const lifetime = await Promise.all(idlePlans.map(async ({ data, initial, requestedIdleMs, idleStart }) => {
89 await delay(Math.max(0, requestedIdleMs - (performance.now() - idleStart)), undefined, { signal: abort.signal });
90 // A lookup on the measured socket here would reset its NAT mapping.
91 const delivered = data.watch({ transaction: initial.transaction,
92 expected: { [op.probe]: topology.a1 }, required: [op.probe], timeoutMs });
93 const acknowledged = control.watch({ transaction: initial.transaction,
94 expected: { [op.sent]: topology.a1 }, required: [op.sent], timeoutMs });
95 const idleAtRequestMs = performance.now() - idleStart;
96 await control.send(op.deliverStored, topology.a1, initial.transaction);
97 const [response, ack] = await Promise.all([delivered, acknowledged]);
98 const controlHealthy = (await lookup(control, topology.a1, timeoutMs)).matched;
99 return { localPort: data.port, idleMs: requestedIdleMs, actualIdleAtRequestMs: idleAtRequestMs,
100 outboundPackets: data.counts.outbound, established: initial.matched,
101 probeSent: !ack.failed && Boolean(ack.messages[op.sent]),
102 ackMatched: !ack.failed && Boolean(ack.messages[op.sent]),
103 controlHealthy, received: !response.failed && Boolean(response.messages[op.probe]) };
104 }));
105 abort.signal.throwIfAborted();
106 const summary = (singleHost ? summarizeSingleHostNatProbe : summarizeNatProbe)({ mapping, filtering, lifetime });
107 summary.durationMs = Number((performance.now() - started).toFixed(3));
108 summary.packetCounts = channels.reduce((total, channel) => ({ outbound: total.outbound + channel.counts.outbound,
109 received: total.received + channel.counts.received }), { outbound: 0, received: 0 });
110 return { summary, details: { reflectors: topology, localAddress, mapping, filtering, lifetime,
111 sourcePorts: channels.map(channel => channel.port) } };
112 } finally {
113 clearTimeout(deadline);
114 signal?.removeEventListener('abort', cancel);
115 await Promise.all(channels.map(channel => channel.close()));
116 }