diff --git a/examples/js-libp2p-example-webrtc-private-to-public/.github/pull_request_template.md b/examples/js-libp2p-example-webrtc-private-to-public/.github/pull_request_template.md new file mode 100644 index 0000000..accc1b8 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/.github/pull_request_template.md @@ -0,0 +1,17 @@ +# ⚠️ IMPORTANT ⚠️ + +# Please do not create a Pull Request for this repository + +The contents of this repository are automatically synced from the parent [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples) so any changes made to the standalone repository will be lost after the next sync. + +Please open a PR against [js-libp2p Examples](https://github.com/libp2p/js-libp2p-examples) instead. + +## Contributing + +Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. + +1. Fork the [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples) +2. Create your Feature Branch (`git checkout -b feature/amazing-example`) +3. Commit your Changes (`git commit -a -m 'feat: add some amazing example'`) +4. Push to the Branch (`git push origin feature/amazing-example`) +5. Open a Pull Request diff --git a/examples/js-libp2p-example-webrtc-private-to-public/.github/workflows/sync.yml b/examples/js-libp2p-example-webrtc-private-to-public/.github/workflows/sync.yml new file mode 100644 index 0000000..78f6c8d --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/.github/workflows/sync.yml @@ -0,0 +1,19 @@ +name: pull + +on: + workflow_dispatch + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Pull from another repository + uses: ipfs-examples/actions-pull-directory-from-repo@main + with: + source-repo: libp2p/js-libp2p-examples + source-folder-path: examples/${{ github.event.repository.name }} + source-branch: main + target-branch: main + git-username: github-actions + git-email: github-actions@github.com diff --git a/examples/js-libp2p-example-webrtc-private-to-public/LICENSE b/examples/js-libp2p-example-webrtc-private-to-public/LICENSE new file mode 100644 index 0000000..20ce483 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/LICENSE @@ -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 diff --git a/examples/js-libp2p-example-webrtc-private-to-public/LICENSE-APACHE b/examples/js-libp2p-example-webrtc-private-to-public/LICENSE-APACHE new file mode 100644 index 0000000..14478a3 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/LICENSE-APACHE @@ -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. diff --git a/examples/js-libp2p-example-webrtc-private-to-public/LICENSE-MIT b/examples/js-libp2p-example-webrtc-private-to-public/LICENSE-MIT new file mode 100644 index 0000000..72dc60d --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/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/examples/js-libp2p-example-webrtc-private-to-public/README.md b/examples/js-libp2p-example-webrtc-private-to-public/README.md new file mode 100644 index 0000000..ee36de7 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/README.md @@ -0,0 +1,31 @@ +# @libp2p/example-webrtc-private-to-private + +[![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-examples.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p-examples) +[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p-examples/ci.yml?branch=main\&style=flat-square)](https://github.com/libp2p/js-libp2p-examples/actions/workflows/ci.yml?query=branch%3Amain) + +In libp2p terms a "private" node is one behind a [NAT firewall](https://en.wikipedia.org/wiki/Network_address_translation) that prevents it from being dialed externally. + +This could be a browser, a node.js process or something else. + +Nodes that support the [libp2p WebRTC transport](https://github.com/libp2p/specs/blob/master/webrtc/webrtc.md) such as browsers can by dialed via this method even if they are behind a NAT. + +## Need help? + +- Read the [js-libp2p documentation](https://github.com/libp2p/js-libp2p/tree/main/doc) +- Check out the [js-libp2p API docs](https://libp2p.github.io/js-libp2p/) +- Check out the [general libp2p documentation](https://docs.libp2p.io) for tips, how-tos and more +- Read the [libp2p specs](https://github.com/libp2p/specs) +- Ask a question on the [js-libp2p discussion board](https://github.com/libp2p/js-libp2p/discussions) + +## License + +Licensed under either of + +- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / ) +- MIT ([LICENSE-MIT](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/examples/js-libp2p-example-webrtc-private-to-public/index.html b/examples/js-libp2p-example-webrtc-private-to-public/index.html new file mode 100644 index 0000000..93cee4b --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/index.html @@ -0,0 +1,55 @@ + + + + + + WebRTC-Private-to-Public + + + +
+
+ + + +
+

