diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index b9dfc2b..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,162 +0,0 @@ -name: CI -on: - push: - branches: - - main - pull_request: - branches: - - "**" - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - run: npm i - working-directory: ./examples - - uses: ipfs/aegir/actions/cache-node-modules@master - with: - directories: | - ./examples/node_modules - - check: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present lint - - run: npm run --if-present dep-check - - run: npm run --if-present docs:no-publish - - run: npm run --if-present doc-check - test-node: - needs: build - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [windows-latest, ubuntu-latest, macos-latest] - node: [lts/*] - fail-fast: true - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: ${{ matrix.node }} - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present test:node - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: node - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-chrome: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present test:chrome - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: chrome - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-chrome-webworker: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present test:chrome-webworker - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: chrome-webworker - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-firefox: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present test:firefox - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: firefox - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-firefox-webworker: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npm run --if-present test:firefox-webworker - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: firefox-webworker - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-webkit: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - - run: npx playwright install-deps - - run: npm run --if-present test:webkit - - uses: codecov/codecov-action@5ecb98a3c6b747ed38dc09f787459979aebb39be # v4.3.1 - with: - flags: webkit - files: .coverage/*,packages/*/.coverage/* - token: ${{ secrets.CODECOV_TOKEN }} - - test-examples: - needs: build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - - uses: ipfs/aegir/actions/cache-node-modules@master - with: - directories: | - ./examples/node_modules - - uses: actions/setup-go@v5 - - run: go build -o test-runner main.go - working-directory: ./examples/test-runner - - run: ../test-runner/test-runner -hasProxy - working-directory: ./examples/go-libp2p-http-proxy - - run: ../test-runner/test-runner - working-directory: ./examples/js-libp2p-client-and-node-server/ - - run: ../test-runner/test-runner - working-directory: ./examples/two-js-peers - - run: ./runTest.sh - working-directory: ./examples/peer-id-auth diff --git a/.github/workflows/test-examples.yml b/.github/workflows/test-examples.yml new file mode 100644 index 0000000..6b25e67 --- /dev/null +++ b/.github/workflows/test-examples.yml @@ -0,0 +1,47 @@ +name: test examples +on: + push: + branches: + - main + pull_request: + branches: + - "**" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + - run: npm i + working-directory: ./examples + - uses: ipfs/aegir/actions/cache-node-modules@master + with: + directories: | + ./examples/node_modules + + test-examples: + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + - uses: ipfs/aegir/actions/cache-node-modules@master + with: + directories: | + ./examples/node_modules + - uses: actions/setup-go@v5 + - run: go build -o test-runner main.go + working-directory: ./examples/test-runner + - run: ../test-runner/test-runner -hasProxy + working-directory: ./examples/go-libp2p-http-proxy + - run: ../test-runner/test-runner + working-directory: ./examples/js-libp2p-client-and-node-server/ + - run: ../test-runner/test-runner + working-directory: ./examples/two-js-peers + - run: ./runTest.sh + working-directory: ./examples/peer-id-auth diff --git a/examples/go-libp2p-http-proxy/client.js b/examples/go-libp2p-http-proxy/client.js new file mode 100644 index 0000000..8d25612 --- /dev/null +++ b/examples/go-libp2p-http-proxy/client.js @@ -0,0 +1,58 @@ +/* eslint-disable no-console */ + +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { http } from '@libp2p/http-fetch' +import { tcp } from '@libp2p/tcp' +import { multiaddr } from '@multiformats/multiaddr' +import { createLibp2p } from 'libp2p' + +const node = await createLibp2p({ + // libp2p nodes are started by default, pass false to override this + start: false, + addresses: { + listen: [] + }, + transports: [tcp()], + connectionEncrypters: [noise()], + streamMuxers: [yamux()], + services: { http: http() } +}) + +// start libp2p +await node.start() +console.error('libp2p has started') + +// Read server multiaddr from the command line +const serverAddr = process.argv[2] +if (!serverAddr) { + console.error('Please provide the server multiaddr as an argument') + process.exit(1) +} + +let serverMA = multiaddr(serverAddr) + +// check if this is an http transport multiaddr +const isHTTPTransport = serverMA.protos().find(p => p.name === 'http') +if (!isHTTPTransport && serverMA.getPeerId() === null) { + // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. + // Otherwise js-libp2p will open a new connection for each request. + const conn = await node.dial(serverMA) + serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) +} + +console.error(`Making request to ${serverMA.toString()}`) +try { + const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}`)) + const respBody = await resp.text() + if (resp.status !== 200) { + throw new Error(`Unexpected status code: ${resp.status}`) + } + if (respBody !== 'Hello, World!') { + throw new Error(`Unexpected response body: ${respBody}`) + } + console.error('Got response:', respBody) +} finally { + // stop libp2p + await node.stop() +} diff --git a/examples/go-libp2p-http-proxy/client.mjs b/examples/go-libp2p-http-proxy/client.mjs deleted file mode 100644 index 32593a3..0000000 --- a/examples/go-libp2p-http-proxy/client.mjs +++ /dev/null @@ -1,57 +0,0 @@ -import { noise } from '@chainsafe/libp2p-noise' -import { multiaddr } from '@multiformats/multiaddr' -import { yamux } from '@chainsafe/libp2p-yamux' -import { tcp } from '@libp2p/tcp' -import { createLibp2p } from 'libp2p' -import { http } from '@libp2p/http-fetch' - -const node = await createLibp2p({ - // libp2p nodes are started by default, pass false to override this - start: false, - addresses: { - listen: [] - }, - transports: [tcp()], - connectionEncryption: [noise()], - streamMuxers: [yamux()], - services: { http: http() } -}) - -// start libp2p -await node.start() -console.error('libp2p has started') - -// Read server multiaddr from the command line -const serverAddr = process.argv[2] -if (!serverAddr) { - console.error('Please provide the server multiaddr as an argument') - process.exit(1) -} - -let serverMA = multiaddr(serverAddr) - -const isHTTPTransport = serverMA.protos().find(p => p.name === "http") // check if this is an http transport multiaddr -if (!isHTTPTransport && serverMA.getPeerId() === null) { - // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. - // Otherwise js-libp2p will open a new connection for each request. - const conn = await node.dial(serverMA) - serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) -} - -console.error("Making request to", `${serverMA.toString()}`) -try { - const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}`)) - const respBody = await resp.text() - if (resp.status !== 200) { - throw new Error(`Unexpected status code: ${resp.status}`) - } - if (respBody !== 'Hello, World!') { - throw new Error(`Unexpected response body: ${respBody}`) - } - console.error("Got response:", respBody) -} finally { - // stop libp2p - await node.stop() -} - - diff --git a/examples/go-libp2p-http-proxy/server.js b/examples/go-libp2p-http-proxy/server.js new file mode 100644 index 0000000..2f6b1f4 --- /dev/null +++ b/examples/go-libp2p-http-proxy/server.js @@ -0,0 +1,18 @@ +/* eslint-disable no-console */ + +import http from 'http' + +const port = 55776 + +const server = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end('Hello, World!') +}) + +server.listen(port, () => { + console.error(`Server running at: http://localhost:${port}/`) + // Print multiaddr on stdout for test + console.error("Server's multiaddr is:") + console.log(`/dns4/localhost/tcp/${port}/http`) + console.log('') // Empty line to signal we have no more addresses (for test runner) +}) diff --git a/examples/go-libp2p-http-proxy/server.mjs b/examples/go-libp2p-http-proxy/server.mjs deleted file mode 100644 index 1c9b085..0000000 --- a/examples/go-libp2p-http-proxy/server.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import http from 'http'; - -const port = 55776; - -const server = http.createServer((req, res) => { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('Hello, World!'); -}); - -server.listen(port, () => { - console.error(`Server running at: http://localhost:${port}/`); - // Print multiaddr on stdout for test - console.error("Server's multiaddr is:") - console.log(`/dns4/localhost/tcp/${port}/http`) - console.log("") // Empty line to signal we have no more addresses (for test runner) -}); diff --git a/examples/hono-server-over-libp2p/client.mjs b/examples/hono-server-over-libp2p/client.js similarity index 82% rename from examples/hono-server-over-libp2p/client.mjs rename to examples/hono-server-over-libp2p/client.js index f2726c6..5e3c4d4 100644 --- a/examples/hono-server-over-libp2p/client.mjs +++ b/examples/hono-server-over-libp2p/client.js @@ -1,10 +1,12 @@ +/* eslint-disable no-console */ + import { noise } from '@chainsafe/libp2p-noise' -import { multiaddr } from '@multiformats/multiaddr' import { yamux } from '@chainsafe/libp2p-yamux' +import { http } from '@libp2p/http-fetch' +import { sendPing } from '@libp2p/http-fetch/ping.js' import { tcp } from '@libp2p/tcp' +import { multiaddr } from '@multiformats/multiaddr' import { createLibp2p } from 'libp2p' -import { http } from '@libp2p/http-fetch' -import { sendPing } from '@libp2p/http-fetch/ping.js' const node = await createLibp2p({ // libp2p nodes are started by default, pass false to override this @@ -13,7 +15,7 @@ const node = await createLibp2p({ listen: [] }, transports: [tcp()], - connectionEncryption: [noise()], + connectionEncrypters: [noise()], streamMuxers: [yamux()], services: { http: http() } }) @@ -31,7 +33,7 @@ if (!serverAddr) { let serverMA = multiaddr(serverAddr) -const isHTTPTransport = serverMA.protos().find(p => p.name === "http") // check if this is an http transport multiaddr +const isHTTPTransport = serverMA.protos().find(p => p.name === 'http') // check if this is an http transport multiaddr if (!isHTTPTransport && serverMA.getPeerId() === null) { // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. // Otherwise js-libp2p will open a new connection for each request. @@ -39,7 +41,7 @@ if (!isHTTPTransport && serverMA.getPeerId() === null) { serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) } -console.error("Making request to", `${serverMA.toString()}`) +console.error('Making request to', `${serverMA.toString()}`) try { const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}` + `/http-path/${encodeURIComponent('my-app')}`)) const respBody = await resp.text() @@ -53,7 +55,7 @@ try { const start = new Date().getTime() await sendPing(node, serverMA) const end = new Date().getTime() - console.error("HTTP Ping took", end - start, "ms") + console.error('HTTP Ping took', end - start, 'ms') } finally { await node.stop() } diff --git a/examples/hono-server-over-libp2p/server.mjs b/examples/hono-server-over-libp2p/server.js similarity index 77% rename from examples/hono-server-over-libp2p/server.mjs rename to examples/hono-server-over-libp2p/server.js index b75c044..45f7506 100644 --- a/examples/hono-server-over-libp2p/server.mjs +++ b/examples/hono-server-over-libp2p/server.js @@ -1,11 +1,13 @@ +/* eslint-disable no-console */ + import { noise } from '@chainsafe/libp2p-noise' import { yamux } from '@chainsafe/libp2p-yamux' -import { tcp } from '@libp2p/tcp' -import { createLibp2p } from 'libp2p' +import { serve } from '@hono/node-server' import { WELL_KNOWN_PROTOCOLS, httpCustomServer } from '@libp2p/http-fetch' import { PING_PROTOCOL_ID, servePing } from '@libp2p/http-fetch/ping.js' +import { tcp } from '@libp2p/tcp' import { Hono } from 'hono' -import { serve } from '@hono/node-server' +import { createLibp2p } from 'libp2p' const app = new Hono() @@ -16,22 +18,22 @@ const node = await createLibp2p({ listen: ['/ip4/127.0.0.1/tcp/8000'] }, transports: [tcp()], - connectionEncryption: [noise()], + connectionEncrypters: [noise()], streamMuxers: [yamux()], - services: {http: httpCustomServer({customHTTPHandler: app.fetch.bind(app)})} + services: { http: httpCustomServer({ customHTTPHandler: app.fetch.bind(app) }) } }) app.get(WELL_KNOWN_PROTOCOLS, async (c) => { return node.services.http.serveWellKnownProtocols(c.req) }) app.get('/my-app', (c) => c.text('Hono!')) -node.services.http.registerProtocol('/example-app/0.0.1', "/my-app") +node.services.http.registerProtocol('/example-app/0.0.1', '/my-app') // Register HTTP ping protocol app.all('/ping', (c) => { return servePing(c.req) }) -node.services.http.registerProtocol(PING_PROTOCOL_ID, "/ping") +node.services.http.registerProtocol(PING_PROTOCOL_ID, '/ping') // start libp2p await node.start() @@ -41,17 +43,16 @@ console.error('libp2p has started') const server = serve({ fetch: app.fetch, port: 8001, - hostname: '127.0.0.1', + hostname: '127.0.0.1' }) const listenAddrs = node.getMultiaddrs() console.error('libp2p is listening on the following addresses:') -console.log(`/ip4/127.0.0.1/tcp/8001/http`) +console.log('/ip4/127.0.0.1/tcp/8001/http') for (const addr of listenAddrs) { console.log(addr.toString()) } -console.log("") // Empty line to signal we have no more addresses (for test runner) - +console.log('') // Empty line to signal we have no more addresses (for test runner) // wait for SIGINT await new Promise(resolve => process.on('SIGINT', resolve)) @@ -62,4 +63,3 @@ server.close() // stop libp2p node.stop() console.error('libp2p has stopped') - diff --git a/examples/js-libp2p-client-and-node-server/client.js b/examples/js-libp2p-client-and-node-server/client.js new file mode 100644 index 0000000..d54a76a --- /dev/null +++ b/examples/js-libp2p-client-and-node-server/client.js @@ -0,0 +1,57 @@ +/* eslint-disable no-console */ + +import { noise } from '@chainsafe/libp2p-noise' +import { yamux } from '@chainsafe/libp2p-yamux' +import { http } from '@libp2p/http-fetch' +import { tcp } from '@libp2p/tcp' +import { multiaddr } from '@multiformats/multiaddr' +import { createLibp2p } from 'libp2p' + +const node = await createLibp2p({ + // libp2p nodes are started by default, pass false to override this + start: false, + addresses: { + listen: [] + }, + transports: [tcp()], + connectionEncrypters: [noise()], + streamMuxers: [yamux()], + services: { http: http() } +}) + +// start libp2p +await node.start() +console.error('libp2p has started') + +// Read server multiaddr from the command line +const serverAddr = process.argv[2] +if (!serverAddr) { + console.error('Please provide the server multiaddr as an argument') + process.exit(1) +} + +let serverMA = multiaddr(serverAddr) + +const isHTTPTransport = serverMA.protos().find(p => p.name === 'http') // check if this is an http transport multiaddr +if (!isHTTPTransport && serverMA.getPeerId() === null) { + // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. + // Otherwise js-libp2p will open a new connection for each request. + const conn = await node.dial(serverMA) + serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) +} + +console.error('Making request to', `${serverMA.toString()}`) +try { + const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}`)) + const respBody = await resp.text() + if (resp.status !== 200) { + throw new Error(`Unexpected status code: ${resp.status}`) + } + if (respBody !== 'Hello, World!') { + throw new Error(`Unexpected response body: ${respBody}`) + } + console.error('Got response:', respBody) +} finally { + // stop libp2p + await node.stop() +} diff --git a/examples/js-libp2p-client-and-node-server/client.mjs b/examples/js-libp2p-client-and-node-server/client.mjs deleted file mode 100644 index 32593a3..0000000 --- a/examples/js-libp2p-client-and-node-server/client.mjs +++ /dev/null @@ -1,57 +0,0 @@ -import { noise } from '@chainsafe/libp2p-noise' -import { multiaddr } from '@multiformats/multiaddr' -import { yamux } from '@chainsafe/libp2p-yamux' -import { tcp } from '@libp2p/tcp' -import { createLibp2p } from 'libp2p' -import { http } from '@libp2p/http-fetch' - -const node = await createLibp2p({ - // libp2p nodes are started by default, pass false to override this - start: false, - addresses: { - listen: [] - }, - transports: [tcp()], - connectionEncryption: [noise()], - streamMuxers: [yamux()], - services: { http: http() } -}) - -// start libp2p -await node.start() -console.error('libp2p has started') - -// Read server multiaddr from the command line -const serverAddr = process.argv[2] -if (!serverAddr) { - console.error('Please provide the server multiaddr as an argument') - process.exit(1) -} - -let serverMA = multiaddr(serverAddr) - -const isHTTPTransport = serverMA.protos().find(p => p.name === "http") // check if this is an http transport multiaddr -if (!isHTTPTransport && serverMA.getPeerId() === null) { - // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. - // Otherwise js-libp2p will open a new connection for each request. - const conn = await node.dial(serverMA) - serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) -} - -console.error("Making request to", `${serverMA.toString()}`) -try { - const resp = await node.services.http.fetch(new Request(`multiaddr:${serverMA}`)) - const respBody = await resp.text() - if (resp.status !== 200) { - throw new Error(`Unexpected status code: ${resp.status}`) - } - if (respBody !== 'Hello, World!') { - throw new Error(`Unexpected response body: ${respBody}`) - } - console.error("Got response:", respBody) -} finally { - // stop libp2p - await node.stop() -} - - diff --git a/examples/js-libp2p-client-and-node-server/server.js b/examples/js-libp2p-client-and-node-server/server.js new file mode 100644 index 0000000..2f6b1f4 --- /dev/null +++ b/examples/js-libp2p-client-and-node-server/server.js @@ -0,0 +1,18 @@ +/* eslint-disable no-console */ + +import http from 'http' + +const port = 55776 + +const server = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end('Hello, World!') +}) + +server.listen(port, () => { + console.error(`Server running at: http://localhost:${port}/`) + // Print multiaddr on stdout for test + console.error("Server's multiaddr is:") + console.log(`/dns4/localhost/tcp/${port}/http`) + console.log('') // Empty line to signal we have no more addresses (for test runner) +}) diff --git a/examples/js-libp2p-client-and-node-server/server.mjs b/examples/js-libp2p-client-and-node-server/server.mjs deleted file mode 100644 index 1c9b085..0000000 --- a/examples/js-libp2p-client-and-node-server/server.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import http from 'http'; - -const port = 55776; - -const server = http.createServer((req, res) => { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('Hello, World!'); -}); - -server.listen(port, () => { - console.error(`Server running at: http://localhost:${port}/`); - // Print multiaddr on stdout for test - console.error("Server's multiaddr is:") - console.log(`/dns4/localhost/tcp/${port}/http`) - console.log("") // Empty line to signal we have no more addresses (for test runner) -}); diff --git a/examples/package.json b/examples/package.json index 611ffe3..629fa68 100644 --- a/examples/package.json +++ b/examples/package.json @@ -1,17 +1,18 @@ { "name": "js-libp2p-whatwg-examples", "version": "0.0.1", + "type": "module", "dependencies": { - "@chainsafe/libp2p-noise": "^15.0.0", - "@chainsafe/libp2p-yamux": "^6.0.2", + "@chainsafe/libp2p-noise": "^16.0.0", + "@chainsafe/libp2p-yamux": "^7.0.1", "@hono/node-server": "^1.11.2", "@libp2p/http-fetch": "file:..", - "@libp2p/peer-id": "^4.1.3", - "@libp2p/tcp": "^9.0.26", + "@libp2p/peer-id": "^5.0.7", + "@libp2p/tcp": "^10.0.11", "@multiformats/multiaddr": "^12.3.0", "@multiformats/multiaddr-to-uri": "^10.1.0", "hono": "^4.4.4", - "libp2p": "^1.6.0" + "libp2p": "^2.2.1" }, "license": "Apache-2.0 OR MIT" } diff --git a/examples/peer-id-auth/node.mjs b/examples/peer-id-auth/node.js similarity index 66% rename from examples/peer-id-auth/node.mjs rename to examples/peer-id-auth/node.js index 6482dee..8943ffc 100644 --- a/examples/peer-id-auth/node.mjs +++ b/examples/peer-id-auth/node.js @@ -1,28 +1,30 @@ -import { unmarshalPrivateKey } from '@libp2p/crypto/keys' -import { WellKnownHandler, WELL_KNOWN_PROTOCOLS } from '@libp2p/http-fetch/well-known-handler.js' +/* eslint-disable no-console */ + +import { serve } from '@hono/node-server' +import { generateKeyPair } from '@libp2p/crypto/keys' import { ClientAuth, HTTPPeerIDAuthProto, ServerAuth } from '@libp2p/http-fetch/auth.js' +import { WellKnownHandler, WELL_KNOWN_PROTOCOLS } from '@libp2p/http-fetch/well-known-handler.js' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { Hono } from 'hono' -import { serve } from '@hono/node-server' -import { createEd25519PeerId } from '@libp2p/peer-id-factory' -const myID = await createEd25519PeerId() -const privKey = await unmarshalPrivateKey(myID.privateKey) +const privKey = await generateKeyPair('Ed25519') +const myID = peerIdFromPrivateKey(privKey) const wellKnownHandler = new WellKnownHandler() const args = process.argv.slice(2) if (args.length === 1 && args[0] === 'client') { // Client mode const client = new ClientAuth(privKey) - const observedPeerID = await client.authenticateServer(fetch, "localhost:8001", "http://localhost:8001/auth") - console.log("Server ID:", observedPeerID.toString()) + const observedPeerID = await client.authenticateServer(fetch, 'localhost:8001', 'http://localhost:8001/auth') + console.log('Server ID:', observedPeerID.toString()) - const authenticatedReq = new Request("http://localhost:8001/log-my-id", { + const authenticatedReq = new Request('http://localhost:8001/log-my-id', { headers: { - Authorization: client.bearerAuthHeader("localhost:8001") + Authorization: client.bearerAuthHeader('localhost:8001') } }) await fetch(authenticatedReq) - console.log("Client ID:", myID.toString()) + console.log('Client ID:', myID.toString()) process.exit(0) } // Server mode @@ -38,27 +40,27 @@ app.get(WELL_KNOWN_PROTOCOLS, async (c) => { app.all('/auth', (c) => { return httpServerAuth.httpHandler(addHeadersProxy(c.req)) }) -wellKnownHandler.registerProtocol(HTTPPeerIDAuthProto, "/auth") +wellKnownHandler.registerProtocol(HTTPPeerIDAuthProto, '/auth') app.all('/log-my-id', async (c) => { try { - const id = await httpServerAuth.unwrapBearerToken("localhost:8001", c.req.header('Authorization')) - console.log("Client ID:", id.toString()) + const id = await httpServerAuth.unwrapBearerToken('localhost:8001', c.req.header('Authorization')) + console.log('Client ID:', id.toString()) } catch (e) { console.error(e) return c.text(e.message, { status: 400 }) } c.status(200) }) -wellKnownHandler.registerProtocol("/log-my-id/1", "/log-my-id") +wellKnownHandler.registerProtocol('/log-my-id/1', '/log-my-id') const server = serve({ fetch: app.fetch, port: 8001, - hostname: '127.0.0.1', + hostname: '127.0.0.1' }) -console.log("Server ID:", myID.toString()) +console.log('Server ID:', myID.toString()) // wait for SIGINT await new Promise(resolve => process.on('SIGINT', resolve)) @@ -70,7 +72,7 @@ server.close() // exposes headers and how hono's Request type exposes headers. // The standard Request type exposes headers as a Headers object, while // hono's Request type has a function `header(name: string): string | null` to get the header -function addHeadersProxy(req) { +function addHeadersProxy (req) { return new Proxy(req, { get: (target, prop) => { if (prop === 'headers') { diff --git a/examples/peer-id-auth/runTest.sh b/examples/peer-id-auth/runTest.sh index 6da6deb..752e5b5 100755 --- a/examples/peer-id-auth/runTest.sh +++ b/examples/peer-id-auth/runTest.sh @@ -27,8 +27,8 @@ trap cleanup EXIT GO_SERVER="./go-node" GO_CLIENT="./go-node client" -NODE_SERVER="node node.mjs" -NODE_CLIENT="node node.mjs client" +NODE_SERVER="node node.js" +NODE_CLIENT="node node.js client" # Define server arrays SERVERS=("$GO_SERVER" "$NODE_SERVER") diff --git a/examples/test-runner/main.go b/examples/test-runner/main.go index 4b8f9d1..48c545e 100644 --- a/examples/test-runner/main.go +++ b/examples/test-runner/main.go @@ -63,7 +63,7 @@ func runTest(hasProxy bool) error { } func runServer(ctx context.Context) (*exec.Cmd, []string, error) { - serverCmd := exec.CommandContext(ctx, "node", "server.mjs") + serverCmd := exec.CommandContext(ctx, "node", "server.js") serverCmd.Stderr = os.Stderr serverCmd.Cancel = func() error { serverCmd.Process.Signal(os.Interrupt) @@ -93,7 +93,7 @@ func runServer(ctx context.Context) (*exec.Cmd, []string, error) { } func runClient(serverMultiaddr string) error { - clientCmd := exec.Command("node", "client.mjs", serverMultiaddr) + clientCmd := exec.Command("node", "client.js", serverMultiaddr) clientCmd.Stderr = os.Stderr return clientCmd.Run() } diff --git a/examples/two-js-peers/client.mjs b/examples/two-js-peers/client.js similarity index 81% rename from examples/two-js-peers/client.mjs rename to examples/two-js-peers/client.js index 53b8e94..08bfa61 100644 --- a/examples/two-js-peers/client.mjs +++ b/examples/two-js-peers/client.js @@ -1,11 +1,13 @@ +/* eslint-disable no-console */ + import { noise } from '@chainsafe/libp2p-noise' -import { multiaddr } from '@multiformats/multiaddr' import { yamux } from '@chainsafe/libp2p-yamux' -import { tcp } from '@libp2p/tcp' -import { createLibp2p } from 'libp2p' import { http } from '@libp2p/http-fetch' -import { sendPing } from '@libp2p/http-fetch/ping.js' +import { sendPing } from '@libp2p/http-fetch/ping.js' import { peerIdFromString } from '@libp2p/peer-id' +import { tcp } from '@libp2p/tcp' +import { multiaddr } from '@multiformats/multiaddr' +import { createLibp2p } from 'libp2p' const node = await createLibp2p({ // libp2p nodes are started by default, pass false to override this @@ -14,7 +16,7 @@ const node = await createLibp2p({ listen: [] }, transports: [tcp()], - connectionEncryption: [noise()], + connectionEncrypters: [noise()], streamMuxers: [yamux()], services: { http: http() } }) @@ -32,7 +34,7 @@ if (!serverAddr) { let serverMA = multiaddr(serverAddr) -const isHTTPTransport = serverMA.protos().find(p => p.name === "http") // check if this is an http transport multiaddr +const isHTTPTransport = serverMA.protos().find(p => p.name === 'http') // check if this is an http transport multiaddr if (!isHTTPTransport && serverMA.getPeerId() === null) { // Learn the peer id of the server. This lets us reuse the connection for all our HTTP requests. // Otherwise js-libp2p will open a new connection for each request. @@ -40,13 +42,13 @@ if (!isHTTPTransport && serverMA.getPeerId() === null) { serverMA = serverMA.encapsulate(`/p2p/${conn.remotePeer.toString()}`) } -console.error("Making request to", `${serverMA.toString()}`) +console.error('Making request to', `${serverMA.toString()}`) try { for (let i = 0; i < 2; i++) { const start = new Date().getTime() await sendPing(node, serverMA) const end = new Date().getTime() - console.error("Got response! took", end - start, "ms") + console.error('Got response! took', end - start, 'ms') console.log(end - start) // sleep 1s await new Promise(resolve => setTimeout(resolve, 1000)) @@ -59,7 +61,7 @@ try { const start = new Date().getTime() await sendPing(node, peerIdFromString(serverMA.getPeerId())) const end = new Date().getTime() - console.error("Got response! took", end - start, "ms") + console.error('Got response! took', end - start, 'ms') console.log(end - start) } } finally { diff --git a/examples/two-js-peers/server.mjs b/examples/two-js-peers/server.js similarity index 85% rename from examples/two-js-peers/server.mjs rename to examples/two-js-peers/server.js index d3126b7..aa5234a 100644 --- a/examples/two-js-peers/server.mjs +++ b/examples/two-js-peers/server.js @@ -1,9 +1,11 @@ +/* eslint-disable no-console */ + import { noise } from '@chainsafe/libp2p-noise' import { yamux } from '@chainsafe/libp2p-yamux' -import { tcp } from '@libp2p/tcp' -import { createLibp2p } from 'libp2p' import { http } from '@libp2p/http-fetch' import { PING_PROTOCOL_ID, servePing } from '@libp2p/http-fetch/ping.js' +import { tcp } from '@libp2p/tcp' +import { createLibp2p } from 'libp2p' const node = await createLibp2p({ // libp2p nodes are started by default, pass false to override this @@ -12,9 +14,9 @@ const node = await createLibp2p({ listen: ['/ip4/127.0.0.1/tcp/8000'] }, transports: [tcp()], - connectionEncryption: [noise()], + connectionEncrypters: [noise()], streamMuxers: [yamux()], - services: {http: http()} + services: { http: http() } }) // start libp2p @@ -24,7 +26,7 @@ console.error('libp2p has started') const listenAddrs = node.getMultiaddrs() console.error('libp2p is listening on the following address:') console.log(listenAddrs[0].toString()) -console.log("") // Empty line to signal we have no more addresses (for test runner) +console.log('') // Empty line to signal we have no more addresses (for test runner) node.services.http.handleHTTPProtocol(PING_PROTOCOL_ID, '/ping', servePing) @@ -34,4 +36,3 @@ await new Promise(resolve => setTimeout(resolve, 100000)) // stop libp2p await node.stop() console.error('libp2p has stopped') - diff --git a/package.json b/package.json index d582799..80b420f 100644 --- a/package.json +++ b/package.json @@ -167,10 +167,10 @@ "release": "aegir release" }, "dependencies": { - "@libp2p/crypto": "^4.1.2", - "@libp2p/interface": "^1.2.0", - "@libp2p/interface-internal": "^1.1.0", - "@libp2p/peer-id": "^4.1.3", + "@libp2p/crypto": "^5.0.6", + "@libp2p/interface": "^2.2.0", + "@libp2p/interface-internal": "^2.0.10", + "@libp2p/peer-id": "^5.0.7", "@multiformats/multiaddr": "^12.3.0", "@multiformats/multiaddr-to-uri": "^10.1.0", "@perseveranza-pets/milo": "^0.2.1", @@ -180,12 +180,11 @@ "uint8arrays": "^5.1.0" }, "devDependencies": { - "@libp2p/interface-compliance-tests": "^5.4.1", - "@libp2p/logger": "^4.0.10", - "@libp2p/peer-id-factory": "^4.1.2", + "@libp2p/interface-compliance-tests": "^6.1.8", + "@libp2p/logger": "^5.1.3", "aegir": "^45.0.0", "it-pair": "^2.0.6", - "libp2p": "^1.6.0", + "libp2p": "^2.2.1", "sinon-ts": "^2.0.0" }, "sideEffects": false diff --git a/src/auth/client.ts b/src/auth/client.ts index 64873cf..685f388 100644 --- a/src/auth/client.ts +++ b/src/auth/client.ts @@ -1,5 +1,5 @@ -import { unmarshalPublicKey, marshalPublicKey } from '@libp2p/crypto/keys' -import { peerIdFromKeys } from '@libp2p/peer-id' +import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys' +import { peerIdFromPublicKey } from '@libp2p/peer-id' import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays' import { parseHeader, PeerIDAuthScheme, sign, verify } from './common.js' import type { PeerId, PrivateKey } from '@libp2p/interface' @@ -60,7 +60,7 @@ export class ClientAuth { } // Client initiated handshake (server initiated is not implemented yet) - const marshaledClientPubKey = marshalPublicKey(this.key.public) + const marshaledClientPubKey = publicKeyToProtobuf(this.key.publicKey) const publicKeyStr = uint8ArrayToString(marshaledClientPubKey, 'base64urlpad') const challengeServer = this.generateChallenge() const headers = { @@ -79,7 +79,7 @@ export class ClientAuth { } const authFields = parseHeader(authHeader) const serverPubKeyBytes = uint8ArrayFromString(authFields['public-key'], 'base64urlpad') - const serverPubKey = unmarshalPublicKey(serverPubKeyBytes) + const serverPubKey = publicKeyFromProtobuf(serverPubKeyBytes) const valid = await verify(serverPubKey, PeerIDAuthScheme, [ ['hostname', hostname], @@ -115,7 +115,8 @@ export class ClientAuth { } const serverAuthFields = parseHeader(serverAuthHeader) - const serverID = await peerIdFromKeys(serverPubKeyBytes) + const serverPublicKey = publicKeyFromProtobuf(serverPubKeyBytes) + const serverID = peerIdFromPublicKey(serverPublicKey) this.tokens.set(hostname, { peer: serverID, creationTime: new Date(), diff --git a/src/auth/server.ts b/src/auth/server.ts index 43048f5..052d29d 100644 --- a/src/auth/server.ts +++ b/src/auth/server.ts @@ -1,5 +1,5 @@ -import { unmarshalPublicKey, marshalPublicKey } from '@libp2p/crypto/keys' -import { peerIdFromKeys, peerIdFromString } from '@libp2p/peer-id' +import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys' +import { peerIdFromPublicKey, peerIdFromString } from '@libp2p/peer-id' import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays' import { encodeAuthParams, parseHeader, PeerIDAuthScheme, sign, verify } from './common.js' import type { PeerId, PrivateKey, PublicKey, Logger } from '@libp2p/interface' @@ -95,9 +95,9 @@ export class ServerAuth { let clientPublicKey: PublicKey | null = null if (opaqueState?.clientPublicKey !== undefined) { - clientPublicKey = unmarshalPublicKey(uint8ArrayFromString(opaqueState.clientPublicKey, 'base64urlpad')) + clientPublicKey = publicKeyFromProtobuf(uint8ArrayFromString(opaqueState.clientPublicKey, 'base64urlpad')) } else if (authFields['public-key'] !== undefined) { - clientPublicKey = unmarshalPublicKey(uint8ArrayFromString(authFields['public-key'], 'base64urlpad')) + clientPublicKey = publicKeyFromProtobuf(uint8ArrayFromString(authFields['public-key'], 'base64urlpad')) } const returnParams: Record = {} @@ -116,7 +116,7 @@ export class ServerAuth { const valid = await verify(clientPublicKey, PeerIDAuthScheme, [ ['challenge-client', opaqueState?.challengeClient ?? ''], ['hostname', hostname], - ['server-public-key', marshalPublicKey(this.key.public)] + ['server-public-key', publicKeyToProtobuf(this.key.publicKey)] ], uint8ArrayFromString(authFields.sig, 'base64urlpad')) if (!valid) { this.logger?.error('Invalid signature') @@ -124,7 +124,7 @@ export class ServerAuth { } // Return a bearer token - clientPeerId = await peerIdFromKeys(marshalPublicKey(clientPublicKey)) + clientPeerId = peerIdFromPublicKey(clientPublicKey) returnParams.bearer = this.genBearerToken(clientPeerId, hostname) } @@ -137,10 +137,10 @@ export class ServerAuth { // Sign and return challenge const sig = await sign(this.key, PeerIDAuthScheme, [ ['hostname', hostname], - ['client-public-key', marshalPublicKey(clientPublicKey)], + ['client-public-key', publicKeyToProtobuf(clientPublicKey)], ['challenge-server', authFields['challenge-server']] ]) - returnParams['public-key'] = uint8ArrayToString(marshalPublicKey(this.key.public), 'base64urlpad') + returnParams['public-key'] = uint8ArrayToString(publicKeyToProtobuf(this.key.publicKey), 'base64urlpad') returnParams.sig = uint8ArrayToString(sig, 'base64urlpad') } @@ -176,7 +176,7 @@ export class ServerAuth { returnParams.opaque = this.genOpaque({ challengeClient: challenge, - clientPublicKey: clientPublicKey !== null ? uint8ArrayToString(marshalPublicKey(clientPublicKey), 'base64urlpad') : undefined, + clientPublicKey: clientPublicKey !== null ? uint8ArrayToString(publicKeyToProtobuf(clientPublicKey), 'base64urlpad') : undefined, hostname, creationTime: Date.now() }) @@ -196,7 +196,7 @@ export class ServerAuth { throw new Error('Invalid bearer token') } const bearer = parseHeader(token).bearer - const unwrapped = await this.verifyBox(this.key.public, bearer) as any + const unwrapped = await this.verifyBox(this.key.publicKey, bearer) as any if (typeof unwrapped.peer !== 'string' || typeof unwrapped.h !== 'string' || typeof unwrapped.t !== 'number') { throw new Error('Invalid bearer token') } @@ -214,7 +214,7 @@ export class ServerAuth { } async unwrapOpaque (opaque: string): Promise { - const unwrapped = await this.verifyBox(this.key.public, opaque) as any + const unwrapped = await this.verifyBox(this.key.publicKey, opaque) as any if (typeof unwrapped.challengeClient !== 'string' || typeof unwrapped.hostname !== 'string' || typeof unwrapped.creationTime !== 'number') { throw new Error('Invalid opaque') } diff --git a/test/auth/index.spec.ts b/test/auth/index.spec.ts index fbc3f48..0962c9f 100644 --- a/test/auth/index.spec.ts +++ b/test/auth/index.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { generateKeyPair, unmarshalPrivateKey } from '@libp2p/crypto/keys' -import { createFromPrivKey } from '@libp2p/peer-id-factory' +import { generateKeyPair, privateKeyFromProtobuf } from '@libp2p/crypto/keys' +import { peerIdFromPrivateKey } from '@libp2p/peer-id' import { expect } from 'aegir/chai' import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays' import { ClientAuth } from '../../src/auth/client.js' @@ -18,7 +18,7 @@ describe('HTTP Peer ID Authentication', () => { init = true clientKey = await generateKeyPair('Ed25519') serverKey = await generateKeyPair('Ed25519') - server = await createFromPrivKey(serverKey) + server = peerIdFromPrivateKey(serverKey) } }) @@ -40,7 +40,7 @@ describe('HTTP Peer ID Authentication', () => { const clientKeyHex = '080112208139770ea87d175f56a35466c34c7ecccb8d8a91b4ee37a25df60f5b8fc9b394' const serverKeyHex = '0801124001010101010101010101010101010101010101010101010101010101010101018a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c' const clientPubKeyEncoded = uint8ArrayFromString(clientKeyHex, 'base16') - const serverKey = await unmarshalPrivateKey(uint8ArrayFromString(serverKeyHex, 'base16')) + const serverKey = privateKeyFromProtobuf(uint8ArrayFromString(serverKeyHex, 'base16')) const serverSig = await sign(serverKey, PeerIDAuthScheme, [ ['challenge-server', 'ERERERERERERERERERERERERERERERERERERERERERE='],