Commit6ab94b09Recorded18 Oct 2026Repositorysigil-nat
Add bounded gateway discovery and mapping lifecycle
Changed
.gitignore | 3 ++
LICENSE | 54 ++++++++++++++++++++++++++++
README.md | 22 ++++++++++++
package.sgl | 29 +++++++++++++++
scripts/phantom-nat-check.sh | 15 ++++++++
scripts/phantom-nat-inspect.mjs | 32 +++++++++++++++++
scripts/phantom-upnp-mapping-check.mjs | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
src/sigil/nat/policy.sgl | 10 ++++++
tools/nat/codecs.mjs | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/discovery.mjs | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/external-udp-probe.mjs | 49 +++++++++++++++++++++++++
tools/nat/igd-discovery.mjs | 16 +++++++++
tools/nat/lease.mjs | 176 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/test-codecs.mjs | 94 ++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/test-upnp.mjs | 58 ++++++++++++++++++++++++++++++
tools/nat/upnp.mjs | 303 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 1209 insertions(+)Diff
.gitignoreadded
@@ -0,0 +1,3 @@
+1
/build/+2
/.sigil/+3
/sigil.lockLICENSEadded
@@ -0,0 +1,54 @@
+1
BSD 3-Clause License+2
+3
Copyright (c) 2026, David Wilson+4
All rights reserved.+5
+6
Redistribution and use in source and binary forms, with or without+7
modification, are permitted provided that the following conditions are met:+8
+9
1. Redistributions of source code must retain the above copyright notice,+10
this list of conditions and the following disclaimer.+11
2. Redistributions in binary form must reproduce the above copyright notice,+12
this list of conditions and the following disclaimer in the documentation+13
and/or other materials provided with the distribution.+14
3. Neither the name of the copyright holder nor the names of its contributors+15
may be used to endorse or promote products derived from this software+16
without specific prior written permission.+17
+18
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+19
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+20
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+21
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+22
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+23
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+24
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+25
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+26
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+27
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+28
+29
RFC vector code components in src/sigil/quic/vectors.sgl are extracted from:+30
RFC 8448, Copyright (c) 2019 IETF Trust and the persons identified as the+31
document authors; and RFC 9001, Copyright (c) 2021 IETF Trust and the persons+32
identified as the document authors. All rights reserved. These components+33
are subject to the Simplified BSD License under Section 4.e of the IETF+34
Trust Legal Provisions (https://trustee.ietf.org/license-info):+35
+36
Redistribution and use in source and binary forms, with or without+37
modification, are permitted provided that the following conditions are met:+38
1. Redistributions of source code must retain the above copyright notice,+39
this list of conditions and the following disclaimer.+40
2. Redistributions in binary form must reproduce the above copyright notice,+41
this list of conditions and the following disclaimer in the documentation+42
and/or other materials provided with the distribution.+43
+44
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+45
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+46
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+47
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE+48
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+49
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+50
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+51
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN+52
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+53
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+54
POSSIBILITY OF SUCH DAMAGE.README.mdadded
@@ -0,0 +1,22 @@
+1
# sigil-nat+2
+3
Small, bounded gateway discovery and UDP port-mapping helpers for Sigil+4
applications. PCP (RFC 6887), NAT-PMP (RFC 6886), and UPnP IGD are supported.+5
UPnP control uses a minimal internal HTTP/1.1 client. It does not follow+6
redirects, resolve off-gateway control URLs, parse external entities, or accept+7
unbounded responses.+8
+9
The lease coordinator creates one mapping at a time, caps every requested and+10
observed lease at 30 minutes, renews before expiry, records ownership before+11
network changes, and deletes only a mapping whose ownership tuple matches.+12
An ambiguous create or renewal must be reconciled or explicitly deleted before+13
trying another protocol. A UPnP router that only supports permanent mappings+14
is not used.+15
+16
The JavaScript modules in `tools/nat` are dependency-free operational helpers.+17
Live scripts require explicit host and route configuration.+18
+19
The protocol codec sources are RFC 6887 and RFC 6886. UPnP service actions and+20
lease semantics follow the [WANIPConnection:1 service template](https://upnp.org/specs/gw/UPnP-gw-WANIPConnection-v1-Service.pdf),+21
including `GetSpecificPortMappingEntry`, `AddPortMapping`,+22
`DeletePortMapping`, and `GetExternalIPAddress`.package.sgladded
@@ -0,0 +1,29 @@
+1
(package+2
name: "sigil-nat"+3
version: "0.1.0"+4
sigil: "0.22"+5
description: "Bounded NAT discovery and port-mapping helpers"+6
license: "BSD-3-Clause"+7
authors: (list "David Wilson <david@daviwil.com>")+8
entry: '(sigil nat policy)+9
+10
dependencies: (list+11
(from-git url: "codeberg:sigil/sigil" package: "sigil-lib" version: "^0.22"))+12
+13
dev-dependencies: (list+14
(from-git url: "codeberg:sigil/sigil" package: "sigil-test" version: "^0.22")+15
(from-git url: "codeberg:sigil/sigil" package: "sigil-test-runner" version: "^0.22"))+16
+17
configs: (list+18
(config+19
name: 'dev+20
debug?: #t+21
optimize: 0+22
output-dir: "build/dev")+23
(config+24
name: 'native+25
backend: 'native+26
debug?: #f+27
optimize: 2+28
bundle?: #t+29
output-dir: "build/native")))scripts/phantom-nat-check.shadded
@@ -0,0 +1,15 @@
+1
#!/usr/bin/env bash+2
set -euo pipefail+3
cd "$(dirname "$0")/.."+4
mkdir -p build/nat+5
result="$PWD/build/nat/check-result.txt"+6
record_result() {+7
local job_rc=$?+8
printf 'RESULT sigil-nat-check rc=%s\n' "$job_rc" | tee -a "$result"+9
}+10
trap record_result EXIT+11
printf 'RESULT operation=offline-tests-plus-read-only-inspection mapping-requests=0\n' | tee "$result"+12
timeout --foreground 30 node --test tools/nat/test-codecs.mjs tools/nat/test-upnp.mjs 2>&1 | tee build/nat/tests.log+13
printf 'RESULT offline-tests=PASS\n' | tee -a "$result"+14
timeout --foreground 30 node scripts/phantom-nat-inspect.mjs | tee build/nat/inspection.log+15
printf 'RESULT read-only-inspection=COMPLETE mapping-requests=0\n' | tee -a "$result"scripts/phantom-nat-inspect.mjsadded
@@ -0,0 +1,32 @@
+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';+7
+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');+10
+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');+16
+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();+22
+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));scripts/phantom-upnp-mapping-check.mjsadded
@@ -0,0 +1,121 @@
+1
// One short, owned UPnP UDP mapping with explicit deletion after one echo.+2
import { randomBytes } from 'node:crypto';+3
import { hostname } from 'node:os';+4
import { createSocket } from 'node:dgram';+5
import { mkdirSync, writeFileSync } from 'node:fs';+6
import { once } from 'node:events';+7
import { gatewayRoute, discoverGateway } from '../tools/nat/discovery.mjs';+8
import { discoverIgd } from '../tools/nat/igd-discovery.mjs';+9
import { UpnpIgdClient, upnpUdpCandidate } from '../tools/nat/upnp.mjs';+10
import { SingleUdpLease } from '../tools/nat/lease.mjs';+11
+12
if (!process.env.NAT_EXPECTED_HOST || hostname() !== process.env.NAT_EXPECTED_HOST)+13
throw new Error('Set NAT_EXPECTED_HOST to the intended network host');+14
const route = gatewayRoute();+15
if (!process.env.NAT_EXPECTED_GATEWAY || !process.env.NAT_EXPECTED_LOCAL_ADDRESS ||+16
route.gateway !== process.env.NAT_EXPECTED_GATEWAY ||+17
route.localAddress !== process.env.NAT_EXPECTED_LOCAL_ADDRESS)+18
throw new Error('Set NAT_EXPECTED_GATEWAY and NAT_EXPECTED_LOCAL_ADDRESS to the intended route');+19
+20
const resultPath = 'build/nat/mapping-receipt.json';+21
mkdirSync('build/nat', { recursive: true });+22
const token = randomBytes(32);+23
const responder = createSocket('udp4');+24
responder.bind(0, route.localAddress);+25
await once(responder, 'listening');+26
const internalPort = responder.address().port;+27
let lease;+28
let echoCount = 0;+29
let deleted = false;+30
let responderTimer;+31
const receipt = { route, protocol: 'upnp-igd', internalPort, challenge: token.toString('hex'),+32
mappingRequests: 0, echoCount: 0, deleted: false, responderStopped: false,+33
startedAt: new Date().toISOString() };+34
const save = () => writeFileSync(resultPath, JSON.stringify(receipt, null, 2) + '\n', { mode: 0o600 });+35
const finish = async () => {+36
if (lease && !deleted) {+37
try {+38
const state = await lease.close();+39
deleted = state.phase === 'deleted' || state.phase === 'unavailable';+40
receipt.deleted = deleted;+41
receipt.deleteState = state.phase;+42
} catch (error) {+43
receipt.deleteError = error.message;+44
}+45
}+46
clearTimeout(responderTimer);+47
responder.close();+48
receipt.responderStopped = true;+49
receipt.endedAt = new Date().toISOString();+50
save();+51
};+52
process.once('SIGTERM', () => { void finish().finally(() => process.exit(0)); });+53
process.once('SIGINT', () => { void finish().finally(() => process.exit(0)); });+54
+55
try {+56
await discoverGateway(route);+57
const igd = await discoverIgd(route);+58
const service = igd.services[0];+59
if (!service) throw new Error('No usable WANIPConnection IGD service');+60
const client = new UpnpIgdClient(service, route);+61
const externalAddress = await client.getExternalAddress();+62
receipt.serviceType = service.serviceType;+63
receipt.externalAddress = externalAddress;+64
const deadline = Date.now() + 15 * 60 * 1000;+65
lease = new SingleUdpLease({ candidates: [upnpUdpCandidate(client, { internalPort,+66
internalClient: route.localAddress, externalAddress })], deadline, leaseSeconds: 120,+67
journal: async state => {+68
receipt.leaseState = state;+69
if (state.phase === 'creating') receipt.mappingRequests += 1;+70
save();+71
} });+72
const active = await lease.create();+73
lease.maintain(error => {+74
receipt.renewalError = error.message;+75
save();+76
});+77
receipt.externalPort = active.mapping.externalPort;+78
receipt.grantedLeaseSeconds = active.mapping.lifetime;+79
receipt.readyAt = new Date().toISOString();+80
save();+81
console.log(`READY protocol=upnp-igd externalPort=${receipt.externalPort} leaseSeconds=${receipt.grantedLeaseSeconds}`);+82
responder.on('message', (bytes, peer) => {+83
if (!bytes.equals(token) || echoCount >= 2) return;+84
echoCount += 1;+85
receipt.echoCount = echoCount;+86
responder.send(bytes, peer.port, peer.address, error => {+87
if (error) receipt.echoError = error.message;+88
save();+89
if (echoCount === 1) {+90
void lease.close().then(state => {+91
deleted = state.phase === 'deleted';+92
receipt.deleted = deleted;+93
receipt.deleteState = state.phase;+94
receipt.deletedAt = new Date().toISOString();+95
save();+96
console.log(`RESULT explicit-delete=${deleted} state=${state.phase}; responder-retained=15s`);+97
responderTimer = setTimeout(() => { void finish(); }, 15000);+98
}).catch(async error => {+99
receipt.deleteError = error.message;+100
save();+101
await finish();+102
});+103
}+104
});+105
});+106
setTimeout(() => {+107
if (echoCount === 0) {+108
console.log('RESULT probe-timeout; attempting explicit deletion');+109
void finish();+110
}+111
}, 90000).unref();+112
await new Promise(resolve => responder.once('close', resolve));+113
if (!receipt.deleted) throw new Error('Owned UPnP mapping deletion was not confirmed');+114
if (echoCount !== 1) throw new Error('Expected exactly one pre-delete echo probe');+115
console.log(`RESULT mappingRequests=${receipt.mappingRequests} preDeleteEchoes=${echoCount} deleted=true responderStopped=true`);+116
} catch (error) {+117
receipt.error = error.message;+118
save();+119
await finish();+120
throw error;+121
}src/sigil/nat/policy.sgladded
@@ -0,0 +1,10 @@
+1
(define-library (sigil nat policy)+2
(export sigil-nat-maximum-lease-seconds+3
sigil-nat-lease-valid?)+4
(begin+5
(define sigil-nat-maximum-lease-seconds 1800)+6
+7
(define (sigil-nat-lease-valid? seconds)+8
(and (integer? seconds)+9
(exact? seconds)+10
(<= 1 seconds sigil-nat-maximum-lease-seconds)))))tools/nat/codecs.mjsadded
@@ -0,0 +1,104 @@
+1
// PCP RFC 6887 sections 7/11/14; NAT-PMP RFC 6886 sections 3.2–3.4.+2
// Pure codecs: no sockets, implicit requests, wildcard mappings or crypto.+3
import { isIP } from 'node:net';+4
+5
function check(value, message) { if (!value) throw new Error(message); }+6
function integer(value, maximum, label, minimum = 0) {+7
check(Number.isInteger(value) && value >= minimum && value <= maximum, `Invalid ${label}`);+8
}+9
export function ipv4Bytes(address) {+10
check(isIP(address) === 4, 'Expected an IPv4 address');+11
return Buffer.from(address.split('.').map(Number));+12
}+13
export function mappedAddress(address) {+14
const bytes = Buffer.alloc(16);+15
bytes[10] = 255; bytes[11] = 255; ipv4Bytes(address).copy(bytes, 12);+16
return bytes;+17
}+18
function readAddress(bytes) {+19
if (bytes.subarray(0, 10).every(octet => octet === 0) && bytes[10] === 255 && bytes[11] === 255)+20
return [...bytes.subarray(12)].join('.');+21
return Array.from({ length: 8 }, (_, index) => bytes.readUInt16BE(index * 2).toString(16)).join(':');+22
}+23
function mappingFields({ protocol = 17, internalPort, externalPort = 0, lifetime }) {+24
check(protocol === 17 || protocol === 6, 'Only a single UDP/TCP mapping is supported');+25
integer(internalPort, 65535, 'internal port', 1);+26
integer(externalPort, 65535, 'external port');+27
integer(lifetime, 7200, 'bounded mapping lifetime');+28
}+29
export function pcpAnnounce(clientAddress) {+30
const packet = Buffer.alloc(24);+31
packet[0] = 2; mappedAddress(clientAddress).copy(packet, 8);+32
return packet;+33
}+34
export function pcpMap({ clientAddress, nonce, protocol = 17, internalPort,+35
externalPort = 0, externalAddress = '0.0.0.0', lifetime }) {+36
mappingFields({ protocol, internalPort, externalPort, lifetime });+37
check(Buffer.isBuffer(nonce) && nonce.length === 12, 'PCP requires an owned 96-bit mapping nonce');+38
const packet = Buffer.alloc(60);+39
packet[0] = 2; packet[1] = 1; packet.writeUInt32BE(lifetime, 4);+40
mappedAddress(clientAddress).copy(packet, 8); nonce.copy(packet, 24);+41
packet[36] = protocol; packet.writeUInt16BE(internalPort, 40); packet.writeUInt16BE(externalPort, 42);+42
mappedAddress(externalAddress).copy(packet, 44);+43
return packet;+44
}+45
function pcpOptions(bytes, start) {+46
const options = [];+47
for (let offset = start; offset < bytes.length;) {+48
check(offset + 4 <= bytes.length, 'Truncated PCP option header');+49
const size = bytes.readUInt16BE(offset + 2);+50
const end = offset + 4 + size;+51
const padded = end + ((4 - size % 4) % 4);+52
check(padded <= bytes.length, 'Truncated PCP option/padding');+53
options.push({ code: bytes[offset], bytes: Buffer.from(bytes.subarray(offset + 4, end)) });+54
check(options.length <= 64, 'PCP option work budget');+55
offset = padded;+56
}+57
return options;+58
}+59
export function decodePcp(bytes, expectedOpcode, expectedMap) {+60
check(Buffer.isBuffer(bytes) && bytes.length >= 24 && bytes.length <= 1100, 'Invalid PCP response size');+61
check(bytes[0] === 2 && (bytes[1] & 128) !== 0 && (bytes[1] & 127) === expectedOpcode,+62
'PCP version/direction/opcode mismatch');+63
const response = { protocol: 'pcp', opcode: expectedOpcode, result: bytes[3],+64
lifetime: bytes.readUInt32BE(4), epoch: bytes.readUInt32BE(8) };+65
// Reserved bits are ignored on reception as required by RFC 6887.+66
if (response.result !== 0) return response;+67
if (expectedOpcode === 0) {+68
response.options = pcpOptions(bytes, 24);+69
return response;+70
}+71
check(expectedOpcode === 1 && bytes.length >= 60, 'Truncated/unsupported PCP MAP response');+72
Object.assign(response, { nonce: Buffer.from(bytes.subarray(24, 36)), transport: bytes[36],+73
internalPort: bytes.readUInt16BE(40), externalPort: bytes.readUInt16BE(42),+74
externalAddress: readAddress(bytes.subarray(44, 60)), options: pcpOptions(bytes, 60) });+75
if (expectedMap) {+76
check(response.nonce.equals(expectedMap.nonce) && response.transport === expectedMap.protocol &&+77
response.internalPort === expectedMap.internalPort, 'Unmatched PCP mapping response');+78
}+79
return response;+80
}+81
export function natPmpAddress() { return Buffer.from([0, 0]); }+82
export function natPmpMap({ protocol = 17, internalPort, externalPort = 0, lifetime }) {+83
mappingFields({ protocol, internalPort, externalPort, lifetime });+84
check(lifetime !== 0 || externalPort === 0, 'NAT-PMP delete requires external port zero');+85
const packet = Buffer.alloc(12);+86
packet[1] = protocol === 17 ? 1 : 2;+87
packet.writeUInt16BE(internalPort, 4); packet.writeUInt16BE(externalPort, 6); packet.writeUInt32BE(lifetime, 8);+88
return packet;+89
}+90
export function decodeNatPmp(bytes, opcode, internalPort) {+91
check(Buffer.isBuffer(bytes) && bytes.length >= 8 && bytes.length <= 16, 'Invalid NAT-PMP response size');+92
check(bytes[0] === 0 && bytes[1] === 128 + opcode && [0, 1, 2].includes(opcode),+93
'NAT-PMP version/direction/opcode mismatch');+94
const response = { protocol: 'nat-pmp', opcode, result: bytes.readUInt16BE(2), epoch: bytes.readUInt32BE(4) };+95
if (response.result !== 0) return response;+96
check(bytes.length === (opcode === 0 ? 12 : 16), 'Truncated/extra NAT-PMP response bytes');+97
if (opcode === 0) response.externalAddress = [...bytes.subarray(8, 12)].join('.');+98
else {+99
Object.assign(response, { internalPort: bytes.readUInt16BE(8), externalPort: bytes.readUInt16BE(10),+100
lifetime: bytes.readUInt32BE(12) });+101
if (internalPort !== undefined) check(response.internalPort === internalPort, 'Unmatched NAT-PMP mapping response');+102
}+103
return response;+104
}tools/nat/discovery.mjsadded
@@ -0,0 +1,123 @@
+1
// Read-only queries to one configured gateway. No MAP or AddPortMapping calls.+2
import { createSocket } from 'node:dgram';+3
import { execFileSync } from 'node:child_process';+4
import { isIP } from 'node:net';+5
import { pcpAnnounce, decodePcp, natPmpAddress, decodeNatPmp } from './codecs.mjs';+6
+7
export function gatewayRoute() {+8
const routes = JSON.parse(execFileSync('ip', ['-j', '-4', 'route', 'show', 'default'], { encoding: 'utf8' }));+9
const routesWithGateway = routes.filter(route => isIP(route.gateway) === 4);+10
if (routesWithGateway.length !== 1) throw new Error('Choose one unambiguous IPv4 default gateway');+11
const route = routesWithGateway[0];+12
const addresses = JSON.parse(execFileSync('ip', ['-j', '-4', 'address', 'show', 'dev', route.dev], { encoding: 'utf8' }))+13
.flatMap(device => device.addr_info).filter(address => address.family === 'inet' && address.scope === 'global');+14
const localAddress = route.prefsrc ?? (addresses.length === 1 ? addresses[0].local : undefined);+15
if (isIP(localAddress) !== 4 || !addresses.some(address => address.local === localAddress))+16
throw new Error('Default gateway has no unambiguous owned IPv4 source');+17
return { gateway: route.gateway, localAddress, interface: route.dev };+18
}+19
+20
export function udpQuery({ gateway, localAddress, request, decode, delays }) {+21
if (isIP(gateway) !== 4 || isIP(localAddress) !== 4 || !Buffer.isBuffer(request) || request.length > 1100)+22
throw new Error('Invalid bounded gateway query');+23
if (!Array.isArray(delays) || delays.length < 1 || delays.length > 4 ||+24
delays.some(delay => !Number.isInteger(delay) || delay < 100 || delay > 6000))+25
throw new Error('Invalid gateway retry budget');+26
return new Promise((done, reject) => {+27
const socket = createSocket('udp4');+28
let timer, attempt = 0, finished = false, received = 0;+29
const finish = (error, value) => {+30
if (finished) return;+31
finished = true; clearTimeout(timer);+32
try { socket.close(); } catch (closeError) { if (closeError.code !== 'ERR_SOCKET_DGRAM_NOT_RUNNING') throw closeError; }+33
if (error) reject(error); else done(value);+34
};+35
socket.on('error', error => finish(error));+36
socket.on('message', (bytes, peer) => {+37
if (++received > 32) return finish(new Error('Gateway response work budget exceeded'));+38
if (peer.address !== gateway || peer.port !== 5351 || bytes.length > 1100) return;+39
try { finish(null, decode(bytes)); } catch { /* Discard unrelated/truncated replies until bounded timeout. */ }+40
});+41
socket.bind(0, localAddress, () => {+42
const send = () => {+43
if (finished) return;+44
socket.send(request, 5351, gateway, error => { if (error) finish(error); });+45
timer = setTimeout(() => {+46
if (++attempt < delays.length) send();+47
else finish(new Error('Gateway query timed out'));+48
}, delays[attempt]);+49
};+50
send();+51
});+52
});+53
}+54
+55
export function parseSsdp(bytes, gateway) {+56
if (!Buffer.isBuffer(bytes) || bytes.length > 8192) throw new Error('SSDP response exceeds limit');+57
const lines = bytes.toString('utf8').split('\r\n');+58
if (!/^HTTP\/1\.[01] 200(?: |$)/.test(lines.shift())) throw new Error('Not an SSDP success response');+59
const headers = {};+60
for (const line of lines) {+61
if (!line) break;+62
const match = /^([A-Za-z0-9-]+):[ \t]*(.*)$/.exec(line);+63
if (!match || match[2].length > 2048) throw new Error('Invalid SSDP header');+64
const name = match[1].toLowerCase();+65
if (name in headers) throw new Error('Duplicate SSDP header');+66
headers[name] = match[2].trim();+67
if (Object.keys(headers).length > 32) throw new Error('SSDP header count limit');+68
}+69
if (!/^urn:schemas-upnp-org:(?:device:InternetGatewayDevice:[12]|service:WANIPConnection:[12]|service:WANPPPConnection:1)$/.test(headers.st ?? ''))+70
throw new Error('Not an IGD advertisement');+71
const location = new URL(headers.location);+72
if (!['http:', 'https:'].includes(location.protocol) || location.hostname !== gateway ||+73
location.username || location.password || location.hash) throw new Error('IGD description must remain on the exact gateway');+74
return { protocol: 'upnp-igd', location: location.href, searchTarget: headers.st, server: headers.server ?? '' };+75
}+76
export function ssdpDiscover({ gateway, localAddress }) {+77
return new Promise((done, reject) => {+78
const socket = createSocket('udp4');+79
const results = new Map();+80
let timer, received = 0, finished = false;+81
const finish = error => {+82
if (finished) return;+83
finished = true; clearTimeout(timer);+84
try { socket.close(); } catch (closeError) { if (closeError.code !== 'ERR_SOCKET_DGRAM_NOT_RUNNING') throw closeError; }+85
if (error) reject(error); else done([...results.values()]);+86
};+87
socket.on('error', finish);+88
socket.on('message', (bytes, peer) => {+89
if (++received > 32) return finish(new Error('SSDP response work limit'));+90
if (peer.address !== gateway) return;+91
try { const result = parseSsdp(bytes, gateway); results.set(result.location, result); } catch { /* Not our gateway IGD. */ }+92
});+93
socket.bind(0, localAddress, () => {+94
try {+95
socket.setMulticastInterface(localAddress); socket.setMulticastTTL(1);+96
timer = setTimeout(() => finish(), 2500);+97
const targets = ['device:InternetGatewayDevice:1', 'device:InternetGatewayDevice:2',+98
'service:WANIPConnection:1', 'service:WANIPConnection:2', 'service:WANPPPConnection:1'];+99
for (const destination of ['239.255.255.250', gateway]) {+100
for (const target of targets) {+101
const mx = destination === gateway ? '' : 'MX: 1\r\n';+102
const bytes = Buffer.from(`M-SEARCH * HTTP/1.1\r\nHOST: ${destination}:1900\r\nMAN: "ssdp:discover"\r\n${mx}ST: urn:schemas-upnp-org:${target}\r\nUSER-AGENT: Linux UPnP/1.1 SigilSpike/1\r\n\r\n`);+103
socket.send(bytes, 1900, destination, error => { if (error) finish(error); });+104
}+105
}+106
} catch (error) { finish(error); }+107
});+108
});+109
}+110
+111
export async function discoverGateway(route) {+112
const result = { mode: 'read-only-gateway-discovery', route, startedAt: new Date().toISOString(), createsMapping: false };+113
try { result.pcp = await udpQuery({ ...route, request: pcpAnnounce(route.localAddress),+114
decode: bytes => decodePcp(bytes, 0), delays: [3000, 6000] }); }+115
catch (error) { result.pcp = { error: error.message }; }+116
try { result.natPmp = await udpQuery({ ...route, request: natPmpAddress(),+117
decode: bytes => decodeNatPmp(bytes, 0), delays: [250, 500, 1000] }); }+118
catch (error) { result.natPmp = { error: error.message }; }+119
try { result.upnp = await ssdpDiscover(route); }+120
catch (error) { result.upnp = { error: error.message }; }+121
result.endedAt = new Date().toISOString();+122
return result;+123
}tools/nat/external-udp-probe.mjsadded
@@ -0,0 +1,49 @@
+1
// Outside-network probe helper. Send only a fixed 32-byte challenge and echo.+2
import { createSocket } from 'node:dgram';+3
import { isIP } from 'node:net';+4
import { writeFileSync } from 'node:fs';+5
import { performance } from 'node:perf_hooks';+6
+7
const [externalAddress, portText, challengeHex, receiptPath = 'probe-receipt.json'] = process.argv.slice(2);+8
const externalPort = Number(portText);+9
if (isIP(externalAddress) !== 4 || !Number.isInteger(externalPort) || externalPort < 1 || externalPort > 65535 ||+10
!/^[0-9a-f]{64}$/i.test(challengeHex ?? '')) throw new Error('Invalid UDP probe target/32-byte challenge');+11
const challenge = Buffer.from(challengeHex, 'hex');+12
const observation = await fetch('https://api.ipify.org', { signal: AbortSignal.timeout(3000) });+13
if (!observation.ok) throw new Error(`External address observation returned HTTP ${observation.status}`);+14
const observedAddress = (await observation.text()).trim();+15
if (isIP(observedAddress) !== 4) throw new Error('External address observation returned invalid IPv4');+16
+17
function probe(timeoutMs) {+18
return new Promise((resolve, reject) => {+19
const socket = createSocket('udp4');+20
const started = performance.now();+21
let finished = false;+22
const finish = (error, value) => {+23
if (finished) return;+24
finished = true;+25
clearTimeout(timer);+26
socket.close();+27
if (error) reject(error); else resolve(value);+28
};+29
const timer = setTimeout(() => finish(null, { echoed: false }), timeoutMs);+30
socket.on('error', error => finish(error));+31
socket.on('message', bytes => {+32
if (!bytes.equals(challenge)) return;+33
finish(null, { echoed: true, rttMs: Number((performance.now() - started).toFixed(3)) });+34
});+35
socket.bind(0, () => socket.send(challenge, externalPort, externalAddress,+36
error => { if (error) finish(error); }));+37
});+38
}+39
+40
const beforeDelete = await probe(3000);+41
let afterDelete;+42
if (!beforeDelete.echoed) throw new Error('Outside UDP echo did not arrive before deletion');+43
await new Promise(resolve => setTimeout(resolve, 8000));+44
afterDelete = await probe(2500);+45
const result = { targetAddress: externalAddress, observedAddress,+46
externalPort, beforeDelete, afterDelete, checkedAt: new Date().toISOString() };+47
writeFileSync(receiptPath, JSON.stringify(result, null, 2) + '\n', { mode: 0o600 });+48
if (afterDelete.echoed) throw new Error('UDP mapping still passed traffic after explicit deletion');+49
console.log(`RESULT outsideEcho=true rttMs=${beforeDelete.rttMs} postDeleteProbe=timeout`);tools/nat/igd-discovery.mjsadded
@@ -0,0 +1,16 @@
+1
import { describeIgd } from './upnp.mjs';+2
import { ssdpDiscover } from './discovery.mjs';+3
+4
export async function discoverIgd(route) {+5
const advertisements = await ssdpDiscover(route);+6
const services = [];+7
const errors = [];+8
for (const advertisement of advertisements.slice(0, 8)) {+9
try {+10
services.push(await describeIgd(advertisement, route));+11
} catch (error) {+12
errors.push({ location: advertisement.location, error: error.message });+13
}+14
}+15
return { advertisements, services, errors };+16
}tools/nat/lease.mjsadded
@@ -0,0 +1,176 @@
+1
// One owned UDP mapping. Every state transition can be durably journaled before+2
// the next request; a lost creation/renewal reply blocks fallback until deletion.+3
import { randomBytes } from 'node:crypto';+4
import { pcpMap, decodePcp, natPmpMap, decodeNatPmp } from './codecs.mjs';+5
import { udpQuery } from './discovery.mjs';+6
+7
export class MappingRejected extends Error {}+8
export class MappingUncertain extends Error {}+9
+10
export function udpMappingCandidates(route, discovery, internalPort, query = udpQuery) {+11
const candidates = [];+12
if (discovery.pcp?.result === 0) {+13
const fields = { clientAddress: route.localAddress, nonce: randomBytes(12), protocol: 17, internalPort };+14
candidates.push({+15
protocol: 'pcp', identity: { ...fields, nonce: fields.nonce.toString('hex') },+16
async exchange(lifetime, previous) {+17
const response = await query({ ...route, request: pcpMap({ ...fields, lifetime,+18
externalPort: previous?.externalPort ?? 0, externalAddress: previous?.externalAddress ?? '0.0.0.0' }),+19
decode: bytes => decodePcp(bytes, 1, fields), delays: [3000, 6000] });+20
if (response.result !== 0) throw new MappingRejected(`PCP result ${response.result}`);+21
return response;+22
},+23
});+24
}+25
if (discovery.natPmp?.result === 0) {+26
candidates.push({+27
protocol: 'nat-pmp', identity: { protocol: 17, internalPort, clientAddress: route.localAddress },+28
async exchange(lifetime, previous) {+29
const response = await query({ ...route, request: natPmpMap({ protocol: 17, internalPort, lifetime,+30
externalPort: lifetime === 0 ? 0 : previous?.externalPort ?? 0 }),+31
decode: bytes => decodeNatPmp(bytes, 1, internalPort), delays: [250, 500, 1000] });+32
if (response.result !== 0) throw new MappingRejected(`NAT-PMP result ${response.result}`);+33
return { ...response, externalAddress: discovery.natPmp.externalAddress };+34
},+35
});+36
}+37
return candidates;+38
}+39
+40
export class SingleUdpLease {+41
constructor({ candidates, deadline, leaseSeconds = 120, journal = () => {}, now = Date.now,+42
schedule = setTimeout, cancel = clearTimeout }) {+43
if (!Array.isArray(candidates) || candidates.length > 4 ||+44
!Number.isInteger(leaseSeconds) || leaseSeconds < 1 || leaseSeconds > 1800 ||+45
!Number.isFinite(deadline) || deadline <= now() || deadline - now() > 1800000)+46
throw new Error('One UDP lease requires a future deadline and a 1..1800 second cap');+47
this.candidates = candidates;+48
this.deadline = deadline;+49
this.leaseSeconds = leaseSeconds;+50
this.journal = journal;+51
this.now = now;+52
this.schedule = schedule;+53
this.cancel = cancel;+54
this.state = { phase: 'idle' };+55
this.tail = Promise.resolve();+56
this.stopping = false;+57
}+58
serial(action) {+59
const result = this.tail.then(action);+60
this.tail = result.catch(() => {});+61
return result;+62
}+63
async record(phase, extra = {}) {+64
this.state = { ...this.state, ...extra, phase, at: new Date(this.now()).toISOString() };+65
await this.journal(structuredClone(this.state));+66
}+67
requestedLifetime() {+68
const seconds = Math.min(this.leaseSeconds, Math.floor((this.deadline - this.now()) / 1000));+69
if (seconds < 1 || this.stopping) throw new Error('Mapping run deadline reached or stopping');+70
return seconds;+71
}+72
async accept(response) {+73
// A success reply may describe an unacceptable lease. Preserve that state+74
// for deletion rather than treating it as a clean rejection/fallback.+75
await this.record('uncertain', { mapping: response });+76
if (!Number.isInteger(response.lifetime) || response.lifetime < 1 || response.lifetime > 1800 ||+77
!Number.isInteger(response.externalPort) || response.externalPort < 1 || response.externalPort > 65535 ||+78
typeof response.externalAddress !== 'string')+79
throw new MappingUncertain('Router granted an invalid or over-cap mapping');+80
await this.record('active', { expiresAt: this.now() + response.lifetime * 1000 });+81
return structuredClone(this.state);+82
}+83
async removeOwned() {+84
if (!this.current) return;+85
await this.record('deleting');+86
try {+87
const response = await this.current.exchange(0, this.state.mapping);+88
if (response.lifetime !== 0) throw new Error('Deletion did not acknowledge zero lifetime');+89
await this.record('deleted');+90
} catch (error) {+91
await this.record('uncertain', { error: `Deletion unconfirmed: ${error.message}` });+92
throw new MappingUncertain(this.state.error);+93
}+94
}+95
create() {+96
return this.serial(async () => {+97
if (this.state.phase !== 'idle') throw new Error('This lease already attempted creation');+98
for (const candidate of this.candidates) {+99
const lifetime = this.requestedLifetime();+100
this.current = candidate;+101
await this.record('creating', { protocol: candidate.protocol, identity: candidate.identity, mapping: null });+102
let response;+103
try {+104
response = await candidate.exchange(lifetime);+105
} catch (error) {+106
if (error instanceof MappingRejected) {+107
await this.record('rejected', { error: error.message });+108
continue;+109
}+110
await this.record('uncertain', { error: `Creation unconfirmed: ${error.message}` });+111
await this.removeOwned();+112
// Only an acknowledged delete permits the next protocol.+113
continue;+114
}+115
try {+116
const active = await this.accept(response);+117
if (this.stopping) {+118
await this.removeOwned();+119
throw new Error('Lease stopped during creation');+120
}+121
return active;+122
} catch (error) {+123
if (this.state.phase !== 'deleted') await this.removeOwned();+124
throw error;+125
}+126
}+127
this.current = undefined;+128
await this.record('unavailable');+129
throw new Error('No responding mapping protocol succeeded');+130
});+131
}+132
renew() {+133
return this.serial(async () => {+134
if (this.state.phase !== 'active') throw new Error('Only an active owned lease can renew');+135
try {+136
const lifetime = this.requestedLifetime();+137
await this.record('renewing');+138
return await this.accept(await this.current.exchange(lifetime, this.state.mapping));+139
} catch (error) {+140
await this.record('uncertain', { error: `Renewal failed: ${error.message}` });+141
await this.removeOwned();+142
throw error;+143
}+144
});+145
}+146
maintain(onError = () => {}) {+147
if (this.state.phase !== 'active' || this.maintaining || this.stopping)+148
throw new Error('Maintain requires an active, running lease');+149
this.maintaining = true;+150
const failed = error => { try { onError(error); } catch { /* Cleanup is already attempted. */ } };+151
this.deadlineTimer = this.schedule(() => { void this.close().catch(failed); },+152
Math.max(0, this.deadline - this.now()));+153
const next = () => {+154
if (this.stopping || this.state.phase !== 'active') return;+155
const delay = Math.max(1, Math.floor(this.state.mapping.lifetime * 500));+156
if (this.now() + delay >= this.deadline) return;+157
this.renewTimer = this.schedule(() => {+158
void this.renew().then(next, async error => {+159
try { await this.close(); } catch (closeError) { failed(closeError); }+160
failed(error);+161
});+162
}, delay);+163
};+164
next();+165
}+166
close() {+167
this.stopping = true;+168
this.cancel(this.renewTimer);+169
this.cancel(this.deadlineTimer);+170
return this.serial(async () => {+171
if (this.current && ['creating', 'active', 'renewing', 'uncertain', 'deleting'].includes(this.state.phase))+172
await this.removeOwned();+173
return structuredClone(this.state);+174
});+175
}+176
}tools/nat/test-codecs.mjsadded
@@ -0,0 +1,94 @@
+1
import assert from 'node:assert/strict';+2
import { test } from 'node:test';+3
import { mappedAddress, pcpAnnounce, pcpMap, decodePcp, natPmpAddress, natPmpMap, decodeNatPmp } from './codecs.mjs';+4
import { parseSsdp } from './discovery.mjs';+5
+6
const hex = text => Buffer.from(text.replace(/\s/g, ''), 'hex');+7
const nonce = hex('00112233445566778899aabb');+8
const request = { clientAddress: '192.0.2.10', nonce, protocol: 17, internalPort: 40000, lifetime: 120 };+9
const response = hex(`0281000000000078000004d2000000000000000000000000+10
00112233445566778899aabb110000009c40c35000000000000000000000ffffcb007109`);+11
+12
test('IPv4 PCP fields use the RFC IPv4-mapped representation', () => {+13
assert.equal(mappedAddress('192.0.2.10').toString('hex'), '00000000000000000000ffffc000020a');+14
assert.equal(mappedAddress('0.0.0.0').toString('hex'), '00000000000000000000ffff00000000');+15
assert.throws(() => mappedAddress('router.invalid'), /IPv4/);+16
});+17
test('PCP ANNOUNCE is a zero-lifetime read-only common header', () => {+18
assert.equal(pcpAnnounce('192.0.2.10').length, 24);+19
assert.equal(pcpAnnounce('192.0.2.10').toString('hex'),+20
'020000000000000000000000000000000000ffffc000020a');+21
});+22
test('PCP MAP wire positions match independently specified octets', () => {+23
assert.equal(pcpMap(request).toString('hex'),+24
'020100000000007800000000000000000000ffffc000020a' ++25
'00112233445566778899aabb110000009c40000000000000000000000000ffff00000000');+26
});+27
test('PCP response matches nonce, transport and internal port before delivery', () => {+28
const result = decodePcp(response, 1, request);+29
assert.equal(result.result, 0); assert.equal(result.epoch, 1234); assert.equal(result.lifetime, 120);+30
assert.equal(result.externalAddress, '203.0.113.9'); assert.equal(result.externalPort, 50000);+31
assert.deepEqual(result.nonce, nonce);+32
});+33
test('PCP reserved bits are ignored on reception and zero in emitted requests', () => {+34
const modified = Buffer.from(response); modified[2] = 255; modified[12] = 255; modified[37] = 255;+35
assert.equal(decodePcp(modified, 1, request).externalPort, 50000);+36
assert.equal(pcpMap(request)[37], 0);+37
});+38
test('PCP foreign nonce, opcode, direction and internal port are rejected', () => {+39
for (const index of [0, 1, 24, 36, 40]) {+40
const modified = Buffer.from(response); modified[index] ^= 1;+41
assert.throws(() => decodePcp(modified, 1, request), /mismatch|Unmatched/);+42
}+43
const noResponseBit = Buffer.from(response); noResponseBit[1] = 1;+44
assert.throws(() => decodePcp(noResponseBit, 1, request), /direction/);+45
});+46
test('PCP options are bounded and require their complete padded envelope', () => {+47
const withOption = Buffer.concat([response, hex('80630001bc000000')]);+48
assert.deepEqual(decodePcp(withOption, 1, request).options, [{ code: 128, bytes: hex('bc') }]);+49
assert.throws(() => decodePcp(withOption.subarray(0, -1), 1, request), /Truncated/);+50
assert.throws(() => decodePcp(response.subarray(0, 59), 1, request), /Truncated/);+51
assert.throws(() => decodePcp(Buffer.alloc(1101), 0), /size/);+52
});+53
test('PCP server error header does not invent a successful mapping body', () => {+54
const error = Buffer.from(response.subarray(0, 24)); error[3] = 2;+55
const result = decodePcp(error, 1, request);+56
assert.equal(result.result, 2); assert.equal(result.externalPort, undefined);+57
});+58
test('NAT-PMP address request and response match known octets', () => {+59
assert.deepEqual(natPmpAddress(), hex('0000'));+60
assert.deepEqual(decodeNatPmp(hex('00800000000004d2cb007109'), 0),+61
{ protocol: 'nat-pmp', opcode: 0, result: 0, epoch: 1234, externalAddress: '203.0.113.9' });+62
});+63
test('NAT-PMP UDP/TCP map and exact-port delete never emit wildcard internal port', () => {+64
assert.equal(natPmpMap(request).toString('hex'), '000100009c40000000000078');+65
assert.equal(natPmpMap({ ...request, protocol: 6 }).toString('hex'), '000200009c40000000000078');+66
assert.equal(natPmpMap({ ...request, lifetime: 0 }).toString('hex'), '000100009c40000000000000');+67
assert.throws(() => natPmpMap({ ...request, lifetime: 0, externalPort: 50000 }), /delete/);+68
});+69
test('NAT-PMP mapping response and deletion match the requested internal port', () => {+70
const result = decodeNatPmp(hex('00810000000004d29c40c35000000078'), 1, 40000);+71
assert.equal(result.externalPort, 50000); assert.equal(result.lifetime, 120);+72
assert.equal(decodeNatPmp(hex('00810000000004d29c40000000000000'), 1, 40000).lifetime, 0);+73
assert.throws(() => decodeNatPmp(hex('00810000000004d29c41c35000000078'), 1, 40000), /Unmatched/);+74
});+75
test('NAT-PMP truncation, extra data and foreign opcodes do not pass as replies', () => {+76
assert.throws(() => decodeNatPmp(hex('00800000000004d2cb0071'), 0), /Truncated/);+77
assert.throws(() => decodeNatPmp(Buffer.alloc(17), 0), /size/);+78
assert.throws(() => decodeNatPmp(hex('00820000000004d29c40c35000000078'), 1), /opcode/);+79
assert.equal(decodeNatPmp(hex('00810002000004d2'), 1, 40000).result, 2);+80
});+81
test('mapping encoders reject wildcard protocols/ports and excessive leases', () => {+82
for (const change of [{ internalPort: 0 }, { externalPort: 65536 }, { protocol: 0 }, { lifetime: -1 }, { lifetime: 7201 }]) {+83
assert.throws(() => pcpMap({ ...request, ...change }));+84
assert.throws(() => natPmpMap({ ...request, ...change }));+85
}+86
assert.throws(() => pcpMap({ ...request, nonce: Buffer.alloc(11) }), /nonce/);+87
});+88
test('SSDP accepts IGD descriptions only at the exact configured gateway', () => {+89
const reply = location => Buffer.from(`HTTP/1.1 200 OK\r\nST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\nLOCATION: ${location}\r\nSERVER: unit-test\r\n\r\n`);+90
assert.equal(parseSsdp(reply('http://192.0.2.1:5000/root.xml'), '192.0.2.1').location, 'http://192.0.2.1:5000/root.xml');+91
assert.throws(() => parseSsdp(reply('http://203.0.113.1/root.xml'), '192.0.2.1'), /exact gateway/);+92
assert.throws(() => parseSsdp(reply('file:///root.xml'), '192.0.2.1'), /exact gateway/);+93
assert.throws(() => parseSsdp(Buffer.alloc(8193), '192.0.2.1'), /limit/);+94
});tools/nat/test-upnp.mjsadded
@@ -0,0 +1,58 @@
+1
import assert from 'node:assert/strict';+2
import { test } from 'node:test';+3
import { parseIgdDescription, upnpUdpCandidate } from './upnp.mjs';+4
+5
+6
const gateway = '192.0.2.1';+7
const location = new URL(`http://${gateway}:52869/gatedesc.xml`);+8
const description = Buffer.from(`<?xml version="1.0"?>+9
<root><URLBase>http://${gateway}:52869/</URLBase><device><serviceList>+10
<service><serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>+11
<controlURL>/upnp/control/WANIPConn1</controlURL></service>+12
</serviceList></device></root>`);+13
+14
test('IGD service description resolves a same-gateway control URL', () => {+15
assert.deepEqual(parseIgdDescription(description, location, gateway), {+16
protocol: 'upnp-igd', serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',+17
controlUrl: `http://${gateway}:52869/upnp/control/WANIPConn1`,+18
});+19
});+20
+21
test('IGD description refuses external control hosts and XML entities', () => {+22
const offGateway = Buffer.from(description.toString().replace('/upnp/control/WANIPConn1',+23
'http://192.0.2.99/control'));+24
assert.throws(() => parseIgdDescription(offGateway, location, gateway), /escaped/);+25
assert.throws(() => parseIgdDescription(Buffer.from('<!DOCTYPE root [<!ENTITY x SYSTEM "file:///etc/passwd">]>'),+26
location, gateway), /entities/);+27
});+28
+29
test('UPnP mapping candidate probes only free ports and verifies its owner before deletion', async () => {+30
const entries = new Map();+31
const calls = [];+32
const client = {+33
async getMapping(port) { calls.push(['get', port]); return entries.get(port); },+34
async addMapping(entry) {+35
calls.push(['add', entry.externalPort, entry.lifetime]);+36
entries.set(entry.externalPort, { internalPort: entry.internalPort, internalClient: entry.internalClient,+37
enabled: '1', description: entry.description, lifetime: entry.lifetime });+38
},+39
async deleteMapping(port) { calls.push(['delete', port]); entries.delete(port); },+40
};+41
const candidate = upnpUdpCandidate(client, { internalPort: 43123, internalClient: '192.0.2.44',+42
externalAddress: '198.51.100.4', randomPort: () => 51000 });+43
const active = await candidate.exchange(120);+44
assert.equal(active.externalPort, 51000);+45
assert.equal(active.lifetime, 120);+46
const deleted = await candidate.exchange(0, active);+47
assert.equal(deleted.lifetime, 0);+48
assert.equal(entries.size, 0);+49
assert.deepEqual(calls.map(call => call[0]), ['get', 'add', 'get', 'get', 'delete', 'get']);+50
});+51
+52
test('UPnP mapping candidate refuses an occupied port and excessive leases', async () => {+53
const client = { async getMapping() { return { description: 'someone else' }; } };+54
const candidate = upnpUdpCandidate(client, { internalPort: 43123, internalClient: '192.0.2.44',+55
externalAddress: '198.51.100.4', randomPort: () => 51000 });+56
await assert.rejects(candidate.exchange(120), /unoccupied/);+57
await assert.rejects(candidate.exchange(1801), /30 minutes/);+58
});tools/nat/upnp.mjsadded
@@ -0,0 +1,303 @@
+1
// Minimal HTTP/1.1 control point for a gateway already discovered by SSDP.+2
// The peer, size, redirects, XML entities and work are deliberately bounded.+3
import { connect } from 'node:net';+4
import { isIP } from 'node:net';+5
import { randomBytes } from 'node:crypto';+6
+7
const MAX_RESPONSE = 65536;+8
const MAX_HEADER = 16384;+9
+10
function requireValue(value, message) {+11
if (!value) throw new Error(message);+12
}+13
+14
function safeXml(bytes) {+15
requireValue(Buffer.isBuffer(bytes) && bytes.length <= MAX_RESPONSE, 'UPnP XML exceeds size limit');+16
const xml = bytes.toString('utf8');+17
requireValue(!/<!\s*(?:DOCTYPE|ENTITY)/i.test(xml), 'UPnP XML DTD/entities are disabled');+18
return xml.replace(/<!--[\s\S]*?-->/g, '');+19
}+20
+21
function decodeXml(text) {+22
return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, entity) => {+23
const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };+24
if (entity[0] !== '#') return named[entity.toLowerCase()];+25
const value = entity[1].toLowerCase() === 'x'+26
? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);+27
requireValue(Number.isInteger(value) && value > 0 && value <= 0x10ffff &&+28
!(value >= 0xd800 && value <= 0xdfff), 'Invalid XML character reference');+29
return String.fromCodePoint(value);+30
});+31
}+32
+33
function xmlTag(xml, name) {+34
const match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}\\s*>`, 'i').exec(xml);+35
return match ? decodeXml(match[1].trim()) : undefined;+36
}+37
+38
function controlUrl(value, base, gateway) {+39
const url = new URL(value, base);+40
requireValue(url.protocol === 'http:' && url.hostname === gateway &&+41
!url.username && !url.password && !url.hash, 'UPnP control URL escaped the HTTP gateway');+42
return url;+43
}+44
+45
function parseHttpResponse(bytes) {+46
const split = bytes.indexOf('\r\n\r\n');+47
requireValue(split >= 0 && split <= MAX_HEADER, 'Invalid/bounded UPnP HTTP headers');+48
const lines = bytes.subarray(0, split).toString('latin1').split('\r\n');+49
const status = /^HTTP\/1\.[01] ([0-9]{3})(?: .*)?$/.exec(lines.shift() ?? '');+50
requireValue(status, 'Invalid UPnP HTTP status line');+51
const headers = new Map();+52
for (const line of lines) {+53
const match = /^([A-Za-z0-9-]+):[ \t]*(.*)$/.exec(line);+54
requireValue(match && !headers.has(match[1].toLowerCase()), 'Malformed/duplicate UPnP HTTP header');+55
headers.set(match[1].toLowerCase(), match[2].trim());+56
}+57
const body = bytes.subarray(split + 4);+58
const transferEncoding = headers.get('transfer-encoding');+59
if (transferEncoding) {+60
requireValue(transferEncoding.toLowerCase() === 'chunked', 'Unsupported UPnP transfer encoding');+61
return { status: Number(status[1]), headers, body: decodeChunked(body) };+62
}+63
const length = headers.get('content-length');+64
if (length !== undefined) {+65
requireValue(/^\d+$/.test(length) && Number(length) <= MAX_RESPONSE && body.length >= Number(length),+66
'Invalid/truncated UPnP Content-Length');+67
requireValue(body.length === Number(length), 'Unexpected bytes after UPnP HTTP body');+68
}+69
return { status: Number(status[1]), headers, body };+70
}+71
+72
function decodeChunked(bytes) {+73
const chunks = [];+74
let offset = 0;+75
let total = 0;+76
while (true) {+77
const lineEnd = bytes.indexOf('\r\n', offset);+78
requireValue(lineEnd >= 0 && lineEnd - offset <= 32, 'Malformed UPnP chunk header');+79
const sizeText = bytes.subarray(offset, lineEnd).toString('ascii').split(';', 1)[0];+80
requireValue(/^[0-9a-f]{1,8}$/i.test(sizeText), 'Invalid UPnP chunk size');+81
const size = Number.parseInt(sizeText, 16);+82
offset = lineEnd + 2;+83
if (size === 0) {+84
requireValue(bytes.subarray(offset).equals(Buffer.from('\r\n')), 'Unexpected UPnP chunk trailers');+85
break;+86
}+87
total += size;+88
requireValue(total <= MAX_RESPONSE && offset + size + 2 <= bytes.length &&+89
bytes.subarray(offset + size, offset + size + 2).equals(Buffer.from('\r\n')),+90
'Truncated/oversized UPnP chunk');+91
chunks.push(bytes.subarray(offset, offset + size));+92
offset += size + 2;+93
}+94
return Buffer.concat(chunks, total);+95
}+96
+97
function requestHttp(url, { gateway, localAddress, method, headers = {}, body = Buffer.alloc(0) }) {+98
requireValue(isIP(gateway) === 4 && isIP(localAddress) === 4 && url.hostname === gateway &&+99
url.protocol === 'http:' && !url.username && !url.password, 'UPnP HTTP target must be the selected IPv4 gateway');+100
requireValue(body.length <= MAX_RESPONSE, 'UPnP request body exceeds limit');+101
const port = Number(url.port || 80);+102
requireValue(Number.isInteger(port) && port >= 1 && port <= 65535, 'Invalid UPnP HTTP port');+103
const path = `${url.pathname || '/'}${url.search}`;+104
const lines = [`${method} ${path} HTTP/1.1`, `Host: ${gateway}:${port}`,+105
'Connection: close', 'Accept: text/xml, application/xml'];+106
for (const [name, value] of Object.entries(headers)) {+107
requireValue(/^[A-Za-z0-9-]+$/.test(name) && !/[\r\n]/.test(value), 'Invalid UPnP request header');+108
lines.push(`${name}: ${value}`);+109
}+110
if (body.length) lines.push(`Content-Length: ${body.length}`);+111
const wire = Buffer.concat([Buffer.from(`${lines.join('\r\n')}\r\n\r\n`), body]);+112
return new Promise((resolve, reject) => {+113
const socket = connect({ host: gateway, port, localAddress });+114
const parts = [];+115
let length = 0;+116
let settled = false;+117
const finish = (error, response) => {+118
if (settled) return;+119
settled = true;+120
socket.destroy();+121
if (error) reject(error); else resolve(response);+122
};+123
socket.setTimeout(3000, () => finish(new Error('UPnP HTTP request timed out')));+124
socket.on('error', error => finish(error));+125
socket.on('connect', () => socket.write(wire));+126
socket.on('data', chunk => {+127
length += chunk.length;+128
if (length > MAX_RESPONSE + MAX_HEADER) return finish(new Error('UPnP HTTP response exceeds limit'));+129
parts.push(chunk);+130
});+131
socket.on('end', () => {+132
try { finish(null, parseHttpResponse(Buffer.concat(parts, length))); }+133
catch (error) { finish(error); }+134
});+135
});+136
}+137
+138
export function parseIgdDescription(bytes, location, gateway) {+139
const xml = safeXml(bytes);+140
const rootUrl = xmlTag(xml, 'URLBase');+141
const base = rootUrl ? controlUrl(rootUrl, location, gateway) : location;+142
const services = [...xml.matchAll(/<service(?:\s[^>]*)?>([\s\S]*?)<\/service\s*>/gi)];+143
for (const [, serviceXml] of services) {+144
const serviceType = xmlTag(serviceXml, 'serviceType');+145
if (!/^urn:schemas-upnp-org:service:(?:WANIPConnection:[12]|WANPPPConnection:1)$/.test(serviceType ?? '')) continue;+146
const control = xmlTag(serviceXml, 'controlURL');+147
requireValue(control, 'IGD service has no control URL');+148
return { protocol: 'upnp-igd', serviceType, controlUrl: controlUrl(control, base, gateway).href };+149
}+150
throw new Error('IGD description has no supported WANIPConnection/WANPPPConnection service');+151
}+152
+153
export async function describeIgd(discovered, route) {+154
const location = new URL(discovered.location);+155
requireValue(location.protocol === 'http:' && location.hostname === route.gateway &&+156
!location.username && !location.password && !location.hash, 'IGD description URL must remain on the selected gateway');+157
const response = await requestHttp(location, { ...route, method: 'GET' });+158
requireValue(response.status === 200, `IGD description returned HTTP ${response.status}`);+159
return { ...parseIgdDescription(response.body, location, route.gateway), gateway: route.gateway,+160
localAddress: route.localAddress };+161
}+162
+163
function xmlEscape(value) {+164
return String(value).replace(/[&<>"']/g, character => ({+165
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+166
})[character]);+167
}+168
+169
function parseActionResult(bytes, action) {+170
const xml = safeXml(bytes);+171
const fault = xmlTag(xml, 'errorCode');+172
if (fault) {+173
const error = new Error(`UPnP ${action} SOAP fault ${fault}`);+174
error.upnpCode = Number(fault);+175
throw error;+176
}+177
const body = new RegExp(`<[^>]*:?${action}Response(?:\\s[^>]*)?>([\\s\\S]*?)<\\/[^>]*:?${action}Response\\s*>`, 'i').exec(xml);+178
requireValue(body, `UPnP ${action} response element is missing`);+179
return body[1];+180
}+181
+182
export class UpnpIgdClient {+183
constructor(service, route) {+184
requireValue(service?.protocol === 'upnp-igd' &&+185
/^urn:schemas-upnp-org:service:(?:WANIPConnection:[12]|WANPPPConnection:1)$/.test(service.serviceType),+186
'Unsupported IGD service');+187
this.service = service;+188
this.route = route;+189
this.control = new URL(service.controlUrl);+190
}+191
async action(action, values = {}) {+192
const fields = Object.entries(values).map(([name, value]) => `<${name}>${xmlEscape(value)}</${name}>`).join('');+193
const body = Buffer.from(`<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:${action} xmlns:u="${this.service.serviceType}">${fields}</u:${action}></s:Body></s:Envelope>`);+194
const response = await requestHttp(this.control, { ...this.route, method: 'POST', body, headers: {+195
'Content-Type': 'text/xml; charset="utf-8"',+196
SOAPAction: `"${this.service.serviceType}#${action}"`,+197
} });+198
if (response.status !== 200) {+199
const faultCode = xmlTag(safeXml(response.body), 'errorCode');+200
const error = new Error(faultCode+201
? `UPnP ${action} SOAP fault ${faultCode}`+202
: `UPnP ${action} returned HTTP ${response.status}`);+203
if (faultCode) error.upnpCode = Number(faultCode);+204
throw error;+205
}+206
return parseActionResult(response.body, action);+207
}+208
async getExternalAddress() {+209
const response = await this.action('GetExternalIPAddress');+210
const address = xmlTag(response, 'NewExternalIPAddress');+211
requireValue(isIP(address) === 4 && address !== '0.0.0.0', 'IGD returned no usable IPv4 external address');+212
return address;+213
}+214
async getMapping(externalPort, protocol = 'UDP') {+215
try {+216
const response = await this.action('GetSpecificPortMappingEntry', {+217
NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: protocol,+218
});+219
return {+220
internalPort: Number(xmlTag(response, 'NewInternalPort')),+221
internalClient: xmlTag(response, 'NewInternalClient'),+222
enabled: xmlTag(response, 'NewEnabled'),+223
description: xmlTag(response, 'NewPortMappingDescription'),+224
lifetime: Number(xmlTag(response, 'NewLeaseDuration')),+225
};+226
} catch (error) {+227
if (error.upnpCode === 714) return undefined;+228
throw error;+229
}+230
}+231
async addMapping({ internalPort, internalClient, externalPort, description, lifetime }) {+232
await this.action('AddPortMapping', {+233
NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: 'UDP',+234
NewInternalPort: internalPort, NewInternalClient: internalClient,+235
NewEnabled: 1, NewPortMappingDescription: description, NewLeaseDuration: lifetime,+236
});+237
}+238
async deleteMapping(externalPort) {+239
await this.action('DeletePortMapping', {+240
NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: 'UDP',+241
});+242
}+243
}+244
+245
export function upnpUdpCandidate(client, { internalPort, internalClient, externalAddress,+246
randomPort = () => 49152 + randomBytes(2).readUInt16BE(0) % 16384 }) {+247
const owner = `sigil-nat:${randomBytes(12).toString('hex')}`;+248
let ownedPort;+249
let current;+250
async function verifyOwned(port, requireBoundLease = true) {+251
const entry = await client.getMapping(port, 'UDP');+252
if (!entry) return undefined;+253
requireValue(entry.description === owner && entry.internalPort === internalPort &&+254
entry.internalClient === internalClient && entry.enabled === '1',+255
'UPnP port is occupied by a mapping this process does not own');+256
if (requireBoundLease)+257
requireValue(Number.isInteger(entry.lifetime) && entry.lifetime >= 1 && entry.lifetime <= 1800,+258
'UPnP router granted an invalid or over-cap lease');+259
return entry;+260
}+261
return {+262
protocol: 'upnp-igd', identity: { internalPort, internalClient, owner },+263
async exchange(lifetime, previous) {+264
requireValue(Number.isInteger(lifetime) && lifetime >= 0 && lifetime <= 1800,+265
'UPnP lease must be within 30 minutes');+266
const port = previous?.externalPort ?? ownedPort ?? randomPort();+267
ownedPort = port;+268
if (lifetime === 0) {+269
const entry = await verifyOwned(port, false);+270
if (!entry) return { lifetime: 0 };+271
await client.deleteMapping(port);+272
requireValue(!(await client.getMapping(port, 'UDP')), 'UPnP mapping still exists after deletion');+273
current = undefined;+274
return { lifetime: 0, externalPort: port, externalAddress };+275
}+276
if (!previous) {+277
let free;+278
for (let attempts = 0; attempts < 8; attempts += 1) {+279
const candidate = attempts === 0 ? port : randomPort();+280
const entry = await client.getMapping(candidate, 'UDP');+281
if (!entry) { ownedPort = candidate; free = true; break; }+282
}+283
requireValue(free, 'No unoccupied external UDP port in bounded allocation attempts');+284
} else {+285
const existing = await verifyOwned(port);+286
requireValue(existing, 'Owned UPnP mapping disappeared before renewal');+287
}+288
try {+289
await client.addMapping({ internalPort, internalClient, externalPort: ownedPort,+290
description: owner, lifetime });+291
} catch (error) {+292
// A lost SOAP reply is resolved by reading the exact owner tuple.+293
const entry = await verifyOwned(ownedPort);+294
if (!entry) throw error;+295
}+296
const entry = await verifyOwned(ownedPort);+297
requireValue(entry && entry.lifetime > 0 && entry.lifetime <= 1800,+298
'UPnP did not install a bounded leased mapping');+299
current = entry;+300
return { lifetime: entry.lifetime, externalPort: ownedPort, externalAddress };+301
},+302
};+303
}