@libp2p/upnp-nat 2.0.12-98b43045c → 2.0.12-b02ea9b6e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/upnp-nat.ts CHANGED
@@ -1,82 +1,53 @@
1
1
  import { upnpNat } from '@achingbrain/nat-port-mapper'
2
- import { isIPv4, isIPv6 } from '@chainsafe/is-ip'
3
- import { InvalidParametersError, serviceCapabilities, setMaxListeners, start, stop } from '@libp2p/interface'
2
+ import { serviceCapabilities, setMaxListeners, start, stop } from '@libp2p/interface'
4
3
  import { debounce } from '@libp2p/utils/debounce'
5
- import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'
6
- import { isPrivate } from '@libp2p/utils/multiaddr/is-private'
7
- import { isPrivateIp } from '@libp2p/utils/private-ip'
8
- import { QUICV1, TCP, WebSockets, WebSocketsSecure, WebTransport } from '@multiformats/multiaddr-matcher'
9
- import { dynamicExternalAddress, staticExternalAddress } from './check-external-address.js'
10
- import { DoubleNATError, InvalidIPAddressError } from './errors.js'
11
- import type { ExternalAddress } from './check-external-address.js'
4
+ import { DEFAULT_PORT_MAPPING_TTL } from './constants.js'
5
+ import { GatewayFinder } from './gateway-finder.js'
6
+ import { UPnPPortMapper } from './upnp-port-mapper.js'
12
7
  import type { UPnPNATComponents, UPnPNATInit, UPnPNAT as UPnPNATInterface } from './index.js'
13
- import type { NatAPI, MapPortOptions } from '@achingbrain/nat-port-mapper'
14
- import type { Libp2pEvents, Logger, Startable, TypedEventTarget } from '@libp2p/interface'
15
- import type { AddressManager } from '@libp2p/interface-internal'
8
+ import type { Gateway, UPnPNAT as UPnPNATClient } from '@achingbrain/nat-port-mapper'
9
+ import type { Logger, Startable } from '@libp2p/interface'
16
10
  import type { DebouncedFunction } from '@libp2p/utils/debounce'
17
- import type { Multiaddr } from '@multiformats/multiaddr'
18
-
19
- const DEFAULT_TTL = 7200
20
-
21
- export type { NatAPI, MapPortOptions }
22
-
23
- interface PortMapping {
24
- externalHost: string
25
- externalPort: number
26
- }
27
11
 
