@libp2p/upnp-nat 2.0.12-bc90b4fd5 → 2.0.12-d19974d93

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