From 19ec773634c15a5c37c0c3921686516cc559349e Mon Sep 17 00:00:00 2001 From: Dr_rOot Date: Fri, 28 Aug 2026 10:14:50 +0800 Subject: [PATCH 1/2] fix(network): select the Windows NAT default route (#1999) --- README.md | 10 +- README.zh-CN.md | 10 +- .../windows-route-print-tailscale.txt | 20 + src/clients/pmp-pcp-client.test.ts | 49 ++ src/clients/pmp-pcp-client.ts | 46 +- src/clients/upnp-client.test.ts | 28 + src/clients/upnp-client.ts | 17 +- src/nat-manager.test.ts | 677 +++++++++++++++++- src/nat-manager.ts | 644 +++++++++++++---- src/net/mock-udp-socket.ts | 6 + src/net/node-udp-socket.test.ts | 6 + src/net/udp-socket.test.ts | 3 + src/net/udp-socket.ts | 6 + src/network-monitor.ts | 60 +- src/network-route.test.ts | 345 +++++++++ src/network-route.ts | 409 +++++++++++ 16 files changed, 2133 insertions(+), 203 deletions(-) create mode 100644 src/__test__/fixtures/windows-route-print-tailscale.txt create mode 100644 src/network-route.test.ts create mode 100644 src/network-route.ts diff --git a/README.md b/README.md index 276b717..dcdea54 100644 --- a/README.md +++ b/README.md @@ -191,8 +191,8 @@ function valueOrThrow(result: ParseResult): T { This keeps expected network, validation, and protocol failures out of exception control flow. Constructor misuse and invalid imperative updates may -still throw; for example, `PmpPcpClient.setGatewayIp()` throws `RangeError` for -an invalid IPv4 address. +still throw; for example, `PmpPcpClient.setNetworkRoute()` throws `RangeError` +for an invalid gateway or internal IPv4 address. `NatErrorCode` contains the stable package-level error codes: @@ -389,12 +389,16 @@ The same client exposes: - `natPmpGetExternalIp({ timeoutMs, signal }?)` - `natPmpMap({ protocol, internalPort, externalPort, ttl, timeoutMs, signal })` - `pcpMap({ protocol, internalPort, externalPort, ttl, timeoutMs, signal, nonce })` +- `setNetworkRoute({ gatewayIp, internalIp })` - `setGatewayIp(ip)` - `close()` NAT-PMP requests are serialized because the protocol has no transaction correlator. PCP requests are correlated by nonce and allow up to four -concurrent requests per client. +concurrent requests per client. After a network change, call +`setNetworkRoute()` before the next probe or mapping so the gateway and PCP +client address change atomically. `setGatewayIp()` remains available for +gateway-only compatibility updates. ### STUN endpoint discovery diff --git a/README.zh-CN.md b/README.zh-CN.md index 2d0b6a5..b0a5f37 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -176,8 +176,9 @@ function valueOrThrow(result: ParseResult): T { ``` 因此,预期内的网络错误、校验失败和协议错误无需通过异常控制流程处理。构造参数 -误用或命令式更新中的无效值仍可能抛出异常;例如,传入无效 IPv4 地址时, -`PmpPcpClient.setGatewayIp()` 会抛出 `RangeError`。 +误用或命令式更新中的无效值仍可能抛出异常;例如,向 +`PmpPcpClient.setNetworkRoute()` 传入无效的网关或内网 IPv4 地址时会抛出 +`RangeError`。 `NatErrorCode` 定义了稳定的包级错误码: @@ -370,11 +371,14 @@ try { - `natPmpGetExternalIp({ timeoutMs, signal }?)` - `natPmpMap({ protocol, internalPort, externalPort, ttl, timeoutMs, signal })` - `pcpMap({ protocol, internalPort, externalPort, ttl, timeoutMs, signal, nonce })` +- `setNetworkRoute({ gatewayIp, internalIp })` - `setGatewayIp(ip)` - `close()` NAT-PMP 没有用于关联请求与响应的事务 ID,因此请求会串行执行。PCP 使用 -`nonce` 关联请求;每个客户端最多同时处理四个 PCP 请求。 +`nonce` 关联请求;每个客户端最多同时处理四个 PCP 请求。网络变化后,应在 +下次探测或映射前调用 `setNetworkRoute()`,以便原子更新网关和 PCP 客户端 +地址。`setGatewayIp()` 仍保留用于仅更新网关的兼容场景。 ### STUN 公网端点发现 diff --git a/src/__test__/fixtures/windows-route-print-tailscale.txt b/src/__test__/fixtures/windows-route-print-tailscale.txt new file mode 100644 index 0000000..3f559fb --- /dev/null +++ b/src/__test__/fixtures/windows-route-print-tailscale.txt @@ -0,0 +1,20 @@ +=========================================================================== +Interface List + 27...00 00 00 00 00 00 ......Tailscale Tunnel + 11...11 22 33 44 55 66 ......Intel(R) Wi-Fi 6 AX201 +=========================================================================== + +IPv4 Route Table +=========================================================================== +Active Routes: +Network Destination Netmask Gateway Interface Metric + 0.0.0.0 0.0.0.0 169.254.40.1 169.254.40.20 5 + 0.0.0.0 0.0.0.0 10.0.0.1 10.0.0.42 25 + 10.0.0.0 255.255.255.0 On-link 10.0.0.42 281 + 10.0.0.42 255.255.255.255 On-link 10.0.0.42 281 + 169.254.0.0 255.255.0.0 On-link 169.254.40.20 261 +=========================================================================== +Persistent Routes: + Network Address Netmask Gateway Address Metric + 0.0.0.0 0.0.0.0 10.9.9.1 1 +=========================================================================== diff --git a/src/clients/pmp-pcp-client.test.ts b/src/clients/pmp-pcp-client.test.ts index 634f192..fc396e6 100644 --- a/src/clients/pmp-pcp-client.test.ts +++ b/src/clients/pmp-pcp-client.test.ts @@ -172,4 +172,53 @@ describe('PmpPcpClient', () => { expect(() => client.setGatewayIp('10.0.0.256')).toThrow(RangeError) }) }) + + describe('setNetworkRoute', () => { + it('updates both the datagram destination and PCP client address', async () => { + client.setNetworkRoute({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + const pending = client.pcpMap({ + internalPort: 6881, + externalPort: 6881, + protocol: 'TCP', + ttl: 7200, + timeoutMs: 500, + }) + await tick() + + const sent = udpFactory.sockets[0]?.sendCalls[0] + expect(sent?.address).toBe('10.0.0.1') + expect(sent?.data.subarray(8, 24)).toEqual( + Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 10, 0, 0, 42]) + ) + + await client.close() + await pending + }) + + it('rejects invalid routes atomically', async () => { + expect(() => + client.setNetworkRoute({ + gatewayIp: '10.0.0.1', + internalIp: '', + }) + ).toThrow(RangeError) + + const pending = client.pcpMap({ + internalPort: 6881, + externalPort: 6881, + protocol: 'TCP', + ttl: 7200, + timeoutMs: 500, + }) + await tick() + const sent = udpFactory.sockets[0]?.sendCalls[0] + expect(sent?.address).toBe(gatewayIp) + expect(sent?.data.subarray(8, 24)).toEqual(clientIp) + await client.close() + await pending + }) + }) }) diff --git a/src/clients/pmp-pcp-client.ts b/src/clients/pmp-pcp-client.ts index ad84f97..5a8f53e 100644 --- a/src/clients/pmp-pcp-client.ts +++ b/src/clients/pmp-pcp-client.ts @@ -2,6 +2,7 @@ import { buildExternalIpRequest, buildMappingRequest, buildPcpMapRequest, + ipv4ToBuffer, isIpv4String, NATPMP_OPCODE_EXTERNAL_IP, NATPMP_OPCODE_MAP_TCP, @@ -37,6 +38,11 @@ export interface PmpPcpClientOptions { now?: () => number } +export interface PmpPcpNetworkRoute { + gatewayIp: string + internalIp: string +} + interface PendingNonce { nonce: Buffer expiresAt: number @@ -65,7 +71,7 @@ export class PmpPcpClient { private socketReady: Promise | null = null private readonly udpFactory: UdpSocketFactory private gatewayIp: string - private readonly clientIp: Buffer + private clientIp: Buffer private readonly now: () => number private readonly pendingNonces = new Map() @@ -75,16 +81,16 @@ export class PmpPcpClient { constructor(opts: PmpPcpClientOptions) { this.udpFactory = opts.udpFactory this.gatewayIp = opts.gatewayIp - this.clientIp = opts.clientIp + this.clientIp = Buffer.from(opts.clientIp) this.now = opts.now ?? (() => Date.now()) } /** * Point subsequent NAT-PMP / PCP traffic at a different gateway address. * - * Used by NatManager when discovery reveals a gateway that differs from the - * one supplied at construction (common: constructor gets a - * NetworkMonitor-snapshot best-effort; discovery learns the real one). + * Prefer setNetworkRoute() after an interface change so PCP's embedded + * client address changes with the gateway. This method remains for callers + * that intentionally need a gateway-only update. * * Any requests already in flight retain the address they were sent to — * responses from the old gateway arriving after the switch will be dropped @@ -103,6 +109,36 @@ export class PmpPcpClient { this.gatewayIp = ip } + /** Atomically update the gateway and PCP client address after a route change. */ + setNetworkRoute(route: PmpPcpNetworkRoute): void { + if ( + !route.gatewayIp || + route.gatewayIp === '0.0.0.0' || + !isIpv4String(route.gatewayIp) + ) { + throw new RangeError( + `PmpPcpClient.setNetworkRoute: invalid gateway IPv4 address: ${JSON.stringify(route.gatewayIp)}` + ) + } + if ( + !route.internalIp || + route.internalIp === '0.0.0.0' || + !isIpv4String(route.internalIp) + ) { + throw new RangeError( + `PmpPcpClient.setNetworkRoute: invalid internal IPv4 address: ${JSON.stringify(route.internalIp)}` + ) + } + + const clientIp = Buffer.concat([ + Buffer.alloc(10), + Buffer.from([0xff, 0xff]), + ipv4ToBuffer(route.internalIp), + ]) + this.gatewayIp = route.gatewayIp + this.clientIp = clientIp + } + async natPmpGetExternalIp( options: { timeoutMs?: number; signal?: AbortSignal } = {} ): Promise>> { diff --git a/src/clients/upnp-client.test.ts b/src/clients/upnp-client.test.ts index d501aea..df52d0c 100644 --- a/src/clients/upnp-client.test.ts +++ b/src/clients/upnp-client.test.ts @@ -86,6 +86,34 @@ describe('UpnpClient.discover', () => { await discoverP }) + it('binds SSDP discovery to the selected network interface', async () => { + const discoverP = client.discover({ + timeoutMs: 100, + interfaceAddress: '10.0.0.42', + }) + await tick() + + const sock = udpFactory.sockets[0]! + expect(sock.boundAddress).toBe('10.0.0.42') + expect(sock.multicastInterface).toBe('10.0.0.42') + expect(sock.sendCalls).toHaveLength(2) + await discoverP + }) + + it('rejects an invalid SSDP interface before opening a socket', async () => { + const result = await client.discover({ + timeoutMs: 100, + interfaceAddress: 'not-an-ip', + }) + + expect(result).toEqual({ + ok: false, + error: NatErrorCode.DiscoveryFailed, + detail: 'invalid SSDP interface address', + }) + expect(udpFactory.sockets).toHaveLength(0) + }) + it('searches for both IGD v1 and v2 targets', async () => { const discoverP = client.discover({ timeoutMs: 100 }) await tick() diff --git a/src/clients/upnp-client.ts b/src/clients/upnp-client.ts index 9727ec7..d63a49b 100644 --- a/src/clients/upnp-client.ts +++ b/src/clients/upnp-client.ts @@ -10,6 +10,7 @@ import { SSDP_MULTICAST_PORT, } from '../codecs/index.js' import { + isIpv4String, isLinkLocalIpv4, isPrivateIpv4, isValidPort, @@ -33,6 +34,8 @@ export interface DiscoverOptions { timeoutMs?: number maxResponses?: number mx?: number + /** Local IPv4 address used as the SSDP multicast source interface. */ + interfaceAddress?: string /** * SSDP search targets to M-SEARCH for. Defaults to {@link * SSDP_IGD_SEARCH_TARGETS} (IGD v1 + v2); one packet is sent per target on @@ -86,6 +89,13 @@ export class UpnpClient { async discover( options: DiscoverOptions = {} ): Promise> { + const interfaceAddress = options.interfaceAddress + if (interfaceAddress && !isIpv4String(interfaceAddress)) { + return parseErr( + NatErrorCode.DiscoveryFailed, + 'invalid SSDP interface address' + ) + } if (this.discovering) { return parseErr( NatErrorCode.DiscoveryFailed, @@ -202,7 +212,12 @@ export class UpnpClient { ;(async () => { try { - await socket.bind(0) + await socket.bind(0, interfaceAddress) + if (interfaceAddress) { + // Binding fixes the unicast response address; IP_MULTICAST_IF + // fixes the outgoing M-SEARCH interface (including on Windows). + socket.setMulticastInterface?.(interfaceAddress) + } for (const st of searchTargets) { await socket.send( buildMSearch(st, mx), diff --git a/src/nat-manager.test.ts b/src/nat-manager.test.ts index 6a0c097..b7e7dad 100644 --- a/src/nat-manager.test.ts +++ b/src/nat-manager.test.ts @@ -85,6 +85,7 @@ function makeDeps(): TestDeps { natPmpMap: vi.fn(), pcpMap: vi.fn(), setGatewayIp: vi.fn(), + setNetworkRoute: vi.fn(), close: vi.fn(), } const networkMonitor = { @@ -114,6 +115,20 @@ function makeDeps(): TestDeps { } as unknown as TestDeps } +class RenewalTrackingNatManager extends NatManager { + renewalSchedules = 0 + renewalClears = 0 + + protected override scheduleRenewal(): void { + this.renewalSchedules++ + } + + protected override clearRenewalTimer(): void { + this.renewalClears++ + super.clearRenewalTimer() + } +} + describe('NatManager lifecycle', () => { let deps: TestDeps let manager: NatManager @@ -277,6 +292,68 @@ describe('NatManager discovery', () => { expect(manager.getStatus().gatewayInfo?.gatewayIp).toBe('192.168.1.1') }) + it('binds UPnP discovery to the monitored default-route interface', async () => { + vi.mocked(deps.upnpClient.discover).mockResolvedValue(UPNP_GATEWAY_STUB) + + await manager.start() + + expect(deps.upnpClient.discover).toHaveBeenCalledWith({ + timeoutMs: 3000, + interfaceAddress: '192.168.1.100', + }) + expect(deps.networkMonitor.snapshot).toHaveBeenCalledTimes(1) + }) + + it('awaits a verified route before accepting UPnP on a multi-NIC host', async () => { + const verified = Promise.withResolvers<{ + gatewayIp: string + internalIp: string + hash: string + }>() + deps.networkMonitor.verifiedSnapshot = vi.fn(() => verified.promise) + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.20', + hash: 'fallback-a', + }) + vi.mocked(deps.upnpClient.discover).mockResolvedValue({ + ...UPNP_GATEWAY_STUB, + value: { + ...UPNP_GATEWAY_STUB.value, + gatewayIp: '10.0.0.254', + controlHost: '10.0.0.254', + }, + }) + + const starting = manager.start() + await tick() + expect(deps.upnpClient.discover).not.toHaveBeenCalled() + + verified.resolve({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + hash: 'verified-b', + }) + await starting + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + expect(deps.upnpClient.discover).toHaveBeenCalledWith({ + timeoutMs: 3000, + interfaceAddress: '10.0.0.42', + }) + expect(deps.networkMonitor.snapshot).not.toHaveBeenCalled() + + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.upnpClient.mapPort).mockResolvedValue({ ok: true }) + await manager.mapConfiguredPorts() + + expect(deps.upnpClient.mapPort).toHaveBeenCalledTimes(2) + for (const [, params] of vi.mocked(deps.upnpClient.mapPort).mock.calls) { + expect(params).toMatchObject({ internalIp: '10.0.0.42' }) + } + }) + it('transitions Discovering → Failed when all protocols fail', async () => { vi.mocked(deps.upnpClient.discover).mockResolvedValue({ ok: false, @@ -297,6 +374,129 @@ describe('NatManager discovery', () => { expect(states[states.length - 1]).toBe(NatState.Failed) }) + it('uses a background-refreshed route before probing NAT-PMP', async () => { + vi.mocked(deps.networkMonitor.snapshot) + .mockReturnValueOnce({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.100', + hash: 'fallback', + }) + .mockReturnValueOnce({ + gatewayIp: '192.168.1.254', + internalIp: '192.168.1.100', + hash: 'resolved', + }) + vi.mocked(deps.upnpClient.discover).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpGetExternalIp).mockResolvedValue({ + ok: true, + value: { externalIp: '203.0.113.10' }, + }) + + await manager.start() + + expect(deps.upnpClient.discover).toHaveBeenCalledWith({ + timeoutMs: 3000, + interfaceAddress: '192.168.1.100', + }) + expect(deps.pmpPcpClient.setNetworkRoute).toHaveBeenCalledWith({ + gatewayIp: '192.168.1.254', + internalIp: '192.168.1.100', + }) + const setNetworkRoute = deps.pmpPcpClient.setNetworkRoute + if (!setNetworkRoute) throw new Error('setNetworkRoute mock missing') + const gatewayUpdateOrder = + vi.mocked(setNetworkRoute).mock.invocationCallOrder[0] + const probeOrder = vi.mocked(deps.pmpPcpClient.natPmpGetExternalIp).mock + .invocationCallOrder[0] + expect(gatewayUpdateOrder).toBeLessThan(probeOrder ?? 0) + }) + + it('re-verifies the route after UPnP when topology changes mid-discovery', async () => { + const upnpResult = Promise.withResolvers<{ ok: false }>() + const routeB = Promise.withResolvers<{ + gatewayIp: string + internalIp: string + hash: string + }>() + deps.networkMonitor.verifiedSnapshot = vi + .fn() + .mockResolvedValueOnce({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.20', + hash: 'route-a', + }) + .mockReturnValueOnce(routeB.promise) + vi.mocked(deps.upnpClient.discover).mockReturnValue(upnpResult.promise) + vi.mocked(deps.pmpPcpClient.natPmpGetExternalIp).mockResolvedValue({ + ok: true, + value: { externalIp: '203.0.113.10' }, + }) + + const starting = manager.start() + await tick() + expect(deps.upnpClient.discover).toHaveBeenCalledWith({ + timeoutMs: 3000, + interfaceAddress: '192.168.1.20', + }) + + upnpResult.resolve({ ok: false }) + await tick() + expect(deps.networkMonitor.verifiedSnapshot).toHaveBeenCalledTimes(2) + expect(deps.pmpPcpClient.setNetworkRoute).not.toHaveBeenCalled() + expect(deps.pmpPcpClient.natPmpGetExternalIp).not.toHaveBeenCalled() + + routeB.resolve({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + hash: 'route-b', + }) + await starting + + expect(deps.pmpPcpClient.setNetworkRoute).toHaveBeenCalledTimes(1) + expect(deps.pmpPcpClient.setNetworkRoute).toHaveBeenCalledWith({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + }) + expect(deps.pmpPcpClient.natPmpGetExternalIp).toHaveBeenCalledTimes(1) + expect(manager.getStatus().gatewayInfo).toMatchObject({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + }) + }) + + it('does not probe an old NAT-PMP gateway when the route is unavailable', async () => { + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '', + internalIp: '', + hash: '', + }) + vi.mocked(deps.upnpClient.discover).mockResolvedValue({ ok: false }) + + await manager.start() + + expect(deps.pmpPcpClient.setNetworkRoute).not.toHaveBeenCalled() + expect(deps.pmpPcpClient.natPmpGetExternalIp).not.toHaveBeenCalled() + expect(manager.getStatus().state).toBe(NatState.Failed) + }) + + it('keeps NAT-PMP available for a gateway-only legacy adapter', async () => { + delete deps.pmpPcpClient.setNetworkRoute + vi.mocked(deps.upnpClient.discover).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpGetExternalIp).mockResolvedValue({ + ok: true, + value: { externalIp: '203.0.113.10' }, + }) + + await manager.start() + + expect(deps.pmpPcpClient.setGatewayIp).toHaveBeenCalledWith('192.168.1.1') + expect(deps.pmpPcpClient.natPmpGetExternalIp).toHaveBeenCalledTimes(1) + expect(manager.getStatus().state).toBe(NatState.Ready) + expect(manager.getStatus().gatewayInfo?.supportedProtocols).toEqual([ + NatProtocol.NatPmp, + ]) + }) + it('emits NatGatewayChanged when gateway is discovered', async () => { vi.mocked(deps.upnpClient.discover).mockResolvedValue({ ok: true, @@ -351,6 +551,40 @@ describe('NatManager mapping with fallback', () => { expect(manager.getStatus().activeMappings).toHaveLength(2) }) + it('disables PCP but maps with NAT-PMP for a legacy adapter', async () => { + delete deps.pmpPcpClient.setNetworkRoute + vi.mocked(deps.pmpPcpClient.natPmpMap).mockResolvedValue({ + ok: true, + value: { externalPort: 6881, ttl: 7200 }, + }) + + await manager.start() + await manager.mapConfiguredPorts() + + expect(deps.pmpPcpClient.setGatewayIp).toHaveBeenCalledWith('192.168.1.1') + expect(deps.pmpPcpClient.pcpMap).not.toHaveBeenCalled() + expect(deps.pmpPcpClient.natPmpMap).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + }) + + it('uses the discovery interface for UPnP mapping', async () => { + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.upnpClient.mapPort).mockResolvedValue({ ok: true }) + + await manager.start() + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.50', + hash: 'changed', + }) + await manager.mapConfiguredPorts() + + const mappingParams = vi.mocked(deps.upnpClient.mapPort).mock.calls[0]?.[1] + expect(mappingParams).toMatchObject({ internalIp: '192.168.1.100' }) + expect(deps.networkMonitor.snapshot).toHaveBeenCalledTimes(1) + }) + it('passes the lifecycle abort signal to UPnP mapPort and aborts it on stop', async () => { vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ ok: false, @@ -648,6 +882,372 @@ describe('NatManager stop during in-flight discovery', () => { }) }) +describe('NatManager stop during queued transitions', () => { + let deps: TestDeps + let manager: RenewalTrackingNatManager + + beforeEach(() => { + deps = makeDeps() + vi.mocked(deps.upnpClient.discover).mockResolvedValue(UPNP_GATEWAY_STUB) + manager = new RenewalTrackingNatManager(deps) + }) + + it('drops queued discovery and invalidates an active mapping, then restarts', async () => { + const gate = Promise.withResolvers() + let positiveMapCalls = 0 + vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async (params) => { + const ttl = (params as { ttl: number }).ttl + if (ttl === 0) return { ok: true } + positiveMapCalls++ + if (positiveMapCalls === 1) await gate.promise + return { ok: true, value: { externalPort: 6881, ttl: 7200 } } + }) + + await manager.start() + const mapping = manager.mapConfiguredPorts() + await tick() + expect(manager.getStatus().state).toBe(NatState.Mapping) + + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'changed' }) + await tick() + + await manager.stop() + expect(manager.getStatus().state).toBe(NatState.Stopped) + gate.resolve() + await mapping + + expect(positiveMapCalls).toBe(1) + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + expect(manager.getStatus().state).toBe(NatState.Stopped) + expect(manager.getStatus().activeMappings).toHaveLength(0) + expect(manager.renewalSchedules).toBe(0) + + const cleanupIndex = vi + .mocked(deps.pmpPcpClient.pcpMap) + .mock.calls.findIndex(([params]) => (params as { ttl: number }).ttl === 0) + expect(cleanupIndex).toBeGreaterThanOrEqual(0) + const cleanupOrder = vi.mocked(deps.pmpPcpClient.pcpMap).mock + .invocationCallOrder[cleanupIndex] + const closeOrders = vi.mocked(deps.pmpPcpClient.close).mock + .invocationCallOrder + expect(closeOrders.at(-1)).toBeGreaterThan(cleanupOrder ?? 0) + + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ + ok: true, + value: { externalPort: 6881, ttl: 7200 }, + }) + await manager.start() + await manager.mapConfiguredPorts() + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().activeMappings).toHaveLength(2) + expect(manager.renewalSchedules).toBe(1) + }) + + it('invalidates an active remap and does not run queued discovery', async () => { + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ + ok: true, + value: { externalPort: 6881, ttl: 7200 }, + }) + await manager.start() + await manager.mapConfiguredPorts() + manager.renewalSchedules = 0 + + const gate = Promise.withResolvers() + let positiveRemapCalls = 0 + vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async (params) => { + const ttl = (params as { ttl: number }).ttl + if (ttl === 0) return { ok: true } + positiveRemapCalls++ + if (positiveRemapCalls === 1) await gate.promise + return { ok: true, value: { externalPort: 6881, ttl: 7200 } } + }) + + const remapping = manager.remapAll() + await tick() + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'changed' }) + await tick() + + await manager.stop() + gate.resolve() + await remapping + + expect(positiveRemapCalls).toBe(1) + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + expect(manager.getStatus().state).toBe(NatState.Stopped) + expect(manager.getStatus().activeMappings).toHaveLength(0) + expect(manager.renewalSchedules).toBe(0) + + const pcpCalls = vi.mocked(deps.pmpPcpClient.pcpMap).mock.calls + const lastCleanupIndex = pcpCalls.findLastIndex( + ([params]) => (params as { ttl: number }).ttl === 0 + ) + const lastCleanupOrder = vi.mocked(deps.pmpPcpClient.pcpMap).mock + .invocationCallOrder[lastCleanupIndex] + const lastCloseOrder = vi + .mocked(deps.pmpPcpClient.close) + .mock.invocationCallOrder.at(-1) + expect(lastCloseOrder).toBeGreaterThan(lastCleanupOrder ?? 0) + }) + + it('serializes a rapid stop then start without overwriting the new route', async () => { + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.upnpClient.mapPort).mockResolvedValue({ ok: true }) + vi.mocked(deps.upnpClient.discover) + .mockReset() + .mockResolvedValueOnce(UPNP_GATEWAY_STUB) + .mockResolvedValueOnce({ + ...UPNP_GATEWAY_STUB, + value: { + ...UPNP_GATEWAY_STUB.value, + gatewayIp: '10.0.0.254', + controlHost: '10.0.0.254', + }, + }) + await manager.start() + await manager.mapConfiguredPorts() + + const unmapGate = Promise.withResolvers() + let unmapCalls = 0 + vi.mocked(deps.upnpClient.unmapPort).mockImplementation(async () => { + unmapCalls++ + if (unmapCalls === 1) await unmapGate.promise + return { ok: true } + }) + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + + const stopping = manager.stop() + const restarting = manager.start() + await tick() + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + + unmapGate.resolve() + await Promise.all([stopping, restarting]) + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Ready) + expect(manager.getStatus().gatewayInfo).toMatchObject({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + }) + for (const [gateway] of vi.mocked(deps.upnpClient.unmapPort).mock.calls) { + expect(gateway).toMatchObject({ gatewayIp: '192.168.1.1' }) + } + const closeOrder = vi + .mocked(deps.pmpPcpClient.close) + .mock.invocationCallOrder.at(-1) + const secondDiscoveryOrder = vi.mocked(deps.upnpClient.discover).mock + .invocationCallOrder[1] + expect(secondDiscoveryOrder).toBeGreaterThan(closeOrder ?? 0) + }) +}) + +describe('NatManager topology-change remapping', () => { + let deps: TestDeps + let manager: RenewalTrackingNatManager + + const gatewayB = { + ...UPNP_GATEWAY_STUB, + value: { + ...UPNP_GATEWAY_STUB.value, + gatewayIp: '10.0.0.254', + controlHost: '10.0.0.254', + }, + } + + beforeEach(() => { + deps = makeDeps() + vi.mocked(deps.upnpClient.discover) + .mockResolvedValueOnce(UPNP_GATEWAY_STUB) + .mockResolvedValueOnce(gatewayB) + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ + ok: true, + value: { externalPort: 6881, ttl: 7200 }, + }) + manager = new RenewalTrackingNatManager(deps) + }) + + it('clears route A and immediately rebuilds mappings on route B', async () => { + await manager.start() + await manager.mapConfiguredPorts() + expect(manager.getStatus().activeMappings).toHaveLength(2) + expect(manager.renewalSchedules).toBe(1) + + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'route-b' }) + + expect(manager.getStatus().activeMappings).toHaveLength(0) + expect(manager.getStatus().gatewayInfo).toBeNull() + expect(manager.renewalClears).toBe(1) + await tick() + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().gatewayInfo).toMatchObject({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + }) + expect(manager.getStatus().activeMappings).toHaveLength(2) + expect(manager.renewalSchedules).toBe(2) + const mappingSizes = deps.events + .filter( + (event): event is Extract => + event.type === 'mapping-updated' + ) + .map((event) => event.mappings.length) + expect(mappingSizes).toEqual([2, 0, 2]) + }) + + it('does not retain route A when route B remapping fails', async () => { + await manager.start() + await manager.mapConfiguredPorts() + expect(manager.getStatus().activeMappings).toHaveLength(2) + + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.pmpPcpClient.natPmpMap).mockResolvedValue({ ok: false }) + vi.mocked(deps.upnpClient.mapPort).mockResolvedValue({ ok: false }) + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'route-b' }) + await tick() + + expect(manager.getStatus().state).toBe(NatState.Failed) + expect(manager.getStatus().activeMappings).toHaveLength(0) + expect(manager.getStatus().gatewayInfo).toBeNull() + expect(manager.renewalSchedules).toBe(1) + expect(manager.renewalClears).toBeGreaterThanOrEqual(2) + const mappingSizes = deps.events + .filter( + (event): event is Extract => + event.type === 'mapping-updated' + ) + .map((event) => event.mappings.length) + expect(mappingSizes).toEqual([2, 0]) + }) + + it('consumes map and remap intents queued while B discovery awaits', async () => { + await manager.start() + await manager.mapConfiguredPorts() + + const bDiscovery = Promise.withResolvers() + vi.mocked(deps.upnpClient.discover) + .mockReset() + .mockReturnValueOnce(bDiscovery.promise) + vi.mocked(deps.pmpPcpClient.pcpMap).mockClear() + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'route-b' }) + await tick() + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + + deps.hooks._fireReady() + const remapping = manager.remapAll() + bDiscovery.resolve(gatewayB) + await remapping + + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().activeMappings).toHaveLength(2) + expect(deps.pmpPcpClient.pcpMap).toHaveBeenCalledTimes(2) + expect(manager.renewalSchedules).toBe(2) + }) + + it('consumes map and remap intents queued while B mapping awaits', async () => { + await manager.start() + await manager.mapConfiguredPorts() + + const firstBMap = Promise.withResolvers() + let bMapCalls = 0 + vi.mocked(deps.pmpPcpClient.pcpMap).mockClear() + vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async () => { + bMapCalls++ + if (bMapCalls === 1) await firstBMap.promise + return { ok: true, value: { externalPort: 6881, ttl: 7200 } } + }) + vi.mocked(deps.networkMonitor.snapshot).mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'route-b' }) + await tick() + expect(bMapCalls).toBe(1) + + deps.hooks._fireReady() + const remapping = manager.remapAll() + firstBMap.resolve() + await remapping + + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().activeMappings).toHaveLength(2) + expect(bMapCalls).toBe(2) + expect(manager.renewalSchedules).toBe(2) + }) + + it('preserves remap intent when topology change clears a queued map', async () => { + const firstDiscovery = Promise.withResolvers() + vi.mocked(deps.upnpClient.discover) + .mockReset() + .mockReturnValueOnce(firstDiscovery.promise) + .mockResolvedValueOnce(gatewayB) + vi.mocked(deps.networkMonitor.snapshot) + .mockReturnValueOnce({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.100', + hash: 'route-a', + }) + .mockReturnValue({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.50', + hash: 'route-b', + }) + + const starting = manager.start() + await tick() + expect(manager.getStatus().state).toBe(NatState.Discovering) + deps.hooks._fireReady() + await Promise.resolve() + + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'route-b' }) + firstDiscovery.resolve(UPNP_GATEWAY_STUB) + await starting + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().gatewayInfo?.gatewayIp).toBe('10.0.0.254') + expect(manager.getStatus().activeMappings).toHaveLength(2) + }) +}) + describe('NatManager public API', () => { let deps: TestDeps let manager: NatManager @@ -714,7 +1314,7 @@ describe('NatManager mutex coalescing', () => { manager = new NatManager(deps) }) - it('concurrent mapConfiguredPorts skips second call via dirty flag', async () => { + it('coalesces a concurrent mapConfiguredPorts call', async () => { const gate = Promise.withResolvers() vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async () => { await gate.promise // block until test releases @@ -726,19 +1326,18 @@ describe('NatManager mutex coalescing', () => { const first = manager.mapConfiguredPorts() // Yield so first call enters mutex await tick() - // Launch second — should coalesce (set dirty flag and return) + // Launch second — it shares the queue drain and requests one re-run. const second = manager.mapConfiguredPorts() - await second // second resolves immediately // Release the block gate.resolve() - await first + await Promise.all([first, second]) expect(manager.getStatus().state).toBe(NatState.Active) expect(manager.getStatus().activeMappings).toHaveLength(2) }) - it('dirty flag causes re-run after mutex release', async () => { + it('same-label queue entry causes one re-run after mutex release', async () => { const gate = Promise.withResolvers() let callCount = 0 vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async () => { @@ -751,17 +1350,77 @@ describe('NatManager mutex coalescing', () => { // First call enters mutex, blocks at first pcpMap call const first = manager.mapConfiguredPorts() await tick() - // Second call: mutex is locked → sets dirty flag → returns immediately - manager.mapConfiguredPorts() - // Release gate: first call finishes, sees dirty, re-runs + // Second call coalesces to one pending map-configured entry. + const second = manager.mapConfiguredPorts() + // Release gate: first call finishes, then the pending entry re-runs. gate.resolve() - await first + await Promise.all([first, second]) // First run: 2 ports. Re-run due to dirty: 2 more ports. Total = 4 expect(callCount).toBe(4) expect(manager.getStatus().state).toBe(NatState.Active) }) + it('drains discovery queued while mapConfiguredPorts is running', async () => { + const gate = Promise.withResolvers() + let mapCalls = 0 + vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async () => { + mapCalls++ + if (mapCalls === 1) await gate.promise + return { ok: true, value: { externalPort: 6881, ttl: 7200 } } + }) + + await manager.start() + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + const mapping = manager.mapConfiguredPorts() + await tick() + + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'changed' }) + await tick() + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + + gate.resolve() + await mapping + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().activeMappings).toHaveLength(2) + }) + + it('drains discovery queued while remapAll is running', async () => { + vi.mocked(deps.pmpPcpClient.pcpMap).mockResolvedValue({ + ok: true, + value: { externalPort: 6881, ttl: 7200 }, + }) + await manager.start() + await manager.mapConfiguredPorts() + + const gate = Promise.withResolvers() + let remapCalls = 0 + vi.mocked(deps.pmpPcpClient.pcpMap).mockImplementation(async () => { + remapCalls++ + if (remapCalls === 1) await gate.promise + return { ok: true, value: { externalPort: 6881, ttl: 7200 } } + }) + const remapping = manager.remapAll() + await tick() + + const onChange = vi.mocked(deps.networkMonitor.onChange).mock.calls[0]?.[0] + if (!onChange) throw new Error('network listener missing') + onChange({ hash: 'changed' }) + await tick() + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(1) + + gate.resolve() + await remapping + + expect(deps.upnpClient.discover).toHaveBeenCalledTimes(2) + expect(manager.getStatus().state).toBe(NatState.Active) + expect(manager.getStatus().activeMappings).toHaveLength(2) + }) + it('concurrent runDiscovery calls coalesce without warn', async () => { vi.mocked(deps.upnpClient.discover).mockImplementation(async () => { await new Promise((r) => setTimeout(r, 20)) diff --git a/src/nat-manager.ts b/src/nat-manager.ts index ebd3b01..735b26a 100644 --- a/src/nat-manager.ts +++ b/src/nat-manager.ts @@ -1,5 +1,5 @@ import crypto from 'node:crypto' -import { UPNP_WANIP_V1 } from './codecs/index.js' +import { isIpv4String, UPNP_WANIP_V1 } from './codecs/index.js' import { NatErrorCode } from './errors.js' import { natLogger } from './logger.js' import { GenerationGuard, TransitionMutex } from './state-machine.js' @@ -35,6 +35,7 @@ export interface NatSettingsProvider { export interface UpnpClientLike { discover(opts?: { timeoutMs?: number + interfaceAddress?: string }): Promise<{ ok: boolean; value?: unknown; error?: unknown }> mapPort( gateway: unknown, @@ -63,6 +64,7 @@ export interface PmpPcpClientLike { params: unknown ): Promise<{ ok: boolean; value?: unknown; error?: unknown }> setGatewayIp(ip: string): void + setNetworkRoute?(route: { gatewayIp: string; internalIp: string }): void close(): Promise } @@ -83,6 +85,11 @@ export interface NetworkMonitorLike { stop(): void onChange(listener: (snap: unknown) => void): () => void snapshot(): { gatewayIp: string; internalIp: string; hash: string } + verifiedSnapshot?(): Promise<{ + gatewayIp: string + internalIp: string + hash: string + }> } export interface NatManagerHooks { @@ -111,6 +118,11 @@ export interface NatManagerDeps { now?: () => number } +interface QueuedTransition { + lifecycleEpoch: number + work: (lifecycleEpoch: number) => Promise +} + export class NatManager { protected readonly deps: NatManagerDeps protected readonly mutex = new TransitionMutex() @@ -135,7 +147,14 @@ export class NatManager { ] protected retryCount = 0 protected retryTimer: NodeJS.Timeout | null = null - private readonly coalesceDirty = new Map() + private readonly queuedWork = new Map() + private queueDrain: Promise | null = null + private stopInFlight: Promise | null = null + private lifecycleEpoch = 0 + private lifecycleActive = false + private networkRemapPending = false + private natPmpGatewayReady = false + private pcpRouteReady = false constructor(deps: NatManagerDeps) { this.deps = deps @@ -156,6 +175,8 @@ export class NatManager { } async start(): Promise { + const stopping = this.stopInFlight + if (stopping) await stopping const nat = this.deps.settingsProvider.getNat() const engine = this.deps.settingsProvider.getEngine() // Reset retry budget on every explicit start so user-triggered enable() @@ -180,6 +201,11 @@ export class NatManager { 'NatManager.start: entering' ) if (!nat.enabled) { + this.lifecycleActive = false + this.lifecycleEpoch++ + this.queuedWork.clear() + this.gen.bump() + this.networkRemapPending = false this.setState(NatState.Stopped) log.info( { state: this.state }, @@ -187,6 +213,7 @@ export class NatManager { ) return } + this.lifecycleActive = true this.subscribeToBus() log.debug( { subscribers: this.unsubscribers.length }, @@ -212,9 +239,37 @@ export class NatManager { ) } - async stop(): Promise { + stop(): Promise { + if (this.stopInFlight) return this.stopInFlight + const task = Promise.resolve().then(() => this.doStop()) + this.stopInFlight = task + void task.then( + () => { + if (this.stopInFlight === task) this.stopInFlight = null + }, + () => { + if (this.stopInFlight === task) this.stopInFlight = null + } + ) + return task + } + + private async doStop(): Promise { const beforeState = this.state const beforeMappingCount = this.activeMappings.length + const mappingsToUnmap = [...this.activeMappings] + const gatewayForUnmap = this.gatewayInfo + const droppedTransitions = this.queuedWork.size + this.lifecycleActive = false + this.lifecycleEpoch++ + const stopEpoch = this.lifecycleEpoch + this.queuedWork.clear() + this.networkRemapPending = false + this.natPmpGatewayReady = false + this.pcpRouteReady = false + this.activeMappings = [] + this.gatewayInfo = null + this.stickyProtocol = null // Invalidate any in-flight discovery before its trailing setState writes // can resurrect us from Stopped — the generation guard inside doDiscovery // honours this bump on every isCurrent() checkpoint. @@ -229,6 +284,7 @@ export class NatManager { hasRenewalTimer: this.renewalTimer !== null, hasAbortController: this.abortController !== null, subscribers: this.unsubscribers.length, + droppedTransitions, }, 'NatManager.stop: entering' ) @@ -260,9 +316,9 @@ export class NatManager { // Best-effort: each mapping is independent, so one failure must not block // the rest or prevent shutdown. let unmappedCount = 0 - for (const mapping of this.activeMappings) { + for (const mapping of mappingsToUnmap) { try { - await this.unmapOne(mapping) + await this.unmapOne(mapping, gatewayForUnmap) unmappedCount++ } catch (err) { log.warn( @@ -282,10 +338,9 @@ export class NatManager { pmpPcpClosed = false log.warn({ err }, 'pmpPcp close failed') } - this.activeMappings = [] - this.gatewayInfo = null - this.stickyProtocol = null - this.setState(NatState.Stopped) + if (this.lifecycleEpoch === stopEpoch && !this.lifecycleActive) { + this.setState(NatState.Stopped) + } log.info( { previousState: beforeState, @@ -294,6 +349,7 @@ export class NatManager { renewalTimerCleared: renewalWasActive, aborted, releasedSubscribers: subscriberCount, + droppedTransitions, pmpPcpClosed, state: this.state, }, @@ -313,22 +369,56 @@ export class NatManager { this.deps.onEvent({ type: 'error', error: { code, message } }) } - /** - * Push the learned gateway address into PmpPcpClient so subsequent - * NAT-PMP / PCP packets target the real gateway rather than the - * placeholder the factory used at construction. Silently tolerates - * malformed inputs from discovery (logs + keeps previous value) rather - * than propagating the RangeError up the discovery path. - */ - protected syncPmpPcpGatewayIp(ip: string | undefined | null): void { - if (!ip) return + /** Push one discovery round's gateway and client address into PMP/PCP. */ + protected syncPmpPcpNetworkRoute(route: { + gatewayIp: string | undefined | null + internalIp: string | undefined | null + }): boolean { + this.natPmpGatewayReady = false + this.pcpRouteReady = false + if ( + !route.gatewayIp || + route.gatewayIp === '0.0.0.0' || + !isIpv4String(route.gatewayIp) + ) { + return false + } + + const hasValidInternalIp = + Boolean(route.internalIp) && + route.internalIp !== '0.0.0.0' && + isIpv4String(route.internalIp as string) + if (hasValidInternalIp && this.deps.pmpPcpClient.setNetworkRoute) { + try { + this.deps.pmpPcpClient.setNetworkRoute({ + gatewayIp: route.gatewayIp, + internalIp: route.internalIp as string, + }) + this.natPmpGatewayReady = true + this.pcpRouteReady = true + return true + } catch (err) { + log.warn( + { err, gatewayIp: route.gatewayIp, internalIp: route.internalIp }, + 'syncPmpPcpNetworkRoute: atomic route update failed; falling back to gateway-only mode' + ) + } + } + try { - this.deps.pmpPcpClient.setGatewayIp(ip) + this.deps.pmpPcpClient.setGatewayIp(route.gatewayIp) + this.natPmpGatewayReady = true + log.debug( + { gatewayIp: route.gatewayIp }, + 'PMP/PCP adapter is in gateway-only mode; PCP is disabled' + ) + return true } catch (err) { log.warn( - { err, ip }, - 'syncPmpPcpGatewayIp: discovery produced invalid gateway IP' + { err, gatewayIp: route.gatewayIp }, + 'syncPmpPcpNetworkRoute: gateway update failed' ) + return false } } @@ -370,13 +460,48 @@ export class NatManager { }) const netOff = this.deps.networkMonitor.onChange((snap: unknown) => { - log.info({ snap }, 'network change detected — re-discovering') - void this.runDiscovery() + this.handleNetworkChange(snap) }) this.unsubscribers.push(settingsOff, readyOff, netOff) } + private handleNetworkChange(snap: unknown): void { + if (!this.lifecycleActive) return + const shouldRemap = + this.networkRemapPending || + this.activeMappings.length > 0 || + this.queuedWork.has('map-configured') || + this.queuedWork.has('remap-all') || + this.state === NatState.Mapping || + this.state === NatState.Active + const hadVisibleMappings = this.activeMappings.length > 0 + + // A topology change invalidates every transition created for the old + // route. Keep the lifecycle active, then enqueue a fresh discovery in the + // new epoch behind whichever transition is currently unwinding. + this.lifecycleEpoch++ + this.queuedWork.clear() + this.gen.bump() + this.abortController?.abort() + this.clearRenewalTimer() + this.networkRemapPending ||= shouldRemap + this.activeMappings = [] + this.gatewayInfo = null + this.stickyProtocol = null + this.natPmpGatewayReady = false + this.pcpRouteReady = false + if (hadVisibleMappings) { + this.deps.onEvent({ type: 'mapping-updated', mappings: [] }) + } + + log.info( + { snap, shouldRemap, hadVisibleMappings }, + 'network change invalidated the previous route; re-discovering' + ) + void this.runDiscovery() + } + private async handleSettingsChanged(): Promise { const nat = this.deps.settingsProvider.getNat() if (!nat.enabled) { @@ -400,22 +525,27 @@ export class NatManager { } } - private async unmapOne(mapping: NatMapping): Promise { - if ( - mapping.method === NatProtocol.Upnp && - this.gatewayInfo?.controlUrl && - this.gatewayInfo.controlHost && - this.gatewayInfo.controlPort - ) { + private async unmapOne( + mapping: NatMapping, + gatewayInfo: NatGatewayInfo | null = this.gatewayInfo + ): Promise { + if (mapping.method === NatProtocol.Upnp) { + if ( + !gatewayInfo?.controlUrl || + !gatewayInfo.controlHost || + !gatewayInfo.controlPort + ) { + return + } await this.deps.upnpClient.unmapPort( { - gatewayIp: this.gatewayInfo.gatewayIp, - controlUrl: this.gatewayInfo.controlUrl, - controlHost: this.gatewayInfo.controlHost, - controlPort: this.gatewayInfo.controlPort, + gatewayIp: gatewayInfo.gatewayIp, + controlUrl: gatewayInfo.controlUrl, + controlHost: gatewayInfo.controlHost, + controlPort: gatewayInfo.controlPort, serviceType: UPNP_WANIP_V1, - manufacturer: this.gatewayInfo.manufacturer ?? '', - modelName: this.gatewayInfo.modelName ?? '', + manufacturer: gatewayInfo.manufacturer ?? '', + modelName: gatewayInfo.modelName ?? '', }, { externalPort: mapping.externalPort, @@ -434,7 +564,7 @@ export class NatManager { ? Buffer.from(mapping.pcpNonce, 'hex') : undefined, }) - } else { + } else if (mapping.method === NatProtocol.NatPmp) { // NAT-PMP: ttl=0 means "remove" per RFC 6886 §3.3 await this.deps.pmpPcpClient.natPmpMap({ protocol: mapping.protocol, @@ -445,55 +575,185 @@ export class NatManager { } } + private async discardStaleMappings( + mappings: NatMapping[], + gatewayInfo: NatGatewayInfo | null + ): Promise { + let pmpCleanupAttempted = false + for (const mapping of mappings) { + if ( + mapping.method === NatProtocol.Pcp || + mapping.method === NatProtocol.NatPmp + ) { + pmpCleanupAttempted = true + } + try { + await this.unmapOne(mapping, gatewayInfo) + } catch (err) { + log.warn( + { err, port: mapping.internalPort, method: mapping.method }, + 'failed to discard mapping from a stopped lifecycle' + ) + } + } + if (pmpCleanupAttempted) { + try { + // A stale cleanup may run after stop() closed the shared UDP client. + // Close again so its one final delete request cannot leave a reopened + // socket or cleanup timer behind in the stopped lifecycle. + await this.deps.pmpPcpClient.close() + } catch (err) { + log.warn({ err }, 'failed to close PMP/PCP client after stale cleanup') + } + } + } + /** - * Run `work` under the shared mutex with coalescing: if the mutex is already - * held, set a dirty flag so the current holder re-runs after completing. - * Eliminates contention warnings during cold-start and network-change bursts. + * Queue work by label, coalescing duplicate labels while preserving ordering + * across different labels. One drain owns the mutex, so a network discovery + * queued during mapping/remapping cannot be lost when that holder releases. */ private async runCoalesced( label: string, - work: () => Promise + work: (lifecycleEpoch: number) => Promise ): Promise { - if (this.mutex.isLocked) { - this.coalesceDirty.set(label, true) - log.debug( - { currentHolder: this.mutex.currentHolder }, - `${label}: coalesced (mutex busy, will re-run after current)` - ) + if (!this.lifecycleActive) { + log.debug({ label }, 'transition ignored while NAT lifecycle is stopped') return } - do { - this.coalesceDirty.set(label, false) - const caller = `${label}@${this.now()}` + const lifecycleEpoch = this.lifecycleEpoch + const alreadyQueued = this.queuedWork.has(label) + this.queuedWork.set(label, { lifecycleEpoch, work }) + if (alreadyQueued || this.mutex.currentHolder?.startsWith(`${label}@`)) { log.debug( - { caller, currentHolder: this.mutex.currentHolder }, - `${label}: attempting mutex` + { currentHolder: this.mutex.currentHolder }, + `${label}: coalesced in transition queue` ) - try { - await this.mutex.runExclusive(async () => { - log.debug({ caller }, `${label}: mutex acquired`) - await work() - }, caller) - log.debug({ caller }, `${label}: mutex released`) - } catch { - // TOCTOU: mutex was free at the isLocked check but acquired before - // runExclusive. Mark dirty so the holder picks it up. - this.coalesceDirty.set(label, true) + } + + if (!this.queueDrain) { + // Start on the next microtask so queueDrain is installed before work can + // synchronously re-enter through a state/event callback. + this.queueDrain = Promise.resolve().then(() => this.drainQueuedWork()) + } + await this.queueDrain + } + + private async drainQueuedWork(): Promise { + try { + while (this.queuedWork.size > 0) { + const next = this.queuedWork.entries().next() + if (next.done) return + const [label, transition] = next.value + this.queuedWork.delete(label) + if (!this.isLifecycleCurrent(transition.lifecycleEpoch)) { + log.debug( + { label, lifecycleEpoch: transition.lifecycleEpoch }, + 'discarding stale queued transition' + ) + continue + } + const caller = `${label}@${this.now()}` log.debug( { caller, currentHolder: this.mutex.currentHolder }, - `${label}: mutex race, will retry` + `${label}: draining transition queue` ) - return + try { + await this.mutex.runExclusive(async () => { + log.debug({ caller }, `${label}: mutex acquired`) + if (!this.isLifecycleCurrent(transition.lifecycleEpoch)) return + await transition.work(transition.lifecycleEpoch) + }, caller) + log.debug({ caller }, `${label}: mutex released`) + } catch (err) { + log.warn( + { err, caller, currentHolder: this.mutex.currentHolder }, + `${label}: queued transition failed` + ) + } } - } while (this.coalesceDirty.get(label)) + } finally { + this.queueDrain = null + } + } + + private isLifecycleCurrent(lifecycleEpoch: number): boolean { + return this.lifecycleActive && lifecycleEpoch === this.lifecycleEpoch } protected async runDiscovery(): Promise { - await this.runCoalesced('discovery', () => this.doDiscovery()) + await this.runCoalesced('discovery', (lifecycleEpoch) => + this.doDiscoveryTransition(lifecycleEpoch) + ) + } + + private async doDiscoveryTransition(lifecycleEpoch: number): Promise { + await this.doDiscovery(lifecycleEpoch) + if (!this.isLifecycleCurrent(lifecycleEpoch) || !this.networkRemapPending) { + return + } + + if (this.state === NatState.Ready) { + this.consumeSatisfiedMappingTransitions(lifecycleEpoch) + // Stay inside the current queue/mutex transition. Calling the public + // method here would await this same drain and deadlock. + await this.doMapConfiguredPorts(lifecycleEpoch) + } + if (!this.isLifecycleCurrent(lifecycleEpoch)) return + if (this.state === NatState.Active) { + // ready/config/remap events can arrive while either mapping request is + // awaiting I/O. The successful B mapping satisfies those same-epoch + // intents too; consume them with no further await before clearing the + // remap marker and returning to the queue drain. + this.consumeSatisfiedMappingTransitions(lifecycleEpoch) + this.networkRemapPending = false + return + } + + // Discovery or immediate remapping on the new route failed. Keep the + // remap intent for the retry cycle, but never expose the previous route's + // gateway or mappings in the meantime. + this.clearRenewalTimer() + this.activeMappings = [] + this.gatewayInfo = null + this.stickyProtocol = null + this.natPmpGatewayReady = false + this.pcpRouteReady = false } - private async doDiscovery(): Promise { + private consumeSatisfiedMappingTransitions(lifecycleEpoch: number): void { + for (const label of ['map-configured', 'remap-all']) { + const queued = this.queuedWork.get(label) + if (queued?.lifecycleEpoch === lifecycleEpoch) { + this.queuedWork.delete(label) + log.debug( + { label, lifecycleEpoch }, + 'direct post-discovery mapping consumed queued transition' + ) + } + } + } + + private async readVerifiedNetworkSnapshot(): Promise<{ + gatewayIp: string + internalIp: string + hash: string + }> { + try { + return this.deps.networkMonitor.verifiedSnapshot + ? await this.deps.networkMonitor.verifiedSnapshot() + : this.deps.networkMonitor.snapshot() + } catch (err) { + log.warn({ err }, 'verified route snapshot failed; using cached snapshot') + return this.deps.networkMonitor.snapshot() + } + } + + private async doDiscovery(lifecycleEpoch: number): Promise { + if (!this.isLifecycleCurrent(lifecycleEpoch)) return this.setState(NatState.Discovering) + this.natPmpGatewayReady = false + this.pcpRouteReady = false const generation = this.gen.bump() this.abortController?.abort() this.abortController = new AbortController() @@ -501,10 +761,23 @@ export class NatManager { // Phase 1 discovery: try UPnP first; NAT-PMP/PCP probe is a fast // UDP request and does not establish gateway info for SOAP, so treat // UPnP as primary. + const network = await this.readVerifiedNetworkSnapshot() + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + !this.gen.isCurrent(generation) + ) { + return + } const upnp = await this.deps.upnpClient.discover({ timeoutMs: 3000, + ...(network.internalIp ? { interfaceAddress: network.internalIp } : {}), }) - if (!this.gen.isCurrent(generation)) return + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + !this.gen.isCurrent(generation) + ) { + return + } if (upnp.ok && upnp.value) { const g = upnp.value as { gatewayIp: string @@ -516,7 +789,7 @@ export class NatManager { modelName: string } this.gatewayInfo = { - internalIp: this.deps.networkMonitor.snapshot().internalIp, + internalIp: network.internalIp, gatewayIp: g.gatewayIp, externalIp: null, controlUrl: g.controlUrl, @@ -526,38 +799,60 @@ export class NatManager { modelName: g.modelName, supportedProtocols: [NatProtocol.Upnp], } - this.syncPmpPcpGatewayIp(g.gatewayIp) + this.syncPmpPcpNetworkRoute({ + gatewayIp: g.gatewayIp, + internalIp: network.internalIp, + }) this.deps.onEvent({ type: 'gateway-changed', info: this.gatewayInfo }) this.setState(NatState.Ready) return } // Fall back to NAT-PMP probe - const pmp = await this.deps.pmpPcpClient.natPmpGetExternalIp({ - timeoutMs: 1000, - }) - if (!this.gen.isCurrent(generation)) return - if (pmp.ok) { - const snap = this.deps.networkMonitor.snapshot() - const pmpVal = pmp.value as { externalIp?: string } | undefined - this.gatewayInfo = { - internalIp: snap.internalIp, - gatewayIp: snap.gatewayIp, - externalIp: pmpVal?.externalIp ?? null, - controlUrl: null, - controlHost: null, - controlPort: null, - manufacturer: null, - modelName: null, - supportedProtocols: [NatProtocol.NatPmp], - } - this.syncPmpPcpGatewayIp(snap.gatewayIp) - this.deps.onEvent({ type: 'gateway-changed', info: this.gatewayInfo }) - this.setState(NatState.Ready) + // The topology can change while UPnP awaits its timeout. Verify the route + // again so PMP never reuses a newly-created interface heuristic. + const pmpNetwork = await this.readVerifiedNetworkSnapshot() + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + !this.gen.isCurrent(generation) + ) { return } + if (this.syncPmpPcpNetworkRoute(pmpNetwork)) { + const pmp = await this.deps.pmpPcpClient.natPmpGetExternalIp({ + timeoutMs: 1000, + }) + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + !this.gen.isCurrent(generation) + ) { + return + } + if (pmp.ok) { + const pmpVal = pmp.value as { externalIp?: string } | undefined + this.gatewayInfo = { + internalIp: pmpNetwork.internalIp, + gatewayIp: pmpNetwork.gatewayIp, + externalIp: pmpVal?.externalIp ?? null, + controlUrl: null, + controlHost: null, + controlPort: null, + manufacturer: null, + modelName: null, + supportedProtocols: [NatProtocol.NatPmp], + } + this.deps.onEvent({ type: 'gateway-changed', info: this.gatewayInfo }) + this.setState(NatState.Ready) + return + } + } - if (!this.gen.isCurrent(generation)) return + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + !this.gen.isCurrent(generation) + ) { + return + } this.setLastError( NatErrorCode.DiscoveryFailed, 'all discovery attempts failed' @@ -565,9 +860,15 @@ export class NatManager { this.setState(NatState.Failed) } - private async doMapConfiguredPorts(): Promise { - if (this.state !== NatState.Ready && this.state !== NatState.Active) return + private async doMapConfiguredPorts(lifecycleEpoch: number): Promise { + if ( + !this.isLifecycleCurrent(lifecycleEpoch) || + (this.state !== NatState.Ready && this.state !== NatState.Active) + ) { + return + } const engine = this.deps.settingsProvider.getEngine() + const cleanupGateway = this.gatewayInfo const ports: Array<{ port: number purpose: NatMappingPurpose @@ -579,8 +880,22 @@ export class NatManager { this.setState(NatState.Mapping) const newMappings: NatMapping[] = [] for (const p of ports) { - const mapping = await this.mapOne(p.port, p.protocol, p.purpose) + const mapping = await this.mapOne( + lifecycleEpoch, + p.port, + p.protocol, + p.purpose + ) + if (!this.isLifecycleCurrent(lifecycleEpoch)) { + await this.discardStaleMappings( + mapping ? [...newMappings, mapping] : newMappings, + cleanupGateway + ) + return + } if (!mapping) { + await this.discardStaleMappings(newMappings, cleanupGateway) + if (!this.isLifecycleCurrent(lifecycleEpoch)) return this.setLastError( NatErrorCode.MappingFailed, `all protocols failed for port ${p.port}` @@ -600,63 +915,74 @@ export class NatManager { } async mapConfiguredPorts(): Promise { - await this.runCoalesced('map-configured', () => this.doMapConfiguredPorts()) + await this.runCoalesced('map-configured', (lifecycleEpoch) => + this.doMapConfiguredPorts(lifecycleEpoch) + ) } async remapAll(): Promise { - const caller = `remap-all@${this.now()}` - log.debug( - { caller, currentHolder: this.mutex.currentHolder }, - 'remapAll: attempting mutex' + await this.runCoalesced('remap-all', (lifecycleEpoch) => + this.doRemapAll(lifecycleEpoch) ) - try { - await this.mutex.runExclusive(async () => { - log.debug({ caller }, 'remapAll: mutex acquired') - if (this.activeMappings.length === 0) { - await this.doMapConfiguredPorts() - return + } + + private async doRemapAll(lifecycleEpoch: number): Promise { + if (!this.isLifecycleCurrent(lifecycleEpoch)) return + if (this.activeMappings.length === 0) { + await this.doMapConfiguredPorts(lifecycleEpoch) + return + } + const cleanupGateway = this.gatewayInfo + const refreshed: NatMapping[] = [] + for (const existing of this.activeMappings) { + const mapping = await this.mapOne( + lifecycleEpoch, + existing.internalPort, + existing.protocol, + existing.purpose, + { + preferred: existing.method, + ...(existing.pcpNonce ? { existingNonce: existing.pcpNonce } : {}), } - const refreshed: NatMapping[] = [] - for (const existing of this.activeMappings) { - const mapping = await this.mapOne( - existing.internalPort, - existing.protocol, - existing.purpose, - { - preferred: existing.method, - ...(existing.pcpNonce - ? { existingNonce: existing.pcpNonce } - : {}), - } + ) + if (!this.isLifecycleCurrent(lifecycleEpoch)) { + await this.discardStaleMappings( + mapping ? [...refreshed, mapping] : refreshed, + cleanupGateway + ) + return + } + if (!mapping) { + // Partial failure: invalidate sticky protocol and attempt full fallback + this.stickyProtocol = null + const retry = await this.mapOne( + lifecycleEpoch, + existing.internalPort, + existing.protocol, + existing.purpose + ) + if (!this.isLifecycleCurrent(lifecycleEpoch)) { + await this.discardStaleMappings( + retry ? [...refreshed, retry] : refreshed, + cleanupGateway ) - if (!mapping) { - // Partial failure: invalidate sticky protocol and attempt full fallback - this.stickyProtocol = null - const retry = await this.mapOne( - existing.internalPort, - existing.protocol, - existing.purpose - ) - if (!retry) { - this.setState(NatState.Failed) - return - } - refreshed.push(retry) - } else { - refreshed.push(mapping) - } + return } - this.activeMappings = refreshed - this.deps.onEvent({ - type: 'mapping-updated', - mappings: [...this.activeMappings], - }) - this.scheduleRenewal() - }, caller) - log.debug({ caller }, 'remapAll: mutex released') - } catch (err) { - log.warn({ err, caller }, 'remapAll mutex contention') + if (!retry) { + this.setState(NatState.Failed) + return + } + refreshed.push(retry) + } else { + refreshed.push(mapping) + } } + this.activeMappings = refreshed + this.deps.onEvent({ + type: 'mapping-updated', + mappings: [...this.activeMappings], + }) + this.scheduleRenewal() } protected scheduleRenewal(): void { @@ -680,6 +1006,7 @@ export class NatManager { } private async mapOne( + lifecycleEpoch: number, internalPort: number, protocol: NatTransportProtocol, purpose: NatMappingPurpose, @@ -702,17 +1029,6 @@ export class NatManager { existingNonce ) if (result) { - this.stickyProtocol = proto - // SPEC FIX: warn when NAT-PMP is SELECTED (success), not when it fails - if (proto === NatProtocol.NatPmp) { - this.deps.onEvent({ - type: 'error', - error: { - code: 'NAT_SECURITY_WARNING', - message: 'NAT-PMP selected; responses are unauthenticated', - }, - }) - } const mapping: NatMapping = { internalPort, externalPort: result.externalPort, @@ -725,8 +1041,21 @@ export class NatManager { lastRenewedAt: this.now(), } if (result.pcpNonce) mapping.pcpNonce = result.pcpNonce + if (!this.isLifecycleCurrent(lifecycleEpoch)) return mapping + this.stickyProtocol = proto + // SPEC FIX: warn when NAT-PMP is SELECTED (success), not when it fails + if (proto === NatProtocol.NatPmp) { + this.deps.onEvent({ + type: 'error', + error: { + code: 'NAT_SECURITY_WARNING', + message: 'NAT-PMP selected; responses are unauthenticated', + }, + }) + } return mapping } + if (!this.isLifecycleCurrent(lifecycleEpoch)) return null } return null } @@ -741,6 +1070,7 @@ export class NatManager { try { switch (proto) { case NatProtocol.Pcp: { + if (!this.pcpRouteReady) return null const r = await this.deps.pmpPcpClient.pcpMap({ internalPort, externalPort: internalPort, @@ -767,6 +1097,7 @@ export class NatManager { return mapped } case NatProtocol.NatPmp: { + if (!this.natPmpGatewayReady) return null const r = await this.deps.pmpPcpClient.natPmpMap({ protocol, internalPort, @@ -789,6 +1120,7 @@ export class NatManager { !info?.controlUrl || !info.controlHost || !info.controlPort || + !info.internalIp || info.controlPort < 1 || info.controlPort > 65535 ) { @@ -805,7 +1137,7 @@ export class NatManager { modelName: info.modelName ?? '', }, { - internalIp: this.deps.networkMonitor.snapshot().internalIp, + internalIp: info.internalIp, internalPort, externalPort: internalPort, protocol, diff --git a/src/net/mock-udp-socket.ts b/src/net/mock-udp-socket.ts index 6cb6697..30a8ee3 100644 --- a/src/net/mock-udp-socket.ts +++ b/src/net/mock-udp-socket.ts @@ -19,6 +19,7 @@ export class MockUdpSocket implements UdpSocket { public boundPort: number | null = null public boundAddress: string | null = null public memberships: Array<{ multicast: string; iface?: string }> = [] + public multicastInterface: string | null = null public ttl: number | null = null public closed = false @@ -35,6 +36,11 @@ export class MockUdpSocket implements UdpSocket { this.memberships.push(iface ? { multicast, iface } : { multicast }) } + setMulticastInterface(interfaceAddress: string): void { + if (this.closed) throw new Error('socket closed') + this.multicastInterface = interfaceAddress + } + setMulticastTTL(ttl: number): void { if (this.closed) throw new Error('socket closed') this.ttl = ttl diff --git a/src/net/node-udp-socket.test.ts b/src/net/node-udp-socket.test.ts index 48abd25..0e186cd 100644 --- a/src/net/node-udp-socket.test.ts +++ b/src/net/node-udp-socket.test.ts @@ -17,6 +17,7 @@ class FakeSocket extends EventEmitter { callback() ) addMembership = vi.fn() + setMulticastInterface = vi.fn() setMulticastTTL = vi.fn() send = vi.fn( ( @@ -78,6 +79,7 @@ describe('NodeUdpSocket', () => { const payload = Buffer.from('hello') subject.addMembership('239.255.255.250', '192.168.1.10') + subject.setMulticastInterface('192.168.1.10') subject.setMulticastTTL(4) await subject.send(payload, 1900, '239.255.255.250') @@ -85,6 +87,7 @@ describe('NodeUdpSocket', () => { '239.255.255.250', '192.168.1.10' ) + expect(socket.setMulticastInterface).toHaveBeenCalledWith('192.168.1.10') expect(socket.setMulticastTTL).toHaveBeenCalledWith(4) expect(socket.send).toHaveBeenCalledWith( payload, @@ -152,6 +155,9 @@ describe('NodeUdpSocket', () => { subject.send(Buffer.from('x'), 1, '127.0.0.1') ).rejects.toThrow('socket closed') expect(() => subject.addMembership('239.0.0.1')).toThrow('socket closed') + expect(() => subject.setMulticastInterface('192.168.1.10')).toThrow( + 'socket closed' + ) expect(() => subject.setMulticastTTL(1)).toThrow('socket closed') }) }) diff --git a/src/net/udp-socket.test.ts b/src/net/udp-socket.test.ts index 0bd933d..8fd0d5d 100644 --- a/src/net/udp-socket.test.ts +++ b/src/net/udp-socket.test.ts @@ -35,6 +35,9 @@ describe('MockUdpSocket', () => { ) await expect(s.bind()).rejects.toThrow('socket closed') expect(() => s.addMembership('239.255.255.250')).toThrow('socket closed') + expect(() => s.setMulticastInterface?.('192.168.1.10')).toThrow( + 'socket closed' + ) expect(() => s.setMulticastTTL(4)).toThrow('socket closed') }) }) diff --git a/src/net/udp-socket.ts b/src/net/udp-socket.ts index 0473a95..ba6d1c2 100644 --- a/src/net/udp-socket.ts +++ b/src/net/udp-socket.ts @@ -16,6 +16,7 @@ export type UdpMessageListener = (msg: Buffer, rinfo: UdpRemoteInfo) => void export interface UdpSocket { bind(port?: number, address?: string): Promise addMembership(multicastAddress: string, interfaceAddress?: string): void + setMulticastInterface?(interfaceAddress: string): void setMulticastTTL(ttl: number): void send(msg: Buffer, port: number, address: string): Promise onMessage(listener: UdpMessageListener): void @@ -59,6 +60,11 @@ export class NodeUdpSocket implements UdpSocket { this.socket.addMembership(multicastAddress, interfaceAddress) } + setMulticastInterface(interfaceAddress: string): void { + if (!this.socket) throw new Error('socket closed') + this.socket.setMulticastInterface(interfaceAddress) + } + setMulticastTTL(ttl: number): void { if (!this.socket) throw new Error('socket closed') this.socket.setMulticastTTL(ttl) diff --git a/src/network-monitor.ts b/src/network-monitor.ts index 986becf..7421015 100644 --- a/src/network-monitor.ts +++ b/src/network-monitor.ts @@ -1,5 +1,5 @@ -import os from 'node:os' import { natLogger } from './logger.js' +import { createCachedNetworkRouteResolver } from './network-route.js' const log = natLogger('network-monitor') @@ -13,6 +13,7 @@ export interface NetworkMonitorOptions { intervalMs?: number stableRounds?: number // Consecutive identical snapshots before emitting a change snapshotFn?: () => NetworkSnapshot // Injectable for tests + verifiedSnapshotFn?: () => Promise } export const DEFAULT_INTERVAL_MS = 5000 @@ -24,6 +25,7 @@ export class NetworkMonitor { private readonly intervalMs: number private readonly stableRounds: number private readonly snapshotFn: () => NetworkSnapshot + private readonly verifiedSnapshotFn: () => Promise private timer: NodeJS.Timeout | null = null private listeners = new Set() private established: NetworkSnapshot | null = null @@ -33,7 +35,13 @@ export class NetworkMonitor { constructor(opts: NetworkMonitorOptions = {}) { this.intervalMs = Math.max(500, opts.intervalMs ?? DEFAULT_INTERVAL_MS) this.stableRounds = Math.max(1, opts.stableRounds ?? DEFAULT_STABLE_ROUNDS) - this.snapshotFn = opts.snapshotFn ?? defaultSnapshotFn + const defaultSource = createDefaultSnapshotSource() + this.snapshotFn = opts.snapshotFn ?? defaultSource.snapshot + this.verifiedSnapshotFn = + opts.verifiedSnapshotFn ?? + (opts.snapshotFn + ? async () => this.snapshotFn() + : defaultSource.verifiedSnapshot) } onChange(listener: NetworkChangeListener): () => void { @@ -64,6 +72,15 @@ export class NetworkMonitor { } } + async verifiedSnapshot(): Promise { + try { + return await this.verifiedSnapshotFn() + } catch (err) { + log.warn({ err }, 'verified snapshot failed; using current snapshot') + return this.snapshot() + } + } + private poll(): void { let snap: NetworkSnapshot try { @@ -102,32 +119,23 @@ export class NetworkMonitor { } } -function defaultSnapshotFn(): NetworkSnapshot { - const ifaces = os.networkInterfaces() - let internalIp = '' - let gatewayIp = '' - // Best-effort: first IPv4 non-internal address. True default gateway - // detection requires platform-specific calls; Phase 1 uses the presence - // of interfaces as a proxy. - for (const iface of Object.values(ifaces)) { - if (!iface) continue - for (const addr of iface) { - if (addr.family === 'IPv4' && !addr.internal) { - internalIp = addr.address - // Derive probable gateway as .1 on the same /24 — heuristic; - // NatManager re-discovers - const parts = addr.address.split('.') - if (parts.length === 4) { - gatewayIp = `${parts[0]}.${parts[1]}.${parts[2]}.1` - } - break - } +function createDefaultSnapshotSource(): { + snapshot: () => NetworkSnapshot + verifiedSnapshot: () => Promise +} { + const resolveRoute = createCachedNetworkRouteResolver() + const toSnapshot = (route: { + gatewayIp: string + internalIp: string + }): NetworkSnapshot => { + return { + gatewayIp: route.gatewayIp, + internalIp: route.internalIp, + hash: `${route.gatewayIp}|${route.internalIp}`, } - if (internalIp) break } return { - gatewayIp, - internalIp, - hash: `${gatewayIp}|${internalIp}`, + snapshot: () => toSnapshot(resolveRoute()), + verifiedSnapshot: async () => toSnapshot(await resolveRoute.verified()), } } diff --git a/src/network-route.test.ts b/src/network-route.test.ts new file mode 100644 index 0000000..983b714 --- /dev/null +++ b/src/network-route.test.ts @@ -0,0 +1,345 @@ +import { readFileSync } from 'node:fs' +import type os from 'node:os' +import { describe, expect, it, vi } from 'vitest' +import { tick } from './__test__/utils.js' +import { NetworkMonitor, type NetworkSnapshot } from './network-monitor.js' +import { + createCachedNetworkRouteResolver, + DEFAULT_ROUTE_CACHE_MAX_AGE_MS, + parseWindowsIpv4DefaultRoutes, + resolveDefaultNetworkRoute, + resolveWindowsRouteExecutable, +} from './network-route.js' + +const TAILSCALE_ROUTE_PRINT = readFileSync( + new URL( + './__test__/fixtures/windows-route-print-tailscale.txt', + import.meta.url + ), + 'utf8' +) + +type NetworkInterfaces = ReturnType + +function ipv4( + address: string, + netmask: string, + internal = false +): NonNullable[number] { + return { + address, + netmask, + family: 'IPv4', + mac: '00:00:00:00:00:00', + internal, + cidr: `${address}/24`, + } +} + +describe('Windows default route resolution', () => { + it('resolves route.exe only beneath an absolute SystemRoot', () => { + expect(resolveWindowsRouteExecutable('C:\\Windows')).toBe( + 'C:\\Windows\\System32\\route.exe' + ) + expect(resolveWindowsRouteExecutable('Windows')).toBeNull() + expect(resolveWindowsRouteExecutable('')).toBeNull() + expect( + resolveWindowsRouteExecutable('\\\\server\\share\\Windows') + ).toBeNull() + }) + + it('parses only complete numeric IPv4 default-route rows', () => { + expect(parseWindowsIpv4DefaultRoutes(TAILSCALE_ROUTE_PRINT)).toEqual([ + { + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + metric: 25, + }, + ]) + }) + + it('selects the physical default route instead of a Tailscale interface', () => { + const resolved = resolveDefaultNetworkRoute({ + platform: 'win32', + interfaces: { + Tailscale: [ipv4('169.254.40.20', '255.255.0.0')], + 'Wi-Fi': [ipv4('10.0.0.42', '255.255.255.0')], + }, + windowsRouteTable: TAILSCALE_ROUTE_PRINT, + }) + + expect(resolved).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + }) + + it('uses the lowest metric among physical routes', () => { + const resolved = resolveDefaultNetworkRoute({ + platform: 'win32', + interfaces: { + Ethernet: [ipv4('192.168.1.20', '255.255.255.0')], + 'Wi-Fi': [ipv4('10.0.0.42', '255.255.255.0')], + }, + windowsRouteTable: ` + 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.20 55 + 0.0.0.0 0.0.0.0 10.0.0.1 10.0.0.42 25 + `, + }) + + expect(resolved).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + }) + + it('prefers a physical route over a lower-metric virtual route', () => { + const resolved = resolveDefaultNetworkRoute({ + platform: 'win32', + interfaces: { + 'Tailscale Tunnel': [ipv4('100.100.20.30', '255.255.255.255')], + Ethernet: [ipv4('192.168.1.20', '255.255.255.0')], + }, + windowsRouteTable: ` + 0.0.0.0 0.0.0.0 100.100.20.1 100.100.20.30 1 + 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.20 25 + `, + }) + + expect(resolved).toEqual({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.20', + }) + }) + + it('falls back to a physical private interface before route data arrives', () => { + const resolved = resolveDefaultNetworkRoute({ + platform: 'win32', + interfaces: { + Tailscale: [ipv4('169.254.40.20', '255.255.0.0')], + 'Hyper-V Virtual Ethernet': [ipv4('172.20.0.1', '255.255.240.0')], + 'Wi-Fi': [ipv4('10.8.4.42', '255.255.252.0')], + }, + }) + + expect(resolved).toEqual({ + gatewayIp: '10.8.4.1', + internalIp: '10.8.4.42', + }) + }) + + it('returns an empty snapshot when only link-local interfaces exist', () => { + const resolved = resolveDefaultNetworkRoute({ + platform: 'win32', + interfaces: { + Tailscale: [ipv4('169.254.40.20', '255.255.0.0')], + }, + windowsRouteTable: TAILSCALE_ROUTE_PRINT, + }) + + expect(resolved).toEqual({ gatewayIp: '', internalIp: '' }) + }) +}) + +describe('background network route resolution', () => { + const wlanInterfaces: NetworkInterfaces = { + 'Wi-Fi': [ipv4('10.0.0.42', '255.255.255.0')], + } + const firstRoute = '0.0.0.0 0.0.0.0 10.0.0.1 10.0.0.42 25' + const changedRoute = '0.0.0.0 0.0.0.0 10.0.0.254 10.0.0.42 5' + + it('awaits a verified route instead of accepting the first NIC fallback', async () => { + let reads = 0 + const interfaces: NetworkInterfaces = { + Ethernet: [ipv4('192.168.1.20', '255.255.255.0')], + 'Wi-Fi': [ipv4('10.0.0.42', '255.255.255.0')], + } + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => interfaces, + readWindowsRouteTable: async () => { + reads++ + return changedRoute + }, + now: () => 1_000, + }) + + expect(resolve()).toEqual({ + gatewayIp: '192.168.1.1', + internalIp: '192.168.1.20', + }) + await expect(resolve.verified()).resolves.toEqual({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + }) + expect(reads).toBe(1) + }) + + it('returns fallback immediately and single-flights adjacent calls', async () => { + let reads = 0 + let finishRead: ((output: string) => void) | undefined + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => wlanInterfaces, + readWindowsRouteTable: () => { + reads++ + return new Promise((resolveRead) => { + finishRead = resolveRead + }) + }, + now: () => 1_000, + }) + + expect(resolve()).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + expect(resolve()).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + expect(reads).toBe(0) + await Promise.resolve() + expect(reads).toBe(1) + + finishRead?.(changedRoute) + await tick() + expect(resolve()).toEqual({ + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + }) + }) + + it('refreshes route and metric changes after cache expiry', async () => { + let reads = 0 + let now = 0 + let routeTable = firstRoute + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => wlanInterfaces, + readWindowsRouteTable: async () => { + reads++ + return routeTable + }, + now: () => now, + }) + + expect(resolve().gatewayIp).toBe('10.0.0.1') + await tick() + expect(reads).toBe(1) + + routeTable = changedRoute + now = DEFAULT_ROUTE_CACHE_MAX_AGE_MS - 1 + expect(resolve().gatewayIp).toBe('10.0.0.1') + expect(reads).toBe(1) + + now = DEFAULT_ROUTE_CACHE_MAX_AGE_MS + expect(resolve().gatewayIp).toBe('10.0.0.1') + await tick() + expect(resolve().gatewayIp).toBe('10.0.0.254') + expect(reads).toBe(2) + }) + + it('negatively caches route-command failures', async () => { + let reads = 0 + let now = 0 + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => wlanInterfaces, + readWindowsRouteTable: async () => { + reads++ + throw new Error('route.exe timed out') + }, + now: () => now, + }) + + expect(resolve()).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + await tick() + expect(resolve()).toEqual({ + gatewayIp: '10.0.0.1', + internalIp: '10.0.0.42', + }) + expect(reads).toBe(1) + + now = DEFAULT_ROUTE_CACHE_MAX_AGE_MS + resolve() + await tick() + expect(reads).toBe(2) + }) + + it('refreshes immediately when interface topology changes', async () => { + let reads = 0 + let interfaces = wlanInterfaces + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => interfaces, + readWindowsRouteTable: async () => { + reads++ + return firstRoute + }, + now: () => 1_000, + }) + + expect(resolve().gatewayIp).toBe('10.0.0.1') + await tick() + interfaces = { + ...wlanInterfaces, + Tailscale: [ipv4('169.254.40.20', '255.255.0.0')], + } + expect(resolve().gatewayIp).toBe('10.0.0.1') + await tick() + expect(reads).toBe(2) + }) + + it('observes a same-interface route change within four default polls', async () => { + vi.useFakeTimers() + let reads = 0 + let now = 0 + let routeTable = firstRoute + const resolve = createCachedNetworkRouteResolver({ + platform: 'win32', + readInterfaces: () => wlanInterfaces, + readWindowsRouteTable: async () => { + reads++ + return routeTable + }, + now: () => now, + }) + const snapshot = (): NetworkSnapshot => { + const route = resolve() + return { ...route, hash: `${route.gatewayIp}|${route.internalIp}` } + } + const monitor = new NetworkMonitor({ + intervalMs: 5_000, + stableRounds: 2, + snapshotFn: snapshot, + }) + const changes: NetworkSnapshot[] = [] + monitor.onChange((change) => changes.push(change)) + + try { + monitor.start() + await vi.advanceTimersByTimeAsync(0) + routeTable = changedRoute + for (const timestamp of [5_000, 10_000, 15_000, 20_000]) { + now = timestamp + await vi.advanceTimersByTimeAsync(5_000) + } + + expect(changes).toEqual([ + { + gatewayIp: '10.0.0.254', + internalIp: '10.0.0.42', + hash: '10.0.0.254|10.0.0.42', + }, + ]) + expect(reads).toBe(3) + } finally { + monitor.stop() + vi.useRealTimers() + } + }) +}) diff --git a/src/network-route.ts b/src/network-route.ts new file mode 100644 index 0000000..41f2d9b --- /dev/null +++ b/src/network-route.ts @@ -0,0 +1,409 @@ +import { execFile } from 'node:child_process' +import os from 'node:os' +import path from 'node:path' +import { + isIpv4String, + isLinkLocalIpv4, + isLoopbackIpv4, + isPrivateIpv4, + parseIpv4, +} from './codecs/ip-utils.js' + +const MAX_ROUTE_PRINT_BYTES = 1024 * 1024 +const ROUTE_PRINT_TIMEOUT_MS = 1000 + +/** + * NetworkMonitor.snapshot() remains synchronous by returning cached or + * interface-derived data while route.exe refreshes in the background. + */ +export const DEFAULT_ROUTE_CACHE_MAX_AGE_MS = 10_000 + +const VIRTUAL_INTERFACE_RE = + /(?:tailscale|wireguard|wintun|zerotier|\bvpn\b|\btap\b|hyper-v|vethernet|vmware|virtualbox|docker|\bwsl\b)/i + +export interface ResolvedNetworkRoute { + gatewayIp: string + internalIp: string +} + +export interface WindowsIpv4DefaultRoute extends ResolvedNetworkRoute { + metric: number +} + +interface NetworkCandidate { + address: string + name: string + netmask: string + virtual: boolean +} + +interface NetworkRouteOptions { + platform?: NodeJS.Platform + interfaces?: ReturnType + windowsRouteTable?: string +} + +interface CachedNetworkRouteOptions { + platform?: NodeJS.Platform + readInterfaces?: () => ReturnType + readWindowsRouteTable?: () => Promise + now?: () => number + maxAgeMs?: number +} + +interface CachedNetworkRoute { + fingerprint: string + refreshedAt: number + route: ResolvedNetworkRoute +} + +export interface CachedNetworkRouteResolver { + (): ResolvedNetworkRoute + verified(): Promise +} + +interface RefreshContext { + fallback: ResolvedNetworkRoute + fingerprint: string + interfaces: ReturnType +} + +/** + * Create a non-blocking synchronous route snapshot backed by async refreshes. + * + * Interface topology changes bypass the cache immediately (for example when + * Tailscale connects or disconnects). Route/metric-only changes are detected + * when maxAgeMs expires. Only one route command runs at a time. Failures are + * negatively cached so endpoint-policy blocks cannot cause a process storm. + */ +export function createCachedNetworkRouteResolver( + options: CachedNetworkRouteOptions = {} +): CachedNetworkRouteResolver { + const platform = options.platform ?? process.platform + const readInterfaces = + options.readInterfaces ?? (() => os.networkInterfaces()) + const now = options.now ?? (() => Date.now()) + const maxAgeMs = Math.max( + 1, + options.maxAgeMs ?? DEFAULT_ROUTE_CACHE_MAX_AGE_MS + ) + let cached: CachedNetworkRoute | null = null + let inFlight: Promise | null = null + let inFlightFingerprint = '' + let latestFingerprint = '' + let pending: RefreshContext | null = null + + const startRefresh = (context: RefreshContext): Promise | null => { + if (platform !== 'win32') return null + if (inFlight) { + pending = inFlightFingerprint === context.fingerprint ? null : context + return inFlight + } + + inFlightFingerprint = context.fingerprint + const task = Promise.resolve() + .then(options.readWindowsRouteTable ?? readWindowsRouteTable) + .then((output) => { + if (latestFingerprint !== context.fingerprint) return + cached = { + fingerprint: context.fingerprint, + refreshedAt: now(), + route: resolveDefaultNetworkRoute({ + platform, + interfaces: context.interfaces, + windowsRouteTable: output, + }), + } + }) + .catch(() => { + if (latestFingerprint !== context.fingerprint) return + cached = { + fingerprint: context.fingerprint, + refreshedAt: now(), + route: context.fallback, + } + }) + .finally(() => { + if (inFlight !== task) return + inFlight = null + inFlightFingerprint = '' + const next = pending + pending = null + if (next && next.fingerprint === latestFingerprint) { + startRefresh(next) + } + }) + inFlight = task + return task + } + + const resolve = (): ResolvedNetworkRoute => { + const interfaces = readInterfaces() + const fingerprint = networkInterfacesFingerprint(interfaces) + latestFingerprint = fingerprint + const timestamp = now() + const fallback = resolveDefaultNetworkRoute({ platform, interfaces }) + const matchingCache = cached?.fingerprint === fingerprint ? cached : null + const route = matchingCache?.route ?? fallback + const cacheFresh = + matchingCache !== null && + timestamp >= matchingCache.refreshedAt && + timestamp - matchingCache.refreshedAt < maxAgeMs + if (!cacheFresh) { + startRefresh({ fallback, fingerprint, interfaces }) + } + return route + } + + resolve.verified = async (): Promise => { + if (platform !== 'win32') return resolve() + + // If topology changes while route.exe is in flight, loop onto the pending + // single-flight refresh so the returned route always matches the latest + // interface fingerprint observed here. + for (;;) { + const interfaces = readInterfaces() + const fingerprint = networkInterfacesFingerprint(interfaces) + latestFingerprint = fingerprint + const timestamp = now() + const fallback = resolveDefaultNetworkRoute({ platform, interfaces }) + const matchingCache = cached?.fingerprint === fingerprint ? cached : null + const cacheFresh = + matchingCache !== null && + timestamp >= matchingCache.refreshedAt && + timestamp - matchingCache.refreshedAt < maxAgeMs + if (cacheFresh) return matchingCache.route + + const refresh = startRefresh({ fallback, fingerprint, interfaces }) + if (refresh) await refresh + + const latestInterfaces = readInterfaces() + const latest = networkInterfacesFingerprint(latestInterfaces) + if (latest !== fingerprint) continue + const verifiedCache = cached?.fingerprint === fingerprint ? cached : null + if (verifiedCache) return verifiedCache.route + if (inFlight) continue + return fallback + } + } + + return resolve +} + +/** + * Resolve the IPv4 route that should reach the local NAT gateway. + * + * Windows gets its gateway and source address from the kernel route table. + * Other platforms, and Windows installations where route.exe is unavailable, + * use a conservative interface fallback. + */ +export function resolveDefaultNetworkRoute( + options: NetworkRouteOptions = {} +): ResolvedNetworkRoute { + const platform = options.platform ?? process.platform + const interfaces = options.interfaces ?? os.networkInterfaces() + const candidates = collectNetworkCandidates(interfaces) + + if (platform === 'win32' && options.windowsRouteTable !== undefined) { + const route = selectWindowsDefaultRoute( + parseWindowsIpv4DefaultRoutes(options.windowsRouteTable), + candidates + ) + if (route) { + return { + gatewayIp: route.gatewayIp, + internalIp: route.internalIp, + } + } + } + + return fallbackNetworkRoute(candidates) +} + +/** Parse numeric Active Routes rows from locale-independent route.exe output. */ +export function parseWindowsIpv4DefaultRoutes( + output: string +): WindowsIpv4DefaultRoute[] { + if (output.length > MAX_ROUTE_PRINT_BYTES) return [] + + const routes: WindowsIpv4DefaultRoute[] = [] + for (const line of output.split(/\r?\n/)) { + const columns = line.trim().split(/\s+/) + if ( + columns.length !== 5 || + columns[0] !== '0.0.0.0' || + columns[1] !== '0.0.0.0' + ) { + continue + } + + const gatewayIp = columns[2] ?? '' + const internalIp = columns[3] ?? '' + const metricText = columns[4] ?? '' + if (!isUsableRouteAddress(gatewayIp) || !isUsableRouteAddress(internalIp)) { + continue + } + if (!/^\d+$/.test(metricText)) continue + const metric = Number(metricText) + if (!Number.isSafeInteger(metric)) continue + + routes.push({ gatewayIp, internalIp, metric }) + } + + return routes +} + +export function resolveWindowsRouteExecutable( + systemRoot = process.env.SystemRoot +): string | null { + if (!systemRoot) return null + const normalized = path.win32.normalize(systemRoot) + if (!/^[A-Za-z]:\\/.test(normalized) || !path.win32.isAbsolute(normalized)) { + return null + } + return path.win32.join(normalized, 'System32', 'route.exe') +} + +function readWindowsRouteTable(): Promise { + const executable = resolveWindowsRouteExecutable() + if (!executable) { + return Promise.reject( + new Error('SystemRoot is missing or is not an absolute Windows path') + ) + } + return new Promise((resolve, reject) => { + execFile( + executable, + ['PRINT', '-4'], + { + encoding: 'utf8', + maxBuffer: MAX_ROUTE_PRINT_BYTES, + timeout: ROUTE_PRINT_TIMEOUT_MS, + windowsHide: true, + }, + (error, stdout) => { + if (error) reject(error) + else resolve(stdout) + } + ) + }) +} + +function selectWindowsDefaultRoute( + routes: readonly WindowsIpv4DefaultRoute[], + candidates: readonly NetworkCandidate[] +): WindowsIpv4DefaultRoute | null { + const candidateByAddress = new Map() + for (const candidate of candidates) { + const existing = candidateByAddress.get(candidate.address) + if (!existing || (existing.virtual && !candidate.virtual)) { + candidateByAddress.set(candidate.address, candidate) + } + } + + const available = routes.filter((route) => + candidateByAddress.has(route.internalIp) + ) + available.sort((a, b) => { + const aVirtual = candidateByAddress.get(a.internalIp)?.virtual ? 1 : 0 + const bVirtual = candidateByAddress.get(b.internalIp)?.virtual ? 1 : 0 + return aVirtual - bVirtual || a.metric - b.metric + }) + return available[0] ?? null +} + +function collectNetworkCandidates( + interfaces: ReturnType +): NetworkCandidate[] { + const candidates: NetworkCandidate[] = [] + for (const [name, addresses] of Object.entries(interfaces)) { + if (!addresses) continue + for (const address of addresses) { + if ( + address.family !== 'IPv4' || + address.internal || + !isUsableRouteAddress(address.address) + ) { + continue + } + candidates.push({ + address: address.address, + name, + netmask: address.netmask, + virtual: VIRTUAL_INTERFACE_RE.test(name), + }) + } + } + return candidates +} + +function networkInterfacesFingerprint( + interfaces: ReturnType +): string { + const entries: string[] = [] + for (const [name, addresses] of Object.entries(interfaces)) { + if (!addresses) continue + for (const address of addresses) { + if (address.family !== 'IPv4') continue + entries.push( + JSON.stringify([ + name, + address.address, + address.netmask, + address.internal, + ]) + ) + } + } + return entries.sort().join('\n') +} + +function fallbackNetworkRoute( + candidates: readonly NetworkCandidate[] +): ResolvedNetworkRoute { + const ranked = [...candidates].sort((a, b) => { + const aScore = (a.virtual ? 100 : 0) + (isPrivateIpv4(a.address) ? 0 : 10) + const bScore = (b.virtual ? 100 : 0) + (isPrivateIpv4(b.address) ? 0 : 10) + return aScore - bScore + }) + const selected = ranked[0] + if (!selected) return { gatewayIp: '', internalIp: '' } + return { + gatewayIp: deriveProbableGateway(selected.address, selected.netmask), + internalIp: selected.address, + } +} + +function isUsableRouteAddress(address: string): boolean { + if ( + !isIpv4String(address) || + isLinkLocalIpv4(address) || + isLoopbackIpv4(address) || + address === '0.0.0.0' + ) { + return false + } + const parsed = parseIpv4(address) + return parsed.ok && parsed.value[0] > 0 && parsed.value[0] < 224 +} + +function deriveProbableGateway(address: string, netmask: string): string { + const ip = ipv4ToUint32(address) + const mask = ipv4ToUint32(netmask) + if (ip === null || mask === null) return '' + const hostMask = ~mask >>> 0 + if (hostMask < 2) return '' + return uint32ToIpv4(((ip & mask) >>> 0) + 1) +} + +function ipv4ToUint32(address: string): number | null { + const parsed = parseIpv4(address) + if (!parsed.ok) return null + const [a, b, c, d] = parsed.value + return (((a << 24) | (b << 16) | (c << 8) | d) >>> 0) as number +} + +function uint32ToIpv4(value: number): string { + const normalized = value >>> 0 + return `${normalized >>> 24}.${(normalized >>> 16) & 0xff}.${(normalized >>> 8) & 0xff}.${normalized & 0xff}` +} From 1a1f810cd88df51667183c8d87f4cc96a5a9add0 Mon Sep 17 00:00:00 2001 From: Dr_rOot Date: Fri, 28 Aug 2026 10:37:49 +0800 Subject: [PATCH 2/2] chore(release): prepare @motrix/nat 0.1.1 --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index e4bca1e..21d4c11 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@motrix/nat", - "version": "0.1.0", + "version": "0.1.1", "description": "Dependency-free UPnP IGD, NAT-PMP, PCP, and STUN for Node.js", "license": "MIT", "author": "Motrix", @@ -47,7 +47,7 @@ "engines": { "node": ">=22" }, - "packageManager": "pnpm@11.13.0", + "packageManager": "pnpm@11.24.0", "publishConfig": { "access": "public" },