Status: Waiting...

+
+ + + +
+
+

Active Connections:

+
    +
    +
    +

    Listening addresses:

    +
      +
      +

      Output:

      +
      +
      + + + diff --git a/examples/js-libp2p-example-webrtc-private-to-public/index.js b/examples/js-libp2p-example-webrtc-private-to-public/index.js new file mode 100644 index 0000000..21d467b --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/index.js @@ -0,0 +1,180 @@ +/* eslint-disable linebreak-style */ +/* eslint-disable no-console */ + +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { webRTCDirect } from '@libp2p/webrtc' +import { multiaddr } from '@multiformats/multiaddr' +import { pipe } from 'it-pipe' +import { createLibp2p } from 'libp2p' +import { fromString, toString } from 'uint8arrays' + +// const WEBRTC_CODE = protocols('webrtc').code + +const isBrowser = typeof window !== 'undefined' +let node, conn, ma +const elements = isBrowser + ? { + sendSection: document.getElementById('send-section'), + messageBox: document.getElementById('messages'), + sendButton: document.getElementById('send'), + inputField: document.getElementById('messageInput'), + connections: document.getElementById('connections'), + multiaddrs: document.getElementById('multiaddrs'), + status: document.getElementById('status'), + output: document.getElementById('output'), + peer: document.getElementById('peer'), + connect: document.getElementById('connect'), + appendOutput: (line) => { + const div = document.createElement('div') + div.appendChild(document.createTextNode(line)) + elements.output?.appendChild(div) + } + } + : {} + +async function createNode () { + try { + if (isBrowser) { + try { + return await createLibp2p({ + transports: [webRTCDirect()], + connectionEncryption: [noise()], + streamMuxers: [yamux()] + }) + } catch (error) { + console.log(`Failed to create private node: ${error.message}`) + return null + } + } else { + try { + return await createLibp2p({ + addresses: { + listen: ['/ip4/127.0.0.1/tcp/4001/webrtc-direct', '/ip4/192.168.0.5/tcp/4001/webrtc-direct'] + }, + transports: [webRTCDirect()], + connectionEncryption: [noise()], + streamMuxers: [yamux()] + }) + } catch (error) { + console.log(`Failed to create public node: ${error.message}`) + return null + } + } + } catch (error) { + console.log(`Failed to create node: ${error.message}`) + return null + } +} + +async function start () { + node = await createNode() + if (!node) return + + try { + await node.start() + console.log('Node started! Peer ID:', node.peerId.toString()) + node.getMultiaddrs().forEach(addr => console.log('Listening on:', addr.toString())) + updateStatus(`Node started! Peer ID: ${node.peerId.toString()}`, 'green') + if (isBrowser) { + elements.status.textContent = `Node started! Peer ID: ${node.peerId.toString()}` + } + } catch (error) { + console.log(`Failed to start node: ${error.message}`) + return + } + + if (isBrowser) { + connectToPublicPeer() + } else { + console.log('Running as public peer (Node.js)') + node.getMultiaddrs().forEach(addr => console.log('Listening on:', addr.toString())) + } +} + +function connectToPublicPeer () { + // eslint-disable-next-line no-alert + const publicPeerAddr = document.getElementById('peer').value + if (!publicPeerAddr) return + + ma = multiaddr(publicPeerAddr) + node.dial(ma) + .then(() => { + elements.status.textContent = `Connected to ${publicPeerAddr}` + updateStatus(`Connected to ${publicPeerAddr}`, 'green') + setupMessaging() + }) + .catch(error => updateStatus(`Failed to dial peer: ${error.message}`, 'red')) +} + +if (elements.connect) { + elements.connect.addEventListener('click', async () => { + console.log('connect clicked') + ma = multiaddr(elements.peer.value) + elements.appendOutput(`Dialing '${ma}'`) + + const signal = AbortSignal.timeout(5000) + + try { + await node.dial(ma, { + signal + }) + elements.appendOutput(`Connected to '${ma}'`) + } catch (err) { + if (signal.aborted) { + elements.appendOutput(`Timed out connecting to '${ma}'`) + } else { + elements.appendOutput(`Connecting to '${ma}' failed - ${err.message}`) + } + } + }) +} + +function setupMessaging () { + elements.sendButton.addEventListener('click', async () => { + const message = elements.inputField.value + if (!message || !conn) return + + try { + const { stream } = await conn.newStream(['/chat/1.0.0']) + await pipe([fromString(message)], stream.sink) + appendMessage(`You: ${message}`) + elements.inputField.value = '' + } catch (error) { + console.error(`Error sending message: ${error.message}`) + } + }) + + node.handle('/chat/1.0.0', async ({ stream }) => { + try { + await pipe(stream.source, async function (source) { + for await (const msg of source) { + appendMessage(`Peer: ${toString(msg)}`) + } + }) + } catch (error) { + console.error(`Error receiving message: ${error.message}`) + } + }) +} + +function appendMessage (text) { + const messageElement = document.createElement('p') + messageElement.textContent = text + elements.messageBox.appendChild(messageElement) +} + +function updateStatus (text, color = 'black') { + if (elements.status) { + elements.status.textContent = text + elements.status.style.color = color + } +} + +if (isBrowser) { + document.addEventListener('DOMContentLoaded', () => { + start().catch(console.error) + }) +} else { + start().catch(console.error) +} diff --git a/examples/js-libp2p-example-webrtc-private-to-public/package.json b/examples/js-libp2p-example-webrtc-private-to-public/package.json new file mode 100644 index 0000000..6ebe776 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/package.json @@ -0,0 +1,32 @@ +{ + "name": "@libp2p/example-webrtc-private-to-public", + "version": "1.0.0", + "description": "Connect a browser to a public node", + "type": "module", + "scripts": { + "start": "vite", + "build": "vite build", + "public": "node public-peer.js", + "test:firefox": "npm run build && playwright test --browser=firefox test", + "test:chrome": "npm run build && playwright test test", + "test": "npm run build && test-browser-example test" + }, + "dependencies": { + "@chainsafe/libp2p-noise": "^16.0.0", + "@chainsafe/libp2p-yamux": "^7.0.0", + "@libp2p/bootstrap": "^11.0.28", + "@libp2p/circuit-relay-v2": "^3.0.0", + "@libp2p/identify": "^3.0.1", + "@libp2p/ping": "^2.0.1", + "@libp2p/webrtc": "^5.1.0", + "@libp2p/websockets": "^9.0.0", + "@multiformats/multiaddr": "^12.0.0", + "express": "^4.21.2", + "it-pushable": "^3.2.0", + "libp2p": "^2.0.0", + "vite": "^6.0.3" + }, + "devDependencies": { + "test-ipfs-example": "^1.0.0" + } +} diff --git a/examples/js-libp2p-example-webrtc-private-to-public/public-peer.js b/examples/js-libp2p-example-webrtc-private-to-public/public-peer.js new file mode 100644 index 0000000..b3e46f6 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/public-peer.js @@ -0,0 +1,67 @@ +/* eslint-disable linebreak-style */ +/* eslint-disable no-console */ + +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { circuitRelayTransport } from '@libp2p/circuit-relay-v2' +import { identify, identifyPush } from '@libp2p/identify' +import { ping } from '@libp2p/ping' +import { webRTC } from '@libp2p/webrtc' +import { webSockets } from '@libp2p/websockets' +import * as filters from '@libp2p/websockets/filters' +import { createLibp2p } from 'libp2p' + +// const RELAY_MULTIADDR = process.argv[2] + +async function createPublicNode () { + const publicNode = await createLibp2p({ + addresses: { + listen: [ + '/ip4/0.0.0.0/tcp/4005/ws', + '/ip4/0.0.0.0/tcp/4006/webrtc' + ] + }, + transports: [ + webSockets({ + filter: filters.all + }), + webRTC(), + circuitRelayTransport() + ], // Discover at least one relay] + connectionEncrypters: [noise()], + streamMuxers: [yamux()], + services: { + identify: identify(), + identifyPush: identifyPush(), + ping: ping() + } + }) + + try { + await publicNode.start() + console.log('Public Node started') + console.log(`Peer Id: ${publicNode.peerId.toString()}`) + } catch (error) { + console.error('Failed to start Public Node:', error) + } + console.log('Listening on:') + publicNode.getMultiaddrs().forEach((ma) => console.log(ma.toString())) + + publicNode.handle('/webrtc-chat/1.0.0', async ({ stream }) => { + console.log('Public Node: Incoming connection from private node') + const reader = stream.source.pipeThrough(new TextDecoderStream()).getReader() + try { + while (true) { + const { value, done } = await reader.read() + if (done) { + break + } + console.log(`Public Node Received: ${value}`) + } + } catch (err) { + console.error('Public Node: Error reading from stream:', err) + } + }) + return publicNode +} +createPublicNode() diff --git a/examples/js-libp2p-example-webrtc-private-to-public/test/index.spec.js b/examples/js-libp2p-example-webrtc-private-to-public/test/index.spec.js new file mode 100644 index 0000000..eb33f7b --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/test/index.spec.js @@ -0,0 +1,65 @@ +/* eslint-disable no-console */ +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { webRTCDirect } from '@libp2p/webrtc' +import { multiaddr } from '@multiformats/multiaddr' +import { pipe } from 'it-pipe' +import { createLibp2p } from 'libp2p' +import { setup, expect } from 'test-ipfs-example/browser' +import { fromString, toString } from 'uint8arrays' + +// Setup +const test = setup() + +let publicPeer +let privatePeer + +async function createPeer (isPublic = false) { + return await createLibp2p({ + transports: [webRTCDirect()], + connectionEncryption: [noise()], + streamMuxers: [yamux()] + }) +} + +test.before(async () => { + publicPeer = await createPeer(true) + await publicPeer.start() + + privatePeer = await createPeer(false) + await privatePeer.start() +}) + +test.after(async () => { + await publicPeer.stop() + await privatePeer.stop() +}) + +test('Private peer should connect to public peer', async () => { + const publicAddr = publicPeer.getMultiaddrs()[0].toString() + expect(publicAddr).toContain('/webrtc') + + const ma = multiaddr(publicAddr) + await expect(privatePeer.dial(ma)).resolves.not.toThrow() +}) + +test('Private peer should send and receive a message', async () => { + const { stream } = await privatePeer.dialProtocol(publicPeer.peerId, ['/chat/1.0.0']) + const message = 'Hello WebRTC' + + await pipe( + [fromString(message)], + stream.sink + ) + + await publicPeer.handle('/chat/1.0.0', async ({ stream }) => { + await pipe( + stream.source, + async function (source) { + for await (const msg of source) { + expect(toString(msg)).toBe(message) + } + } + ) + }) +}) diff --git a/examples/js-libp2p-example-webrtc-private-to-public/vite.config.js b/examples/js-libp2p-example-webrtc-private-to-public/vite.config.js new file mode 100644 index 0000000..37fe4f6 --- /dev/null +++ b/examples/js-libp2p-example-webrtc-private-to-public/vite.config.js @@ -0,0 +1,12 @@ +export default { + server: { + port: 3000, + open: true + }, + build: { + target: 'es2022' + }, + optimizeDeps: { + esbuildOptions: { target: 'es2022', supported: { bigint: true } } + } +}