diff --git a/packages/pcp-nat/CHANGELOG.md b/packages/pcp-nat/CHANGELOG.md new file mode 100644 index 0000000000..825c32f0d0 --- /dev/null +++ b/packages/pcp-nat/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/pcp-nat/CODE_OF_CONDUCT.md b/packages/pcp-nat/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..6b0fa54c54 --- /dev/null +++ b/packages/pcp-nat/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Contributor Code of Conduct + +This project follows the [`IPFS Community Code of Conduct`](https://github.com/ipfs/community/blob/master/code-of-conduct.md) diff --git a/packages/pcp-nat/LICENSE-APACHE b/packages/pcp-nat/LICENSE-APACHE new file mode 100644 index 0000000000..b09cd7856d --- /dev/null +++ b/packages/pcp-nat/LICENSE-APACHE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/pcp-nat/LICENSE-MIT b/packages/pcp-nat/LICENSE-MIT new file mode 100644 index 0000000000..72dc60d84b --- /dev/null +++ b/packages/pcp-nat/LICENSE-MIT @@ -0,0 +1,19 @@ +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/packages/pcp-nat/README.md b/packages/pcp-nat/README.md new file mode 100644 index 0000000000..309ea9628a --- /dev/null +++ b/packages/pcp-nat/README.md @@ -0,0 +1,82 @@ +# @libp2p/pcp-nat + +[![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/) +[![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io) +[![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p) +[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=main\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amain) + +> PCP NAT hole punching + +# About + + + +The service exported by this module attempts to configure NAT hole punching +via PCP (Port Control Protocol). + +This will make your node publicly accessible from the internet. + +For this to work there are some prerequisites: + +1. Your router must have PCP support enabled +2. Your libp2p node must be listening on a non-loopback IPv4 or IPv6 address +3. You must not be [double-NATed](https://kb.netgear.com/30186/What-is-double-NAT-and-why-is-it-bad) by your ISP + +## Example + +```typescript +import { createLibp2p } from 'libp2p' +import { tcp } from '@libp2p/tcp' +import { PCPNAT } from '@libp2p/pcp-nat' + +const node = await createLibp2p({ + addresses: { + listen: [ + '/ip6/2001:db8:85a3:8d3:aaaa:aaaa:aaaa:aaaa/tcp/0' + ] + }, + transports: [ + tcp() + ], + services: { + // IPv6 Global Unicast Address (GUA) LAN address of your router + pcpNat: pcpNAT("2001:db8:85a3:8d3:1319:8a2e:370:7348", { + autoConfirmAddress: true + }) + } +}) +``` + +# Install + +```console +$ npm i @libp2p/pcp-nat +``` + +# API Docs + +- + +# License + +Licensed under either of + +- Apache 2.0, ([LICENSE-APACHE](https://github.com/libp2p/js-libp2p/blob/main/packages/pcp-nat/LICENSE-APACHE) / ) +- MIT ([LICENSE-MIT](https://github.com/libp2p/js-libp2p/blob/main/packages/pcp-nat/LICENSE-MIT) / ) + +# Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. diff --git a/packages/pcp-nat/package.json b/packages/pcp-nat/package.json new file mode 100644 index 0000000000..126651953f --- /dev/null +++ b/packages/pcp-nat/package.json @@ -0,0 +1,79 @@ +{ + "name": "@libp2p/pcp-nat", + "version": "0.0.1", + "description": "PCP NAT hole punching", + "license": "Apache-2.0 OR MIT", + "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/pcp-nat#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/libp2p/js-libp2p.git" + }, + "bugs": { + "url": "https://github.com/libp2p/js-libp2p/issues" + }, + "publishConfig": { + "access": "public", + "provenance": true + }, + "keywords": [ + "IPFS" + ], + "type": "module", + "types": "./dist/src/index.d.ts", + "files": [ + "src", + "dist", + "!dist/test", + "!**/*.tsbuildinfo" + ], + "exports": { + ".": { + "types": "./dist/src/index.d.ts", + "import": "./dist/src/index.js" + } + }, + "eslintConfig": { + "extends": "ipfs", + "parserOptions": { + "project": true, + "sourceType": "module" + } + }, + "scripts": { + "clean": "aegir clean", + "lint": "aegir lint", + "dep-check": "aegir dep-check", + "doc-check": "aegir doc-check", + "build": "aegir build --no-bundle", + "test": "aegir test -t node -t electron-main", + "test:chrome": "aegir test -t browser -f ./dist/test/browser.js --cov", + "test:chrome-webworker": "aegir test -t webworker -f ./dist/test/browser.js", + "test:firefox": "aegir test -t browser -f ./dist/test/browser.js -- --browser firefox", + "test:firefox-webworker": "aegir test -t webworker -f ./dist/test/browser.js -- --browser firefox", + "test:node": "aegir test -t node --cov", + "test:electron-main": "aegir test -t electron-main" + }, + "dependencies": { + "@achingbrain/nat-port-mapper": "^4.0.2", + "@chainsafe/is-ip": "^2.1.0", + "@libp2p/interface": "^2.5.0", + "@libp2p/interface-internal": "^2.3.1", + "@libp2p/utils": "^6.5.1", + "@multiformats/multiaddr": "^12.3.3", + "@multiformats/multiaddr-matcher": "^1.6.0", + "p-defer": "^4.0.1", + "race-signal": "^1.1.0" + }, + "devDependencies": { + "@libp2p/crypto": "^5.0.11", + "@libp2p/logger": "^5.1.8", + "@libp2p/peer-id": "^5.0.12", + "aegir": "^45.0.5", + "sinon-ts": "^2.0.0", + "wherearewe": "^2.0.1" + }, + "browser": { + "./dist/src/pcp-nat.js": "./dist/src/pcp-nat.browser.js" + }, + "sideEffects": false +} diff --git a/packages/pcp-nat/src/check-external-address.ts b/packages/pcp-nat/src/check-external-address.ts new file mode 100644 index 0000000000..8647df2b05 --- /dev/null +++ b/packages/pcp-nat/src/check-external-address.ts @@ -0,0 +1,121 @@ +import { NotStartedError, start, stop } from '@libp2p/interface' +import { repeatingTask } from '@libp2p/utils/repeating-task' +import pDefer from 'p-defer' +import { raceSignal } from 'race-signal' +import type { Gateway } from '@achingbrain/nat-port-mapper' +import type { AbortOptions, ComponentLogger, Logger, Startable } from '@libp2p/interface' +import type { AddressManager } from '@libp2p/interface-internal' +import type { RepeatingTask } from '@libp2p/utils/repeating-task' +import type { DeferredPromise } from 'p-defer' + +export interface ExternalAddressCheckerComponents { + gateway: Gateway + addressManager: AddressManager + logger: ComponentLogger +} + +export interface ExternalAddressCheckerInit { + interval?: number + timeout?: number + onExternalAddressChange?(newExternalAddress: string): void +} + +export interface ExternalAddress { + getPublicIp (options?: AbortOptions): Promise | string +} + +/** + * Monitors the external network address and notifies when/if it changes + */ +class ExternalAddressChecker implements ExternalAddress, Startable { + private readonly log: Logger + private readonly gateway: Gateway + private started: boolean + private lastPublicIp?: string + private lastPublicIpPromise?: DeferredPromise + private readonly check: RepeatingTask + private readonly onExternalAddressChange?: (newExternalAddress: string) => void + + constructor (components: ExternalAddressCheckerComponents, init: ExternalAddressCheckerInit) { + this.log = components.logger.forComponent('libp2p:pcp:external-address-check') + this.gateway = components.gateway + this.onExternalAddressChange = init.onExternalAddressChange + this.started = false + + this.checkExternalAddress = this.checkExternalAddress.bind(this) + + this.check = repeatingTask(this.checkExternalAddress, init.interval ?? 30000, { + timeout: init.timeout ?? 10000, + runImmediately: true + }) + } + + async start (): Promise { + if (this.started) { + return + } + + await start(this.check) + this.started = true + } + + async stop (): Promise { + await stop(this.check) + this.started = false + } + + /** + * Return the last public IP address we found, or wait for it to be found + */ + async getPublicIp (options?: AbortOptions): Promise { + if (!this.started) { + throw new NotStartedError('Not started yet') + } + + if (this.lastPublicIp != null) { + return this.lastPublicIp + } + + this.lastPublicIpPromise = pDefer() + + return raceSignal(this.lastPublicIpPromise.promise, options?.signal, { + errorMessage: 'Requesting the public IP from the network gateway timed out - PCP may not be enabled' + }) + } + + private async checkExternalAddress (options?: AbortOptions): Promise { + try { + const externalAddress = await this.gateway.externalIp(options) + + // check if our public address has changed + if (this.lastPublicIp != null && externalAddress !== this.lastPublicIp) { + this.log('external address changed from %s to %s', this.lastPublicIp, externalAddress) + + // notify listeners that the address has changed + this.onExternalAddressChange?.(externalAddress) + } + + this.lastPublicIp = externalAddress + this.lastPublicIpPromise?.resolve(externalAddress) + } catch (err: any) { + this.log.error('could not resolve external address - %e', err) + + if (this.lastPublicIp != null) { + // ignore the error if we've previously run successfully + return + } + + this.lastPublicIpPromise?.reject(err) + } + } +} + +export function dynamicExternalAddress (components: ExternalAddressCheckerComponents, init: ExternalAddressCheckerInit): ExternalAddress { + return new ExternalAddressChecker(components, init) +} + +export function staticExternalAddress (address: string): ExternalAddress { + return { + getPublicIp: () => address + } +} diff --git a/packages/pcp-nat/src/errors.ts b/packages/pcp-nat/src/errors.ts new file mode 100644 index 0000000000..02b4350200 --- /dev/null +++ b/packages/pcp-nat/src/errors.ts @@ -0,0 +1,11 @@ +export class DoubleNATError extends Error { + constructor (message = 'Double NAT detected') { + super(message) + this.name = 'DoubleNATError' + } +} + +export class InvalidIPAddressError extends Error { + static name = 'InvalidIPAddressError' + name = 'InvalidIPAddressError' +} diff --git a/packages/pcp-nat/src/index.ts b/packages/pcp-nat/src/index.ts new file mode 100644 index 0000000000..9e1a129094 --- /dev/null +++ b/packages/pcp-nat/src/index.ts @@ -0,0 +1,121 @@ +/** + * @packageDocumentation + * + * The service exported by this module attempts to configure NAT hole punching + * via PCP (Port Control Protocol). + * + * This will make your node publicly accessible from the internet. + * + * For this to work there are some prerequisites: + * + * 1. Your router must have PCP support enabled + * 2. Your libp2p node must be listening on a non-loopback IPv4 or IPv6 address + * 3. You must not be [double-NATed](https://kb.netgear.com/30186/What-is-double-NAT-and-why-is-it-bad) by your ISP + * + * @example + * + * ```typescript + * import { createLibp2p } from 'libp2p' + * import { tcp } from '@libp2p/tcp' + * import { PCPNAT } from '@libp2p/pcp-nat' + * + * const node = await createLibp2p({ + * addresses: { + * listen: [ + * '/ip6/2001:db8:85a3:8d3:aaaa:aaaa:aaaa:aaaa/tcp/0' + * ] + * }, + * transports: [ + * tcp() + * ], + * services: { + * // IPv6 Global Unicast Address (GUA) LAN address of your router + * pcpNat: pcpNAT("2001:db8:85a3:8d3:1319:8a2e:370:7348", { + * autoConfirmAddress: true + * }) + * } + * }) + * ``` + */ + +import { PCPNAT as PCPClass } from './pcp-nat.js' +import type { PCPNAT as PCPNATClient, MapPortOptions } from '@achingbrain/nat-port-mapper' +import type { ComponentLogger, Libp2pEvents, NodeInfo, PeerId, TypedEventTarget } from '@libp2p/interface' +import type { AddressManager } from '@libp2p/interface-internal' + +export type { PCPNATClient, MapPortOptions } + +export interface PCPNATInit { + /** + * By default we query configured gateways for their external + * address. To specify it manually instead, pass a value here. + * + * Typically this would be an IPv4 address that the router performs NAT with. + */ + externalAddress?: string + + /** + * Check if the external address has changed this often in ms. Ignored if an + * external address is specified. + * + * @default 30000 + */ + externalAddressCheckInterval?: number + + /** + * Do not take longer than this to check if the external address has changed + * in ms. Ignored if an external address is specified. + * + * @default 10000 + */ + externalAddressCheckTimeout?: number + + /** + * How long PCP port mappings should last for in ms + * + * @default 720_000 + */ + portMappingTTL?: number + + /** + * Whether to automatically refresh PCP port mappings + * + * @default true + */ + portMappingAutoRefresh?: boolean + + /** + * A preconfigured instance of a PCPNatAPI client can be passed as an option, + * otherwise one will be created + */ + portMappingClient?: PCPNATClient + + /** + * Any mapped addresses are added to the observed address list. These + * addresses require additional verification by the `@libp2p/autonat` protocol + * or similar before they are trusted. + * + * To skip this verification and trust them immediately pass `true` here + * + * @default false + */ + autoConfirmAddress?: boolean +} + +export interface PCPNATComponents { + peerId: PeerId + nodeInfo: NodeInfo + logger: ComponentLogger + addressManager: AddressManager + events: TypedEventTarget +} + +export interface PCPNAT { + portMappingClient: PCPNATClient +} + +export function pcpNAT (gateway: string, init: PCPNATInit = {}): (components: PCPNATComponents) => PCPNAT { + return (components: PCPNATComponents) => { + return new PCPClass(gateway, components, init) + } +} diff --git a/packages/pcp-nat/src/pcp-nat.browser.ts b/packages/pcp-nat/src/pcp-nat.browser.ts new file mode 100644 index 0000000000..bd7f7a922d --- /dev/null +++ b/packages/pcp-nat/src/pcp-nat.browser.ts @@ -0,0 +1,21 @@ +import { serviceCapabilities, serviceDependencies } from '@libp2p/interface' +import type { PCPNAT as PCPInterface } from './index.js' +import type { PCPNAT } from '@achingbrain/nat-port-mapper' + +export class PCP implements PCPInterface { + public portMappingClient: PCPNAT + + constructor () { + throw new Error('PCP is not supported in browsers') + } + + readonly [Symbol.toStringTag] = '@libp2p/pcp-nat' + + readonly [serviceCapabilities]: string[] = [ + '@libp2p/nat-traversal' + ] + + get [serviceDependencies] (): string[] { + return [] + } +} diff --git a/packages/pcp-nat/src/pcp-nat.ts b/packages/pcp-nat/src/pcp-nat.ts new file mode 100644 index 0000000000..e3a077c753 --- /dev/null +++ b/packages/pcp-nat/src/pcp-nat.ts @@ -0,0 +1,134 @@ +import { pcpNat } from '@achingbrain/nat-port-mapper' +import { serviceCapabilities, serviceDependencies, setMaxListeners, start, stop } from '@libp2p/interface' +import { debounce } from '@libp2p/utils/debounce' +import { PCPPortMapper } from './pcp-port-mapper.js' +import { StaticGatewayFinder } from './static-gateway-finder.js' +import type { PCPNATComponents, PCPNATInit, PCPNAT as PCPNATInterface } from './index.js' +import type { Gateway, PCPNAT as PCPNATClient } from '@achingbrain/nat-port-mapper' +import type { Logger, Startable, TypedEventTarget } from '@libp2p/interface' +import type { DebouncedFunction } from '@libp2p/utils/debounce' + +export interface GatewayFinderEvents { + 'gateway': CustomEvent +} + +export interface GatewayFinder extends TypedEventTarget { + +} + +export class PCPNAT implements Startable, PCPNATInterface { + private readonly log: Logger + private readonly components: PCPNATComponents + private readonly init: PCPNATInit + private started: boolean + public portMappingClient: PCPNATClient + private shutdownController?: AbortController + private readonly mapIpAddressesDebounced: DebouncedFunction + private readonly gatewayFinder: GatewayFinder + private readonly portMappers: PCPPortMapper[] + private readonly autoConfirmAddress: boolean + private readonly gatewayIP: string + + constructor (gatewayIP: string, components: PCPNATComponents, init: PCPNATInit) { + this.log = components.logger.forComponent('libp2p:pcp-nat') + this.components = components + this.init = init + this.started = false + this.portMappers = [] + this.gatewayIP = gatewayIP + this.autoConfirmAddress = init.autoConfirmAddress ?? false + + this.portMappingClient = init.portMappingClient ?? pcpNat(gatewayIP, { + ttl: init.portMappingTTL, + autoRefresh: init.portMappingAutoRefresh + }) + + // trigger update when our addresses change + this.mapIpAddressesDebounced = debounce(async () => { + try { + await this.mapIpAddresses() + } catch (err: any) { + this.log.error('error mapping IP addresses - %e', err) + } + }, 5_000) + + this.gatewayFinder = new StaticGatewayFinder(components, { + portMappingClient: this.portMappingClient, + gatewayIP + }) + + this.onGatewayDiscovered = this.onGatewayDiscovered.bind(this) + } + + readonly [Symbol.toStringTag] = '@libp2p/pcp-nat' + + readonly [serviceCapabilities]: string[] = [ + '@libp2p/nat-traversal' + ] + + get [serviceDependencies] (): string[] { + if (!this.autoConfirmAddress) { + return [ + '@libp2p/autonat' + ] + } + + return [] + } + + isStarted (): boolean { + return this.started + } + + async start (): Promise { + if (this.started) { + return + } + + this.started = true + this.shutdownController = new AbortController() + setMaxListeners(Infinity, this.shutdownController.signal) + this.components.events.addEventListener('self:peer:update', this.mapIpAddressesDebounced) + this.gatewayFinder.addEventListener('gateway', this.onGatewayDiscovered) + await start(this.mapIpAddressesDebounced, this.gatewayFinder, ...this.portMappers) + } + + /** + * Stops the PCP manager + */ + async stop (): Promise { + this.shutdownController?.abort() + this.components.events.removeEventListener('self:peer:update', this.mapIpAddressesDebounced) + this.gatewayFinder.removeEventListener('gateway', this.onGatewayDiscovered) + await stop(this.mapIpAddressesDebounced, this.gatewayFinder, ...this.portMappers) + this.started = false + } + + onGatewayDiscovered (event: CustomEvent): void { + const mapper = new PCPPortMapper(this.components, { + ...this.init, + gateway: event.detail, + externalAddress: this.gatewayIP + }) + + this.portMappers.push(mapper) + + start(mapper) + .then(() => { + this.mapIpAddressesDebounced() + }) + .catch(() => { }) + } + + async mapIpAddresses (): Promise { + try { + await Promise.all( + this.portMappers.map(async mapper => mapper.mapIpAddresses({ + autoConfirmAddress: this.autoConfirmAddress + })) + ) + } catch (err: any) { + this.log.error('error mapping IP addresses - %e', err) + } + } +} diff --git a/packages/pcp-nat/src/pcp-port-mapper.ts b/packages/pcp-nat/src/pcp-port-mapper.ts new file mode 100644 index 0000000000..23aa8fb86a --- /dev/null +++ b/packages/pcp-nat/src/pcp-port-mapper.ts @@ -0,0 +1,304 @@ +import { isIPv4 } from '@chainsafe/is-ip' +import { InvalidParametersError, start, stop } from '@libp2p/interface' +import { isLinkLocal } from '@libp2p/utils/multiaddr/is-link-local' +import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback' +import { isPrivate } from '@libp2p/utils/multiaddr/is-private' +import { isPrivateIp } from '@libp2p/utils/private-ip' +import { multiaddr } from '@multiformats/multiaddr' +import { + QUICV1, + TCP, + WebSockets, + WebSocketsSecure, + WebTransport +} from '@multiformats/multiaddr-matcher' +import { + dynamicExternalAddress, + staticExternalAddress +} from './check-external-address.js' +import { DoubleNATError } from './errors.js' +import type { ExternalAddress } from './check-external-address.js' +import type { Gateway } from '@achingbrain/nat-port-mapper' +import type { ComponentLogger, Logger } from '@libp2p/interface' +import type { AddressManager, NodeAddress } from '@libp2p/interface-internal' +import type { Multiaddr } from '@multiformats/multiaddr' + +const MAX_DATE = 8_640_000_000_000_000 + +export interface PCPPortMapperInit { + gateway: Gateway + externalAddress?: string + externalAddressCheckInterval?: number + externalAddressCheckTimeout?: number +} + +export interface PCPPortMapperComponents { + logger: ComponentLogger + addressManager: AddressManager +} + +interface PortMapping { + externalHost: string + externalPort: number +} + +export interface MapPortsOptions { + autoConfirmAddress?: boolean +} + +export class PCPPortMapper { + private readonly gateway: Gateway + private readonly externalAddress: ExternalAddress + private readonly addressManager: AddressManager + private readonly log: Logger + private readonly mappedPorts: Map + private started: boolean + + constructor (components: PCPPortMapperComponents, init: PCPPortMapperInit) { + this.log = components.logger.forComponent( + `libp2p:pcp-nat:gateway:${init.gateway.id}` + ) + this.addressManager = components.addressManager + this.gateway = init.gateway + + if (init.externalAddress != null) { + this.externalAddress = staticExternalAddress(init.externalAddress) + } else { + this.externalAddress = dynamicExternalAddress( + { + gateway: this.gateway, + addressManager: this.addressManager, + logger: components.logger + }, + { + interval: init.externalAddressCheckInterval, + timeout: init.externalAddressCheckTimeout, + onExternalAddressChange: this.remapPorts.bind(this) + } + ) + } + this.gateway = init.gateway + this.mappedPorts = new Map() + this.started = false + } + + async start (): Promise { + if (this.started) { + return + } + + await start(this.externalAddress) + this.started = true + } + + async stop (): Promise { + try { + const shutdownTimeout = AbortSignal.timeout(1000) + + await this.gateway.stop({ + signal: shutdownTimeout + }) + } catch (err: any) { + this.log.error('error closing gateway - %e', err) + } + + await stop(this.externalAddress) + this.started = false + } + + /** + * Update the local address mappings when the gateway's external interface + * address changes + */ + private remapPorts (newExternalHost: string): void { + for (const [ + key, + { externalHost, externalPort } + ] of this.mappedPorts.entries()) { + const [host, port, transport] = key.split('-') + + this.addressManager.removePublicAddressMapping( + host, + parseInt(port), + externalHost, + externalPort, + transport === 'tcp' ? 'tcp' : 'udp' + ) + this.addressManager.addPublicAddressMapping( + host, + parseInt(port), + newExternalHost, + externalPort, + transport === 'tcp' ? 'tcp' : 'udp' + ) + } + } + + /** + * Return any eligible multiaddrs that are not mapped on the detected gateway + */ + private getUnmappedAddresses ( + multiaddrs: NodeAddress[], + publicAddresses: string[] + ): Multiaddr[] { + const output: Multiaddr[] = [] + + for (const { multiaddr: ma, type } of multiaddrs) { + // only consider transport addresses, ignore mapped/observed addrs + if (type !== 'transport') { + continue + } + + const stringTuples = ma.stringTuples() + const address = `${stringTuples[0][1]}` + + // ignore public IPv4 addresses + if (isIPv4(address) && !isPrivate(ma)) { + continue + } + + // ignore any addresses that match the interface on the network gateway + if (publicAddresses.includes(address)) { + continue + } + + // ignore loopback + if (isLoopback(ma)) { + continue + } + + // ignore link-local addresses + if (isLinkLocal(ma)) { + continue + } + + // only IP based addresses + if (!this.isIPAddress(ma)) { + continue + } + + const { port, transport } = ma.toOptions() + + if (this.mappedPorts.has(`${port}-${transport}`)) { + continue + } + + output.push(ma) + } + + return output + } + + async mapIpAddresses (options?: MapPortsOptions): Promise { + try { + const externalHost = await this.externalAddress.getPublicIp() + + // filter addresses to get private, non-relay, IP based addresses that we + // haven't mapped yet + const addresses = this.getUnmappedAddresses( + this.addressManager.getAddressesWithMetadata(), + [externalHost] + ) + + if (addresses.length === 0) { + this.log('no private, non-relay, unmapped, IP based addresses found') + return + } + + this.log('discovered public IP %s', externalHost) + + this.assertNotBehindDoubleNAT(externalHost) + + for (const addr of addresses) { + // try to open uPnP ports for each thin waist address + const { port, host, transport, family } = addr.toOptions() + + // don't try to open port on IPv6 host via IPv4 gateway + if (family === 4 && this.gateway.family !== 'IPv4') { + continue + } + + // don't try to open port on IPv4 host via IPv6 gateway + if (family === 6 && this.gateway.family !== 'IPv6') { + continue + } + + const key = `${host}-${port}-${transport}` + + if (this.mappedPorts.has(key)) { + // already mapped this port + continue + } + + try { + const mapping = await this.gateway.map(port, host, { + protocol: transport === 'tcp' ? 'TCP' : 'UDP' + }) + this.mappedPorts.set(key, mapping) + this.addressManager.addPublicAddressMapping( + mapping.internalHost, + mapping.internalPort, + mapping.externalHost, + mapping.externalPort, + transport === 'tcp' ? 'tcp' : 'udp' + ) + this.log( + 'created mapping of %s:%s to %s:%s for protocol %s', + mapping.internalHost, + mapping.internalPort, + mapping.externalHost, + mapping.externalPort, + transport + ) + + if (options?.autoConfirmAddress === true) { + const ma = multiaddr( + `/ip${isIPv4(mapping.externalHost) ? 4 : 6}/${mapping.externalHost}/${transport}/${mapping.externalPort}` + ) + this.log('auto-confirming IP address %a', ma) + this.addressManager.confirmObservedAddr(ma, { + ttl: MAX_DATE - Date.now() + }) + } + } catch (err) { + this.log.error( + 'failed to create mapping for %s:%d for protocol - %e', + host, + port, + transport, + err + ) + } + } + } catch (err: any) { + this.log.error('error finding gateways - %e', err) + } + } + + /** + * Some ISPs have double-NATs, there's not much we can do with them + */ + private assertNotBehindDoubleNAT (publicIp: string): void { + const isPrivate = isPrivateIp(publicIp) + + if (isPrivate === true) { + throw new DoubleNATError( + `${publicIp} is private - please init PCP with 'externalAddress' set to an externally routable IP or ensure you are not behind a double NAT` + ) + } + + if (isPrivate == null) { + throw new InvalidParametersError(`${publicIp} is not an IP address`) + } + } + + private isIPAddress (ma: Multiaddr): boolean { + return ( + TCP.exactMatch(ma) || + WebSockets.exactMatch(ma) || + WebSocketsSecure.exactMatch(ma) || + QUICV1.exactMatch(ma) || + WebTransport.exactMatch(ma) + ) + } +} diff --git a/packages/pcp-nat/src/static-gateway-finder.ts b/packages/pcp-nat/src/static-gateway-finder.ts new file mode 100644 index 0000000000..ed277ee48f --- /dev/null +++ b/packages/pcp-nat/src/static-gateway-finder.ts @@ -0,0 +1,57 @@ +import { TypedEventEmitter } from '@libp2p/interface' +import type { GatewayFinder, GatewayFinderEvents } from './pcp-nat.js' +import type { Gateway, PCPNAT } from '@achingbrain/nat-port-mapper' +import type { ComponentLogger, Logger } from '@libp2p/interface' + +export interface StaticGatewayFinderComponents { + logger: ComponentLogger +} + +export interface StaticGatewayFinderInit { + portMappingClient: PCPNAT + gatewayIP: string +} + +export class StaticGatewayFinder extends TypedEventEmitter implements GatewayFinder { + private readonly log: Logger + private gateway: Gateway | undefined + private readonly gatewayIP: string + private readonly portMappingClient: PCPNAT + private started: boolean + + constructor (components: StaticGatewayFinderComponents, init: StaticGatewayFinderInit) { + super() + + this.log = components.logger.forComponent('libp2p:pcp-nat:static-gateway-finder') + this.portMappingClient = init.portMappingClient + this.gatewayIP = init.gatewayIP + this.started = false + this.gateway = undefined + } + + async start (): Promise { + this.started = true + } + + async afterStart (): Promise { + try { + const gateway = await this.portMappingClient.getGateway() + + if (!this.started) { + return + } + + this.log('found static gateway at %s', this.gatewayIP) + this.gateway = gateway + this.safeDispatchEvent('gateway', { + detail: gateway + }) + } catch (err) { + this.log.error('could not contact static gateway at %s - %e', this.gatewayIP, err) + } + } + + async stop (): Promise { + this.started = false + } +} diff --git a/packages/pcp-nat/test/browser.ts b/packages/pcp-nat/test/browser.ts new file mode 100644 index 0000000000..85cdba839e --- /dev/null +++ b/packages/pcp-nat/test/browser.ts @@ -0,0 +1,29 @@ +import { generateKeyPair } from '@libp2p/crypto/keys' +import { TypedEventEmitter } from '@libp2p/interface' +import { defaultLogger } from '@libp2p/logger' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' +import { expect } from 'aegir/chai' +import { stubInterface } from 'sinon-ts' +import { isBrowser, isWebWorker } from 'wherearewe' +import { pcpNAT } from '../src/index.js' +import type { AddressManager } from '@libp2p/interface-internal' + +describe('browser non-support', () => { + it('should throw in browsers', async function () { + if (!isBrowser && !isWebWorker) { + return this.skip() + } + + const components = { + peerId: peerIdFromPrivateKey(await generateKeyPair('Ed25519')), + nodeInfo: { name: 'test', version: 'test', userAgent: 'test' }, + logger: defaultLogger(), + addressManager: stubInterface(), + events: new TypedEventEmitter() + } + + expect(() => { + pcpNAT('')(components) + }).to.throw() + }) +}) diff --git a/packages/pcp-nat/test/index.spec.ts b/packages/pcp-nat/test/index.spec.ts new file mode 100644 index 0000000000..e1920b9cbb --- /dev/null +++ b/packages/pcp-nat/test/index.spec.ts @@ -0,0 +1,304 @@ +/* eslint-env mocha */ + +import { generateKeyPair } from '@libp2p/crypto/keys' +import { TypedEventEmitter, start, stop } from '@libp2p/interface' +import { defaultLogger } from '@libp2p/logger' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' +import { multiaddr } from '@multiformats/multiaddr' +import { expect } from 'aegir/chai' +import { type StubbedInstance, stubInterface } from 'sinon-ts' +import { PCPNAT } from '../src/pcp-nat.js' +import type { PCPNATInit } from '../src/index.js' +import type { Gateway, PCPNAT as PCPNATClient } from '@achingbrain/nat-port-mapper' +import type { ComponentLogger, Libp2pEvents, NodeInfo, PeerId, TypedEventTarget } from '@libp2p/interface' +import type { AddressManager } from '@libp2p/interface-internal' + +interface StubbedPCPNATComponents { + peerId: PeerId + nodeInfo: NodeInfo + logger: ComponentLogger + addressManager: StubbedInstance + events: TypedEventTarget +} + +describe('PCP NAT (TCP)', () => { + const teardown: Array<() => Promise> = [] + let client: StubbedInstance + let gateway: StubbedInstance + + async function createNatManager (natManagerOptions: PCPNATInit = {}): Promise<{ natManager: any, components: StubbedPCPNATComponents }> { + const components: StubbedPCPNATComponents = { + peerId: peerIdFromPrivateKey(await generateKeyPair('Ed25519')), + nodeInfo: { name: 'test', version: 'test', userAgent: 'test' }, + logger: defaultLogger(), + addressManager: stubInterface(), + events: new TypedEventEmitter() + } + + gateway = stubInterface({ + family: 'IPv6' + }) + client = stubInterface({ + getGateway: async function () { + return gateway + } + }) + + // IP6 GUA of router + const natManager = new PCPNAT('2a00:1234:5678:90ab:cdef:1234:5678:90ab', components, { + portMappingClient: client, + ...natManagerOptions + }) + + teardown.push(async () => { + await stop(natManager) + }) + + return { + natManager, + components + } + } + + afterEach(async () => { + await Promise.all( + teardown.map(async t => { + await t() + }) + ) + }) + + it('should map TCP connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + // IPv6 GUA of host - internal & external will be the same + const internalHost = '2a00:1234:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa' + const internalPort = 4002 + + const externalHost = '2a00:1234:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa' + const externalPort = 4003 + + gateway.externalIp.resolves(externalHost) + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/127.0.0.1/tcp/4002'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }, { + multiaddr: multiaddr(`/ip6/${internalHost}/tcp/${internalPort}`), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + gateway.map.withArgs(internalPort, internalHost).resolves({ + internalHost, + internalPort, + externalHost, + externalPort, + protocol: 'TCP' + }) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.true() + expect(gateway.map.getCall(0).args[0]).to.equal(internalPort) + expect(gateway.map.getCall(0).args[1]).to.equal(internalHost) + expect(gateway.map.getCall(0).args[2]).to.include({ + protocol: 'TCP' + }) + expect(components.addressManager.addPublicAddressMapping.called).to.be.true() + }) + + it('should map TCP connections to external ports and trust them immediately', async () => { + const { + natManager, + components + } = await createNatManager() + + const internalHost = '2a00:1234:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa' + const internalPort = 4012 + + const externalHost = '2a00:1234:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa' + const externalPort = 4013 + + gateway.externalIp.resolves(externalHost) + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/127.0.0.1/tcp/4002'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }, { + multiaddr: multiaddr(`/ip6/${internalHost}/tcp/${internalPort}`), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + gateway.map.withArgs(internalPort, internalHost).resolves({ + internalHost, + internalPort, + externalHost, + externalPort, + protocol: 'TCP' + }) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called, 'map to have been called').to.be.true() + expect(gateway.map.getCall(0).args[0]).to.equal(internalPort) + expect(gateway.map.getCall(0).args[1]).to.equal(internalHost) + expect(gateway.map.getCall(0).args[2]).to.include({ + protocol: 'TCP' + }) + expect(components.addressManager.addPublicAddressMapping.called).to.be.true() + }) + + it('should not map TCP connections when double-natted', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('192.168.1.1') + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/127.0.0.1/tcp/4002'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }, { + multiaddr: multiaddr('/ip4/192.168.1.12/tcp/4002'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) + + it('should not map non-ipv4 connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('82.3.1.5') + + components.addressManager.getAddresses.returns([ + multiaddr('/ip6/fe80::9400:67ff:fe19:2a0f/tcp/0') + ]) + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip6/fe80::9400:67ff:fe19:2a0f/tcp/0'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) + + it('should not map non-ipv6 loopback connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('82.3.1.5') + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip6/::1/tcp/0'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) + + it('should not map non-TCP connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('82.3.1.5') + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/192.168.1.12/udp/4001'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) + + it('should not map loopback connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('82.3.1.5') + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/127.0.0.1/tcp/4001'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) + + it('should not map non-thin-waist connections to external ports', async () => { + const { + natManager, + components + } = await createNatManager() + + gateway.externalIp.resolves('82.3.1.5') + + components.addressManager.getAddressesWithMetadata.returns([{ + multiaddr: multiaddr('/ip4/127.0.0.1/tcp/4001/sctp/0'), + verified: true, + type: 'transport', + expires: Date.now() + 10_000 + }]) + + await start(natManager) + await natManager.mapIpAddresses() + + expect(gateway.map.called).to.be.false() + expect(components.addressManager.addPublicAddressMapping.called).to.be.false() + }) +}) diff --git a/packages/pcp-nat/tsconfig.json b/packages/pcp-nat/tsconfig.json new file mode 100644 index 0000000000..8ec6890b6d --- /dev/null +++ b/packages/pcp-nat/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "aegir/src/config/tsconfig.aegir.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": [ + "src", + "test" + ], + "references": [ + { + "path": "../crypto" + }, + { + "path": "../interface" + }, + { + "path": "../interface-internal" + }, + { + "path": "../logger" + }, + { + "path": "../peer-id" + }, + { + "path": "../utils" + } + ] +} diff --git a/packages/pcp-nat/typedoc.json b/packages/pcp-nat/typedoc.json new file mode 100644 index 0000000000..f599dc728d --- /dev/null +++ b/packages/pcp-nat/typedoc.json @@ -0,0 +1,5 @@ +{ + "entryPoints": [ + "./src/index.ts" + ] +}