-
Notifications
You must be signed in to change notification settings - Fork 446
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: run UPnP nat on address change, update nat port mapper
- Updates NAT port mapper to handle unavailable ports - Runs NAT port mapping on address change rather than once at startup - Re-maps addresses when the public IP address changes
- Loading branch information
1 parent
0a3406a
commit a04f4a3
Showing
20 changed files
with
24,993 additions
and
96 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
This project is dual licensed under MIT and Apache-2.0. | ||
|
||
MIT: https://www.opensource.org/licenses/mit | ||
Apache-2.0: https://www.apache.org/licenses/license-2.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# @libp2p/auto-tls | ||
|
||
[![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) | ||
|
||
> Automatically acquire a <peerId>.libp2p.direct TLS certificate | ||
# About | ||
|
||
<!-- | ||
!IMPORTANT! | ||
Everything in this README between "# About" and "# Install" is automatically | ||
generated and will be overwritten the next time the doc generator is run. | ||
To make changes to this section, please update the @packageDocumentation section | ||
of src/index.js or src/index.ts | ||
To experiment with formatting, please run "npm run docs" from the root of this | ||
repo and examine the changes made. | ||
--> | ||
|
||
A connection encrypter that does no connection encryption. | ||
|
||
This should not be used in production should be used for research purposes only. | ||
|
||
## Example | ||
|
||
```typescript | ||
import { createLibp2p } from 'libp2p' | ||
import { plaintext } from '@libp2p/plaintext' | ||
|
||
const node = await createLibp2p({ | ||
// ...other options | ||
connectionEncrypters: [ | ||
plaintext() | ||
] | ||
}) | ||
``` | ||
|
||
# Install | ||
|
||
```console | ||
$ npm i @libp2p/plaintext | ||
``` | ||
|
||
## Browser `<script>` tag | ||
|
||
Loading this module through a script tag will make it's exports available as `Libp2pPlaintext` in the global namespace. | ||
|
||
```html | ||
<script src="https://unpkg.com/@libp2p/plaintext/dist/index.min.js"></script> | ||
``` | ||
|
||
# API Docs | ||
|
||
- <https://libp2p.github.io/js-libp2p/modules/_libp2p_plaintext.html> | ||
|
||
# License | ||
|
||
Licensed under either of | ||
|
||
- Apache 2.0, ([LICENSE-APACHE](https://github.com/libp2p/js-libp2p/blob/main/packages/connection-encrypter-plaintext/LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>) | ||
- MIT ([LICENSE-MIT](https://github.com/libp2p/js-libp2p/blob/main/packages/connection-encrypter-plaintext/LICENSE-MIT) / <http://opensource.org/licenses/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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
{ | ||
"name": "@libp2p/auto-tls", | ||
"version": "0.0.0", | ||
"description": "Automatically acquire a <peerId>.libp2p.direct TLS certificate", | ||
"license": "Apache-2.0 OR MIT", | ||
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/auto-tls#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 | ||
}, | ||
"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": { | ||
"build": "aegir build --bundle false", | ||
"test": "aegir test -t node", | ||
"clean": "aegir clean", | ||
"lint": "aegir lint", | ||
"test:node": "aegir test -t node --cov", | ||
"dep-check": "aegir dep-check", | ||
"doc-check": "aegir doc-check" | ||
}, | ||
"dependencies": { | ||
"@libp2p/http-fetch": "^2.0.2", | ||
"@libp2p/interface": "^2.2.0", | ||
"@libp2p/interface-internal": "^2.0.10", | ||
"@libp2p/utils": "^6.1.3", | ||
"@multiformats/multiaddr": "^12.3.1", | ||
"@multiformats/multiaddr-matcher": "^1.4.0", | ||
"acme-client": "^5.4.0", | ||
"multiformats": "^13.3.1" | ||
}, | ||
"devDependencies": { | ||
"aegir": "^44.0.1" | ||
}, | ||
"sideEffects": false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
import { ClientAuth } from '@libp2p/http-fetch/auth' | ||
import { serviceDependencies } from '@libp2p/interface' | ||
import { debounce } from '@libp2p/utils/debounce' | ||
import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback' | ||
import { isPrivate } from '@libp2p/utils/multiaddr/is-private' | ||
import { QUICV1, TCP, WebSockets, WebSocketsSecure, WebTransport } from '@multiformats/multiaddr-matcher' | ||
import * as acmeClient from 'acme-client' | ||
import { base36 } from 'multiformats/bases/base36' | ||
import type { AutoTLSComponents, AutoTLSInit, AutoTLS as AutoTLSInterface, AutoTLSCertificate } from './index.js' | ||
import type { PeerId, PrivateKey, Logger, TypedEventTarget, Libp2pEvents, AbortOptions } from '@libp2p/interface' | ||
import type { AddressManager } from '@libp2p/interface-internal' | ||
import type { DebouncedFunction } from '@libp2p/utils/debounce' | ||
import type { Multiaddr } from '@multiformats/multiaddr' | ||
|
||
export class AutoTLS implements AutoTLSInterface { | ||
private readonly log: Logger | ||
private readonly addressManager: AddressManager | ||
private readonly privateKey: PrivateKey | ||
private readonly peerId: PeerId | ||
private readonly events: TypedEventTarget<Libp2pEvents> | ||
private readonly forgeEndpoint: string | ||
private readonly forgeDomain: string | ||
private readonly acmeDirectory: string | ||
private readonly clientAuth: ClientAuth | ||
private readonly timeout: number | ||
private running: boolean | ||
private shutdownController?: AbortController | ||
public certificate?: AutoTLSCertificate | ||
private fetching: boolean | ||
private readonly fetchCertificates: DebouncedFunction | ||
|
||
constructor (components: AutoTLSComponents, init: AutoTLSInit = {}) { | ||
this.log = components.logger.forComponent('libp2p:certificate-manager') | ||
this.addressManager = components.addressManager | ||
this.privateKey = components.privateKey | ||
this.peerId = components.peerId | ||
this.events = components.events | ||
this.forgeEndpoint = init.forgeEndpoint ?? 'registration.libp2p.direct' | ||
this.forgeDomain = init.forgeDomain ?? 'libp2p.direct' | ||
this.acmeDirectory = init.acmeDirectory ?? 'https://acme-v02.api.letsencrypt.org/directory' | ||
this.timeout = init.timeout ?? 10000 | ||
this.clientAuth = new ClientAuth(this.privateKey) | ||
this.running = false | ||
this.fetching = false | ||
this.fetchCertificates = debounce(this._fetchCertificates.bind(this), init.delay ?? 5000) | ||
} | ||
|
||
get [serviceDependencies] (): string[] { | ||
return [ | ||
'@libp2p/identify' | ||
] | ||
} | ||
|
||
async start (): Promise<void> { | ||
if (this.running) { | ||
return | ||
} | ||
|
||
this.events.addEventListener('self:peer:update', this.fetchCertificates) | ||
this.shutdownController = new AbortController() | ||
this.running = true | ||
} | ||
|
||
async stop (): Promise<void> { | ||
this.running = false | ||
this.events.removeEventListener('self:peer:update', this.fetchCertificates) | ||
this.shutdownController?.abort() | ||
this.fetchCertificates.cancel() | ||
} | ||
|
||
private _fetchCertificates (): void { | ||
if (this.fetching || this.certificate != null) { | ||
this.log('already fetching or already have a certificate') | ||
return | ||
} | ||
|
||
console.info('addresses', this.addressManager | ||
.getAddresses()) | ||
|
||
const addresses = this.addressManager | ||
.getAddresses() | ||
.filter(ma => !isPrivate(ma) && !isLoopback(ma) && ( | ||
TCP.exactMatch(ma) || | ||
WebSockets.exactMatch(ma) || | ||
WebSocketsSecure.exactMatch(ma) || | ||
QUICV1.exactMatch(ma) || | ||
WebTransport.exactMatch(ma) | ||
)) | ||
|
||
if (addresses.length === 0) { | ||
this.log('not fetching certificate as we have no public addresses') | ||
return | ||
} | ||
|
||
this.fetching = true | ||
|
||
this.fetchCertificate(addresses, { | ||
signal: AbortSignal.timeout(this.timeout) | ||
}) | ||
.catch(err => { | ||
this.log.error('error fetching certificates %e', err) | ||
}) | ||
.finally(() => { | ||
this.fetching = false | ||
}) | ||
} | ||
|
||
private async fetchCertificate (mulitaddrs: Multiaddr[], options?: AbortOptions): Promise<void> { | ||
this.log('fetching certificate') | ||
|
||
// TODO: handle rate limit errors like "too many new registrations (10) from this IP address in the last 3h0m0s, retry after 2024-11-01 09:22:38 UTC: see https://letsencrypt.org/docs/rate-limits/#new-registrations-per-ip-address" | ||
|
||
const base36EncodedPeer = base36.encode(this.peerId.toCID().bytes) | ||
const domain = `${base36EncodedPeer}.${this.forgeDomain}` | ||
|
||
// Create CSR | ||
const [certificatePrivateKey, csr] = await acmeClient.forge.createCsr({ | ||
commonName: domain, | ||
altNames: [] | ||
}) | ||
|
||
const accountPrivateKey = await acmeClient.forge.createPrivateKey() | ||
|
||
const client = new acmeClient.Client({ | ||
directoryUrl: this.acmeDirectory, | ||
accountKey: accountPrivateKey | ||
}) | ||
const cert = await client.auto({ | ||
csr, | ||
email: `${base36EncodedPeer}@libp2p.direct`, | ||
termsOfServiceAgreed: true, | ||
challengeCreateFn: async (authz, challenge, keyAuthorization) => { | ||
const addresses = mulitaddrs.map(ma => ma.toString()) | ||
|
||
this.log('asking https://%s/v1/_acme-challenge to respond to the acme DNS challenge on our behalf', this.forgeEndpoint) | ||
this.log('dialback public addresses: %s', addresses.join(', ')) | ||
const response = await this.clientAuth.authenticatedFetch(`https://${this.forgeEndpoint}/v1/_acme-challenge`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json' | ||
}, | ||
body: JSON.stringify({ | ||
value: keyAuthorization, | ||
addresses | ||
}), | ||
...options | ||
}) | ||
|
||
if (!response.ok) { | ||
this.log.error('invalid response from forge %o', response) | ||
throw new Error('Invalid response status') | ||
} | ||
|
||
this.log('https://%s/v1/_acme-challenge will respond to the acme DNS challenge on our behalf', this.forgeEndpoint) | ||
}, | ||
challengeRemoveFn: async (authz, challenge, keyAuthorization) => { | ||
// no-op | ||
}, | ||
challengePriority: ['dns-01'], | ||
skipChallengeVerification: true | ||
}) | ||
|
||
this.log('fetched certificate') | ||
|
||
this.certificate = { | ||
privateKey: certificatePrivateKey, | ||
certificate: cert | ||
} | ||
} | ||
} |
Oops, something went wrong.