Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ function valueOrThrow<T>(result: ParseResult<T>): 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:

Expand Down Expand Up @@ -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

Expand Down
10 changes: 7 additions & 3 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,9 @@ function valueOrThrow<T>(result: ParseResult<T>): T {
```

因此,预期内的网络错误、校验失败和协议错误无需通过异常控制流程处理。构造参数
误用或命令式更新中的无效值仍可能抛出异常;例如,传入无效 IPv4 地址时,
`PmpPcpClient.setGatewayIp()` 会抛出 `RangeError`。
误用或命令式更新中的无效值仍可能抛出异常;例如,向
`PmpPcpClient.setNetworkRoute()` 传入无效的网关或内网 IPv4 地址时会抛出
`RangeError`。

`NatErrorCode` 定义了稳定的包级错误码:

Expand Down Expand Up @@ -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 公网端点发现

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -47,7 +47,7 @@
"engines": {
"node": ">=22"
},
"packageManager": "pnpm@11.13.0",
"packageManager": "pnpm@11.24.0",
"publishConfig": {
"access": "public"
},
Expand Down
20 changes: 20 additions & 0 deletions src/__test__/fixtures/windows-route-print-tailscale.txt
Original file line number Diff line number Diff line change
@@ -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
===========================================================================
49 changes: 49 additions & 0 deletions src/clients/pmp-pcp-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
})
})
46 changes: 41 additions & 5 deletions src/clients/pmp-pcp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
buildExternalIpRequest,
buildMappingRequest,
buildPcpMapRequest,
ipv4ToBuffer,
isIpv4String,
NATPMP_OPCODE_EXTERNAL_IP,
NATPMP_OPCODE_MAP_TCP,
Expand Down Expand Up @@ -37,6 +38,11 @@ export interface PmpPcpClientOptions {
now?: () => number
}

export interface PmpPcpNetworkRoute {
gatewayIp: string
internalIp: string
}

interface PendingNonce {
nonce: Buffer
expiresAt: number
Expand Down Expand Up @@ -65,7 +71,7 @@ export class PmpPcpClient {
private socketReady: Promise<void> | 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<string, PendingNonce>()
Expand All @@ -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
Expand All @@ -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<ParseResult<Extract<NatPmpResponse, { kind: 'external-ip' }>>> {
Expand Down
28 changes: 28 additions & 0 deletions src/clients/upnp-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
17 changes: 16 additions & 1 deletion src/clients/upnp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
SSDP_MULTICAST_PORT,
} from '../codecs/index.js'
import {
isIpv4String,
isLinkLocalIpv4,
isPrivateIpv4,
isValidPort,
Expand All @@ -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
Expand Down Expand Up @@ -86,6 +89,13 @@ export class UpnpClient {
async discover(
options: DiscoverOptions = {}
): Promise<ParseResult<DiscoveredGateway>> {
const interfaceAddress = options.interfaceAddress
if (interfaceAddress && !isIpv4String(interfaceAddress)) {
return parseErr(
NatErrorCode.DiscoveryFailed,
'invalid SSDP interface address'
)
}
if (this.discovering) {
return parseErr(
NatErrorCode.DiscoveryFailed,
Expand Down Expand Up @@ -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),
Expand Down
Loading