28
12
  export class UPnPNAT implements Startable, UPnPNATInterface {
29
- public client: NatAPI
30
- private readonly addressManager: AddressManager
31
- private readonly events: TypedEventTarget<Libp2pEvents>
32
- private readonly externalAddress: ExternalAddress
33
- private readonly description: string
34
- private readonly ttl: number
35
- private readonly keepAlive: boolean
36
- private readonly gateway?: string
37
- private started: boolean
38
13
  private readonly log: Logger
39
- private readonly mappedPorts: Map<string, PortMapping>
40
- private readonly onSelfPeerUpdate: DebouncedFunction
14
+ private readonly components: UPnPNATComponents
15
+ private readonly init: UPnPNATInit
16
+ private started: boolean
17
+ public portMappingClient: UPnPNATClient
41
18
  private shutdownController?: AbortController
19
+ private readonly mapIpAddressesDebounced: DebouncedFunction
20
+ private readonly gatewayFinder: GatewayFinder
21
+ private readonly portMappers: UPnPPortMapper[]
42
22
 
43
23
  constructor (components: UPnPNATComponents, init: UPnPNATInit) {
44
24
  this.log = components.logger.forComponent('libp2p:upnp-nat')
45
- this.addressManager = components.addressManager
46
- this.events = components.events
25
+ this.components = components
26
+ this.init = init
47
27
  this.started = false
48
- this.description = init.description ?? `${components.nodeInfo.name}@${components.nodeInfo.version} ${components.peerId.toString()}`
49
- this.ttl = init.ttl ?? DEFAULT_TTL
50
- this.keepAlive = init.keepAlive ?? true
51
- this.gateway = init.gateway
52
- this.mappedPorts = new Map()
53
-
54
- if (this.ttl < DEFAULT_TTL) {
55
- throw new InvalidParametersError(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`)
56
- }
28
+ this.portMappers = []
57
29
 
58
- this.client = init.client ?? upnpNat({
59
- description: this.description,
60
- ttl: this.ttl,
61
- keepAlive: this.keepAlive,
62
- gateway: this.gateway
30
+ this.portMappingClient = init.portMappingClient ?? upnpNat({
31
+ description: init.portMappingDescription ?? `${components.nodeInfo.name}@${components.nodeInfo.version} ${components.peerId.toString()}`,
32
+ ttl: init.portMappingTTL ?? DEFAULT_PORT_MAPPING_TTL,
33
+ autoRefresh: init.portMappingAutoRefresh ?? true
63
34
  })
64
35
 
65
- this.onSelfPeerUpdate = debounce(this._onSelfPeerUpdate.bind(this), init.delay ?? 5000)
36
+ // trigger update when our addresses change
37
+ this.mapIpAddressesDebounced = debounce(async () => {
38
+ try {
39
+ await this.mapIpAddresses()
40
+ } catch (err: any) {
41
+ this.log.error('error mapping IP addresses - %e', err)
42
+ }
43
+ }, 5_000)
66
44
 
67
- if (typeof init.externalAddress === 'string') {
68
- this.externalAddress = staticExternalAddress(init.externalAddress)
69
- } else {
70
- this.externalAddress = dynamicExternalAddress({
71
- client: this.client,
72
- addressManager: this.addressManager,
73
- logger: components.logger
74
- }, {
75
- interval: init.externalAddressCheckInterval,
76
- timeout: init.externalAddressCheckTimeout,
77
- onExternalAddressChange: this.remapPorts.bind(this)
78
- })
79
- }
45
+ // trigger update when we discovery gateways on the network
46
+ this.gatewayFinder = new GatewayFinder(components, {
47
+ portMappingClient: this.portMappingClient
48
+ })
49
+
50
+ this.onGatewayDiscovered = this.onGatewayDiscovered.bind(this)
80
51
  }
81
52
 
82
53
  readonly [Symbol.toStringTag] = '@libp2p/upnp-nat'
@@ -97,167 +68,44 @@ export class UPnPNAT implements Startable, UPnPNATInterface {
97
68
  this.started = true
98
69
  this.shutdownController = new AbortController()
99
70
  setMaxListeners(Infinity, this.shutdownController.signal)
100
- this.events.addEventListener('self:peer:update', this.onSelfPeerUpdate)
101
- await start(this.externalAddress, this.onSelfPeerUpdate)
71
+ this.components.events.addEventListener('self:peer:update', this.mapIpAddressesDebounced)
72
+ this.gatewayFinder.addEventListener('gateway', this.onGatewayDiscovered)
73
+ await start(this.mapIpAddressesDebounced, this.gatewayFinder, ...this.portMappers)
102
74
  }
103
75
 
104
76
  /**
105
77
  * Stops the NAT manager
106
78
  */
107
79
  async stop (): Promise<void> {
108
- try {
109
- await this.client?.close()
110
- } catch (err: any) {
111
- this.log.error(err)
112
- }
113
-
114
80
  this.shutdownController?.abort()
115
- this.events.removeEventListener('self:peer:update', this.onSelfPeerUpdate)
116
- await stop(this.externalAddress, this.onSelfPeerUpdate)
81
+ this.components.events.removeEventListener('self:peer:update', this.mapIpAddressesDebounced)
82
+ this.gatewayFinder.removeEventListener('gateway', this.onGatewayDiscovered)
83
+ await stop(this.mapIpAddressesDebounced, this.gatewayFinder, ...this.portMappers)
117
84
  this.started = false
118
85
  }
119
86
 
120
- _onSelfPeerUpdate (): void {
121
- this.mapIpAddresses()
122
- .catch(err => {
123
- this.log.error('error mapping IP addresses - %e', err)
124
- })
125
- }
126
-
127
- private getUnmappedAddresses (multiaddrs: Multiaddr[], ipType: 4 | 6): Multiaddr[] {
128
- const output: Multiaddr[] = []
129
-
130
- for (const ma of multiaddrs) {
131
- // ignore public addresses
132
- if (!isPrivate(ma)) {
133
- continue
134
- }
135
-
136
- // ignore loopback
137
- if (isLoopback(ma)) {
138
- continue
139
- }
140
-
141
- // only IP based addresses
142
- if (!(
143
- TCP.exactMatch(ma) ||
144
- WebSockets.exactMatch(ma) ||
145
- WebSocketsSecure.exactMatch(ma) ||
146
- QUICV1.exactMatch(ma) ||
147
- WebTransport.exactMatch(ma)
148
- )) {
149
- continue
150
- }
151
-
152
- const { port, host, family, transport } = ma.toOptions()
153
-
154
- if (family !== ipType) {
155
- continue
156
- }
157
-
158
- if (this.mappedPorts.has(`${host}-${port}-${transport}`)) {
159
- continue
160
- }
161
-
162
- output.push(ma)
163
- }
164
-
165
- return output
166
- }
167
-
168
- async mapIpAddresses (): Promise<void> {
169
- const externalHost = await this.externalAddress.getPublicIp({
170
- signal: this.shutdownController?.signal
87
+ onGatewayDiscovered (event: CustomEvent<Gateway>): void {
88
+ const mapper = new UPnPPortMapper(this.components, {
89
+ ...this.init,
90
+ gateway: event.detail
171
91
  })
172
92
 
173
- let ipType: 4 | 6 = 4
174
-
175
- if (isIPv4(externalHost)) {
176
- ipType = 4
177
- } else if (isIPv6(externalHost)) {
178
- ipType = 6
179
- } else {
180
- throw new InvalidIPAddressError(`Public address ${externalHost} was not an IPv4 address`)
181
- }
182
-
183
- // filter addresses to get private, non-relay, IP based addresses that we
184
- // haven't mapped yet
185
- const addresses = this.getUnmappedAddresses(this.addressManager.getAddresses(), ipType)
186
-
187
- if (addresses.length === 0) {
188
- this.log('no private, non-relay, unmapped, IP based addresses found')
189
- return
190
- }
191
-
192
- this.log('%s public IP %s', this.externalAddress != null ? 'using configured' : 'discovered', externalHost)
193
-
194
- this.assertNotBehindDoubleNAT(externalHost)
195
-
196
- for (const addr of addresses) {
197
- // try to open uPnP ports for each thin waist address
198
- const { family, host, port, transport } = addr.toOptions()
199
-
200
- if (family === 6) {
201
- // only support IPv4 addresses
202
- continue
203
- }
204
-
205
- if (this.mappedPorts.has(`${host}-${port}-${transport}`)) {
206
- // already mapped this port
207
- continue
208
- }
209
-
210
- try {
211
- this.log(`creating mapping of %s:%s key ${host}-${port}-${transport}`, host, port)
212
-
213
- const externalPort = await this.client.map(port, {
214
- localAddress: host,
215
- protocol: transport === 'tcp' ? 'TCP' : 'UDP'
216
- })
217
-
218
- this.mappedPorts.set(`${host}-${port}-${transport}`, {
219
- externalHost,
220
- externalPort
221
- })
93
+ this.portMappers.push(mapper)
222
94
 
223
- this.log('created mapping of %s:%s to %s:%s', externalHost, externalPort, host, port)
224
-
225
- this.addressManager.addPublicAddressMapping(host, port, externalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
226
- } catch (err) {
227
- this.log.error('failed to create mapping of %s:%s - %e', host, port, err)
228
- }
229
- }
230
- }
231
-
232
- /**
233
- * Some ISPs have double-NATs, there's not much we can do with them
234
- */
235
- private assertNotBehindDoubleNAT (publicIp: string): void {
236
- const isPrivate = isPrivateIp(publicIp)
237
-
238
- if (isPrivate === true) {
239
- throw new DoubleNATError(`${publicIp} is private - please init uPnPNAT with 'externalAddress' set to an externally routable IP or ensure you are not behind a double NAT`)
240
- }
241
-
242
- if (isPrivate == null) {
243
- throw new InvalidParametersError(`${publicIp} is not an IP address`)
244
- }
95
+ start(mapper)
96
+ .then(() => {
97
+ this.mapIpAddressesDebounced()
98
+ })
99
+ .catch(() => {})
245
100
  }
246
101
 
247
- /**
248
- * Update the local address mappings when the gateway's external interface
249
- * address changes
250
- */
251
- private remapPorts (newExternalHost: string): void {
252
- for (const [key, { externalHost, externalPort }] of this.mappedPorts.entries()) {
253
- const [
254
- host,
255
- port,
256
- transport
257
- ] = key.split('-')
258
-
259
- this.addressManager.removePublicAddressMapping(host, parseInt(port), externalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
260
- this.addressManager.addPublicAddressMapping(host, parseInt(port), newExternalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
102
+ async mapIpAddresses (): Promise<void> {
103
+ try {
104
+ await Promise.all(
105
+ this.portMappers.map(async mapper => mapper.mapIpAddresses())
106
+ )
107
+ } catch (err: any) {
108
+ this.log.error('error mapping IP addresses - %e', err)
261
109
  }
262
110
  }
263
111
  }
@@ -0,0 +1,223 @@
1
+ import { isIPv4, isIPv6 } from '@chainsafe/is-ip'
2
+ import { InvalidParametersError, start, stop } from '@libp2p/interface'
3
+ import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'
4
+ import { isPrivate } from '@libp2p/utils/multiaddr/is-private'
5
+ import { isPrivateIp } from '@libp2p/utils/private-ip'
6
+ import { QUICV1, TCP, WebSockets, WebSocketsSecure, WebTransport } from '@multiformats/multiaddr-matcher'
7
+ import { dynamicExternalAddress } from './check-external-address.js'
8
+ import { DoubleNATError, InvalidIPAddressError } from './errors.js'
9
+ import type { ExternalAddress } from './check-external-address.js'
10
+ import type { Gateway } from '@achingbrain/nat-port-mapper'
11
+ import type { ComponentLogger, Logger } from '@libp2p/interface'
12
+ import type { AddressManager } from '@libp2p/interface-internal'
13
+ import type { Multiaddr } from '@multiformats/multiaddr'
14
+
15
+ export interface UPnPPortMapperInit {
16
+ gateway: Gateway
17
+ externalAddressCheckInterval?: number
18
+ externalAddressCheckTimeout?: number
19
+ }
20
+
21
+ export interface UPnPPortMapperComponents {
22
+ logger: ComponentLogger
23
+ addressManager: AddressManager
24
+ }
25
+
26
+ interface PortMapping {
27
+ externalHost: string
28
+ externalPort: number
29
+ }
30
+
31
+ export class UPnPPortMapper {
32
+ private readonly gateway: Gateway
33
+ private readonly externalAddress: ExternalAddress
34
+ private readonly addressManager: AddressManager
35
+ private readonly log: Logger
36
+ private readonly mappedPorts: Map<string, PortMapping>
37
+ private started: boolean
38
+
39
+ constructor (components: UPnPPortMapperComponents, init: UPnPPortMapperInit) {
40
+ this.log = components.logger.forComponent(`libp2p:upnp-nat:gateway:${init.gateway.id}`)
41
+ this.addressManager = components.addressManager
42
+ this.gateway = init.gateway
43
+ this.externalAddress = dynamicExternalAddress({
44
+ gateway: this.gateway,
45
+ addressManager: this.addressManager,
46
+ logger: components.logger
47
+ }, {
48
+ interval: init.externalAddressCheckInterval,
49
+ timeout: init.externalAddressCheckTimeout,
50
+ onExternalAddressChange: this.remapPorts.bind(this)
51
+ })
52
+ this.gateway = init.gateway
53
+ this.mappedPorts = new Map()
54
+ this.started = false
55
+ }
56
+
57
+ async start (): Promise<void> {
58
+ if (this.started) {
59
+ return
60
+ }
61
+
62
+ await start(this.externalAddress)
63
+ this.started = true
64
+ }
65
+
66
+ async stop (): Promise<void> {
67
+ try {
68
+ const shutdownTimeout = AbortSignal.timeout(1000)
69
+
70
+ await this.gateway.stop({
71
+ signal: shutdownTimeout
72
+ })
73
+ } catch (err: any) {
74
+ this.log.error('error closing gateway - %e', err)
75
+ }
76
+
77
+ await stop(this.externalAddress)
78
+ this.started = false
79
+ }
80
+
81
+ /**
82
+ * Update the local address mappings when the gateway's external interface
83
+ * address changes
84
+ */
85
+ private remapPorts (newExternalHost: string): void {
86
+ for (const [key, { externalHost, externalPort }] of this.mappedPorts.entries()) {
87
+ const [
88
+ host,
89
+ port,
90
+ transport
91
+ ] = key.split('-')
92
+
93
+ this.addressManager.removePublicAddressMapping(host, parseInt(port), externalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
94
+ this.addressManager.addPublicAddressMapping(host, parseInt(port), newExternalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Return any eligible multiaddrs that are not mapped on the detected gateway
100
+ */
101
+ private getUnmappedAddresses (multiaddrs: Multiaddr[], ipType: 4 | 6): Multiaddr[] {
102
+ const output: Multiaddr[] = []
103
+
104
+ for (const ma of multiaddrs) {
105
+ // ignore public addresses
106
+ if (!isPrivate(ma)) {
107
+ continue
108
+ }
109
+
110
+ // ignore loopback
111
+ if (isLoopback(ma)) {
112
+ continue
113
+ }
114
+
115
+ // only IP based addresses
116
+ if (!(
117
+ TCP.exactMatch(ma) ||
118
+ WebSockets.exactMatch(ma) ||
119
+ WebSocketsSecure.exactMatch(ma) ||
120
+ QUICV1.exactMatch(ma) ||
121
+ WebTransport.exactMatch(ma)
122
+ )) {
123
+ continue
124
+ }
125
+
126
+ const { port, host, family, transport } = ma.toOptions()
127
+
128
+ if (family !== ipType) {
129
+ continue
130
+ }
131
+
132
+ if (this.mappedPorts.has(`${host}-${port}-${transport}`)) {
133
+ continue
134
+ }
135
+
136
+ output.push(ma)
137
+ }
138
+
139
+ return output
140
+ }
141
+
142
+ async mapIpAddresses (): Promise<void> {
143
+ try {
144
+ const externalHost = await this.externalAddress.getPublicIp()
145
+
146
+ let ipType: 4 | 6 = 4
147
+
148
+ if (isIPv4(externalHost)) {
149
+ ipType = 4
150
+ } else if (isIPv6(externalHost)) {
151
+ ipType = 6
152
+ } else {
153
+ throw new InvalidIPAddressError(`Public address ${externalHost} was not an IPv4 address`)
154
+ }
155
+
156
+ // filter addresses to get private, non-relay, IP based addresses that we
157
+ // haven't mapped yet
158
+ const addresses = this.getUnmappedAddresses(this.addressManager.getAddresses(), ipType)
159
+
160
+ if (addresses.length === 0) {
161
+ this.log('no private, non-relay, unmapped, IP based addresses found')
162
+ return
163
+ }
164
+
165
+ this.log('%s public IP %s', this.externalAddress != null ? 'using configured' : 'discovered', externalHost)
166
+
167
+ this.assertNotBehindDoubleNAT(externalHost)
168
+
169
+ for (const addr of addresses) {
170
+ // try to open uPnP ports for each thin waist address
171
+ const { family, host, port, transport } = addr.toOptions()
172
+
173
+ if (family === 6) {
174
+ // only support IPv4 addresses
175
+ continue
176
+ }
177
+
178
+ if (this.mappedPorts.has(`${host}-${port}-${transport}`)) {
179
+ // already mapped this port
180
+ continue
181
+ }
182
+
183
+ try {
184
+ const key = `${host}-${port}-${transport}`
185
+ this.log('creating mapping of key %s', key)
186
+
187
+ const externalPort = await this.gateway.map(port, {
188
+ localAddress: host,
189
+ protocol: transport === 'tcp' ? 'tcp' : 'udp'
190
+ })
191
+
192
+ this.mappedPorts.set(key, {
193
+ externalHost,
194
+ externalPort
195
+ })
196
+
197
+ this.log('created mapping of %s:%s to %s:%s', externalHost, externalPort, host, port)
198
+
199
+ this.addressManager.addPublicAddressMapping(host, port, externalHost, externalPort, transport === 'tcp' ? 'tcp' : 'udp')
200
+ } catch (err) {
201
+ this.log.error('failed to create mapping of %s:%s - %e', host, port, err)
202
+ }
203
+ }
204
+ } catch (err: any) {
205
+ this.log.error('error finding gateways - %e', err)
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Some ISPs have double-NATs, there's not much we can do with them
211
+ */
212
+ private assertNotBehindDoubleNAT (publicIp: string): void {
213
+ const isPrivate = isPrivateIp(publicIp)
214
+
215
+ if (isPrivate === true) {
216
+ throw new DoubleNATError(`${publicIp} is private - please init uPnPNAT with 'externalAddress' set to an externally routable IP or ensure you are not behind a double NAT`)
217
+ }
218
+
219
+ if (isPrivate == null) {
220
+ throw new InvalidParametersError(`${publicIp} is not an IP address`)
221
+ }
222
+ }
223
+ }