AtlatestRepositorysigil-nat
1
// Bounded read-only gateway and UPnP inspection.2
import { hostname } from 'node:os';3
import { mkdirSync, writeFileSync } from 'node:fs';4
import { discoverGateway, gatewayRoute } from '../tools/nat/discovery.mjs';5
import { discoverIgd } from '../tools/nat/igd-discovery.mjs';6
import { UpnpIgdClient } from '../tools/nat/upnp.mjs';8
if (!process.env.NAT_EXPECTED_HOST || hostname() !== process.env.NAT_EXPECTED_HOST)9
throw new Error('Set NAT_EXPECTED_HOST to the intended network host');11
const route = gatewayRoute();12
if (!process.env.NAT_EXPECTED_GATEWAY || !process.env.NAT_EXPECTED_LOCAL_ADDRESS ||13
route.gateway !== process.env.NAT_EXPECTED_GATEWAY ||14
route.localAddress !== process.env.NAT_EXPECTED_LOCAL_ADDRESS)15
throw new Error('Set NAT_EXPECTED_GATEWAY and NAT_EXPECTED_LOCAL_ADDRESS to the intended route');17
const discovery = await discoverGateway(route);18
const igd = await discoverIgd(route);19
const service = igd.services[0];20
let externalAddress;21
if (service) externalAddress = await new UpnpIgdClient(service, route).getExternalAddress();23
const result = { route, discovery, igd,24
externalAddress: externalAddress ?? null,25
checkedAt: new Date().toISOString() };26
mkdirSync('build/nat', { recursive: true });27
writeFileSync('build/nat/gateway-inspection.json', JSON.stringify(result, null, 2) + '\n', { mode: 0o600 });28
console.log(JSON.stringify({ gatewayResponded: Boolean(service),29
upnpService: service?.serviceType ?? null, externalAddressAvailable: Boolean(externalAddress),30
protocolResults: { pcp: discovery.pcp?.result ?? discovery.pcp?.error,31
natPmp: discovery.natPmp?.result ?? discovery.natPmp?.error,32
upnp: igd.services.length } }, null, 2));