Skip to content

Instantly share code, notes, and snippets.

@timaschew
Last active February 22, 2023 07:04
Show Gist options
  • Save timaschew/c5d9c2e84201833827000c24b3a163ce to your computer and use it in GitHub Desktop.
Save timaschew/c5d9c2e84201833827000c24b3a163ce to your computer and use it in GitHub Desktop.
Peerjs with peerID validation by using ed25519
import Peer from "peerjs"
import * as ed from "@noble/ed25519";
import { Buffer } from "buffer"
(async function() {
const privateKey = ed.utils.randomPrivateKey()
const _message = Date.now().toString(16)
const message = Uint8Array.from(Buffer.from(_message, "hex"))
const publicKey = await ed.getPublicKey(privateKey)
const peerId = Buffer.from(publicKey).toString("hex")
const signature = await ed.sign(message, privateKey);
const _signature = Buffer.from(signature).toString("hex")
window.myPeer = new Peer(peerId, {
debug: 3,
token: `ed25519|${_signature}|${_message}`,
host: 'localhost',
port: 9000,
path: '/api'
});
})()

Example payload of the client

{
  id: '621843f72d062b5f94b5c928cae92382711090dc0d22b55ef5a51ca0b1f8482e'
  token: 'ed25519|733bed773f5821caf27d0c12ee43b589ce508db2326fedf4c5d44f8d8b2dae716f128b059d732b879d7bfc1b59e7ccd1d13b3336db23f5e4e85b89519a66760a|17ef87ecc06'
}
const ed = require('@noble/ed25519')
const express = require('express')
const ExpressPeerServer = require('peer').ExpressPeerServer
const PORT = process.env.PORT | 9000
const app = express()
const server = app.listen(PORT)
peerServer = ExpressPeerServer(server, {
debug: true
})
app.use('/api',peerServer)
peerServer.on('connection', async function(connection) {
const { id, token } = connection
if (id.length == 64 && id.match(/[^0123456789abcdef]/) == null) {
const [mode, signature, message] = token.split('|')
if (mode === 'ed25519') {
date = new Date(parseInt(message, 16))
// check if message (timestamp) is not older than 60 seconds
if (date.getTime() + 1000 * 60 < Date.now()) {
return connection.socket.send(JSON.stringify({
type: 'ERROR',
payload: 'message timestamp has expired'
}))
}
const valid = await ed.verify(
Uint8Array.from(Buffer.from(signature, "hex")),
Uint8Array.from(Buffer.from(message, "hex")),
Uint8Array.from(Buffer.from(id, "hex"))
)
if (valid) {
return
}
}
connection.socket.send(JSON.stringify({
type: 'ERROR',
payload: '64 hex IDs are only allowed with valid ed25519 signatures. Use token=ed25519|<SIG>|<MSG>'
}))
connection.socket.close()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment