@libp2p/upnp-nat 2.0.12-b248eefc0 → 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.
@@ -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