2023-01-11 14:21:54 +01:00
|
|
|
const process = require('process')
|
|
|
|
const crypto = require('crypto')
|
|
|
|
const {spawn} = require('child_process')
|
2023-03-03 12:54:21 +01:00
|
|
|
const WebSocket = require('ws');
|
2023-02-24 18:08:48 +01:00
|
|
|
const fs = require('fs');
|
2023-03-06 00:06:57 +01:00
|
|
|
const parser = require('ua-parser-js');
|
|
|
|
const { uniqueNamesGenerator, animals, colors } = require('unique-names-generator');
|
|
|
|
const express = require('express');
|
|
|
|
const RateLimit = require('express-rate-limit');
|
|
|
|
const http = require('http');
|
2023-01-10 05:07:57 +01:00
|
|
|
|
2020-08-28 16:07:25 +02:00
|
|
|
// Handle SIGINT
|
|
|
|
process.on('SIGINT', () => {
|
2022-12-23 05:33:36 +01:00
|
|
|
console.info("SIGINT Received, exiting...")
|
|
|
|
process.exit(0)
|
2020-08-28 16:07:25 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
// Handle SIGTERM
|
|
|
|
process.on('SIGTERM', () => {
|
2022-12-23 05:33:36 +01:00
|
|
|
console.info("SIGTERM Received, exiting...")
|
|
|
|
process.exit(0)
|
2020-08-28 16:07:25 +02:00
|
|
|
})
|
|
|
|
|
2022-12-23 05:33:36 +01:00
|
|
|
// Handle APP ERRORS
|
|
|
|
process.on('uncaughtException', (error, origin) => {
|
|
|
|
console.log('----- Uncaught exception -----')
|
|
|
|
console.log(error)
|
|
|
|
console.log('----- Exception origin -----')
|
|
|
|
console.log(origin)
|
|
|
|
})
|
|
|
|
process.on('unhandledRejection', (reason, promise) => {
|
|
|
|
console.log('----- Unhandled Rejection at -----')
|
|
|
|
console.log(promise)
|
|
|
|
console.log('----- Reason -----')
|
|
|
|
console.log(reason)
|
|
|
|
})
|
|
|
|
|
2023-01-11 14:21:54 +01:00
|
|
|
if (process.argv.includes('--auto-restart')) {
|
|
|
|
process.on(
|
|
|
|
'uncaughtException',
|
|
|
|
() => {
|
|
|
|
process.once(
|
|
|
|
'exit',
|
|
|
|
() => spawn(
|
|
|
|
process.argv.shift(),
|
|
|
|
process.argv,
|
|
|
|
{
|
|
|
|
cwd: process.cwd(),
|
|
|
|
detached: true,
|
|
|
|
stdio: 'inherit'
|
|
|
|
}
|
|
|
|
)
|
|
|
|
);
|
|
|
|
process.exit();
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
2022-12-30 17:13:09 +01:00
|
|
|
|
2023-02-24 18:08:48 +01:00
|
|
|
const rtcConfig = process.env.RTC_CONFIG
|
2023-03-06 00:16:33 +01:00
|
|
|
? JSON.parse(fs.readFileSync(process.env.RTC_CONFIG, 'utf8'))
|
2023-02-24 18:08:48 +01:00
|
|
|
: {
|
|
|
|
"sdpSemantics": "unified-plan",
|
|
|
|
"iceServers": [
|
|
|
|
{
|
|
|
|
"urls": "stun:stun.l.google.com:19302"
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"urls": "stun:openrelay.metered.ca:80"
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"urls": "turn:openrelay.metered.ca:443",
|
|
|
|
"username": "openrelayproject",
|
|
|
|
"credential": "openrelayproject"
|
|
|
|
}
|
|
|
|
]
|
|
|
|
};
|
|
|
|
|
2022-12-23 05:33:36 +01:00
|
|
|
const app = express();
|
|
|
|
|
2023-01-11 14:21:54 +01:00
|
|
|
if (process.argv.includes('--rate-limit')) {
|
|
|
|
const limiter = RateLimit({
|
|
|
|
windowMs: 5 * 60 * 1000, // 5 minutes
|
2023-02-14 21:51:42 +01:00
|
|
|
max: 1000, // Limit each IP to 1000 requests per `window` (here, per 5 minutes)
|
2023-01-11 14:21:54 +01:00
|
|
|
message: 'Too many requests from this IP Address, please try again after 5 minutes.',
|
|
|
|
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
|
|
|
|
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
|
|
|
|
})
|
|
|
|
|
|
|
|
app.use(limiter);
|
2023-02-14 21:51:42 +01:00
|
|
|
// ensure correct client ip and not the ip of the reverse proxy is used for rate limiting on render.com
|
|
|
|
// see https://github.com/express-rate-limit/express-rate-limit#troubleshooting-proxy-issues
|
|
|
|
app.set('trust proxy', 5);
|
2023-01-11 14:21:54 +01:00
|
|
|
}
|
2022-07-14 20:08:57 +02:00
|
|
|
|
2023-02-10 20:22:36 +01:00
|
|
|
if (process.argv.includes('--include-ws-fallback')) {
|
|
|
|
app.use(express.static('public_included_ws_fallback'));
|
|
|
|
} else {
|
|
|
|
app.use(express.static('public'));
|
|
|
|
}
|
2022-12-23 05:33:36 +01:00
|
|
|
|
|
|
|
app.use(function(req, res) {
|
|
|
|
res.redirect('/');
|
|
|
|
});
|
|
|
|
|
|
|
|
app.get('/', (req, res) => {
|
|
|
|
res.sendFile('index.html');
|
|
|
|
});
|
|
|
|
|
|
|
|
const server = http.createServer(app);
|
2023-02-14 02:41:06 +01:00
|
|
|
const port = process.env.PORT || 3000;
|
|
|
|
|
|
|
|
if (process.argv.includes('--localhost-only')) {
|
|
|
|
server.listen(port, '127.0.0.1');
|
|
|
|
} else {
|
|
|
|
server.listen(port);
|
|
|
|
}
|
2022-12-23 05:33:36 +01:00
|
|
|
|
2023-01-17 10:50:28 +01:00
|
|
|
class PairDropServer {
|
2018-09-21 16:05:03 +02:00
|
|
|
|
2022-12-23 05:33:36 +01:00
|
|
|
constructor() {
|
|
|
|
this._wss = new WebSocket.Server({ server });
|
2018-09-21 16:05:03 +02:00
|
|
|
this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));
|
|
|
|
|
|
|
|
this._rooms = {};
|
2023-01-10 05:07:57 +01:00
|
|
|
this._roomSecrets = {};
|
2018-09-21 16:05:03 +02:00
|
|
|
|
2023-01-17 10:50:28 +01:00
|
|
|
console.log('PairDrop is running on port', port);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
_onConnection(peer) {
|
2019-02-18 22:47:21 +01:00
|
|
|
peer.socket.on('message', message => this._onMessage(peer, message));
|
2023-01-10 05:07:57 +01:00
|
|
|
peer.socket.onerror = e => console.error(e);
|
2018-09-21 16:05:03 +02:00
|
|
|
this._keepAlive(peer);
|
2023-02-24 18:08:48 +01:00
|
|
|
this._send(peer, {
|
|
|
|
type: 'rtc-config',
|
|
|
|
config: rtcConfig
|
|
|
|
});
|
2023-03-03 12:54:21 +01:00
|
|
|
this._joinRoom(peer);
|
2019-08-28 17:14:51 +02:00
|
|
|
|
|
|
|
// send displayName
|
2020-12-19 21:05:48 +01:00
|
|
|
this._send(peer, {
|
|
|
|
type: 'display-name',
|
|
|
|
message: {
|
|
|
|
displayName: peer.name.displayName,
|
2022-12-31 18:03:58 +01:00
|
|
|
deviceName: peer.name.deviceName,
|
2023-03-06 00:06:57 +01:00
|
|
|
peerId: peer.id,
|
|
|
|
peerIdHash: peer.id.hashCode128BitSalted()
|
2020-12-19 21:05:48 +01:00
|
|
|
}
|
|
|
|
});
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
2019-02-18 22:47:21 +01:00
|
|
|
_onMessage(sender, message) {
|
2022-12-23 00:05:00 +01:00
|
|
|
// Try to parse message
|
2019-05-29 21:35:39 +02:00
|
|
|
try {
|
|
|
|
message = JSON.parse(message);
|
|
|
|
} catch (e) {
|
|
|
|
return; // TODO: handle malformed JSON
|
|
|
|
}
|
2020-12-16 04:16:21 +01:00
|
|
|
|
2018-09-21 16:05:03 +02:00
|
|
|
switch (message.type) {
|
|
|
|
case 'disconnect':
|
2023-01-10 05:07:57 +01:00
|
|
|
this._onDisconnect(sender);
|
2018-09-21 19:51:29 +02:00
|
|
|
break;
|
2018-09-21 16:05:03 +02:00
|
|
|
case 'pong':
|
|
|
|
sender.lastBeat = Date.now();
|
2018-09-21 19:51:29 +02:00
|
|
|
break;
|
2023-01-10 05:07:57 +01:00
|
|
|
case 'room-secrets':
|
|
|
|
this._onRoomSecrets(sender, message);
|
|
|
|
break;
|
|
|
|
case 'room-secret-deleted':
|
|
|
|
this._onRoomSecretDeleted(sender, message);
|
|
|
|
break;
|
|
|
|
case 'room-secrets-cleared':
|
|
|
|
this._onRoomSecretsCleared(sender, message);
|
|
|
|
break;
|
|
|
|
case 'pair-device-initiate':
|
|
|
|
this._onPairDeviceInitiate(sender);
|
|
|
|
break;
|
|
|
|
case 'pair-device-join':
|
|
|
|
this._onPairDeviceJoin(sender, message);
|
|
|
|
break;
|
|
|
|
case 'pair-device-cancel':
|
|
|
|
this._onPairDeviceCancel(sender);
|
|
|
|
break;
|
|
|
|
case 'resend-peers':
|
|
|
|
this._notifyPeers(sender);
|
|
|
|
break;
|
|
|
|
case 'signal':
|
2023-02-10 20:22:36 +01:00
|
|
|
default:
|
|
|
|
this._signalAndRelay(sender, message);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
2023-01-10 05:07:57 +01:00
|
|
|
}
|
|
|
|
|
2023-02-10 20:22:36 +01:00
|
|
|
_signalAndRelay(sender, message) {
|
2023-01-10 05:07:57 +01:00
|
|
|
const room = message.roomType === 'ip' ? sender.ip : message.roomSecret;
|
2018-09-21 16:05:03 +02:00
|
|
|
|
|
|
|
// relay message to recipient
|
2023-01-10 05:07:57 +01:00
|
|
|
if (message.to && Peer.isValidUuid(message.to) && this._rooms[room]) {
|
2023-02-10 20:22:36 +01:00
|
|
|
const recipient = this._rooms[room][message.to];
|
2018-09-21 16:05:03 +02:00
|
|
|
delete message.to;
|
2023-02-10 20:22:36 +01:00
|
|
|
// add sender
|
|
|
|
message.sender = {
|
|
|
|
id: sender.id,
|
|
|
|
rtcSupported: sender.rtcSupported
|
|
|
|
};
|
2018-09-21 16:05:03 +02:00
|
|
|
this._send(recipient, message);
|
2023-01-10 05:07:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_onDisconnect(sender) {
|
2023-02-10 23:47:39 +01:00
|
|
|
this._leaveRoom(sender, 'ip', '', true);
|
|
|
|
this._leaveAllSecretRooms(sender, true);
|
2023-01-10 05:07:57 +01:00
|
|
|
this._removeRoomKey(sender.roomKey);
|
|
|
|
sender.roomKey = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
_onRoomSecrets(sender, message) {
|
|
|
|
const roomSecrets = message.roomSecrets.filter(roomSecret => {
|
|
|
|
return /^[\x00-\x7F]{64}$/.test(roomSecret);
|
|
|
|
})
|
|
|
|
this._joinSecretRooms(sender, roomSecrets);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onRoomSecretDeleted(sender, message) {
|
|
|
|
this._deleteSecretRoom(sender, message.roomSecret)
|
|
|
|
}
|
|
|
|
|
|
|
|
_onRoomSecretsCleared(sender, message) {
|
|
|
|
for (let i = 0; i<message.roomSecrets.length; i++) {
|
|
|
|
this._deleteSecretRoom(sender, message.roomSecrets[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_deleteSecretRoom(sender, roomSecret) {
|
|
|
|
const room = this._rooms[roomSecret];
|
|
|
|
if (room) {
|
|
|
|
for (const peerId in room) {
|
|
|
|
const peer = room[peerId];
|
|
|
|
this._leaveRoom(peer, 'secret', roomSecret);
|
|
|
|
this._send(peer, {
|
|
|
|
type: 'secret-room-deleted',
|
|
|
|
roomSecret: roomSecret,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this._notifyPeers(sender);
|
|
|
|
}
|
|
|
|
|
|
|
|
getRandomString(length) {
|
|
|
|
let string = "";
|
|
|
|
while (string.length < length) {
|
|
|
|
let arr = new Uint16Array(length);
|
|
|
|
crypto.webcrypto.getRandomValues(arr);
|
|
|
|
arr = Array.apply([], arr); /* turn into non-typed array */
|
|
|
|
arr = arr.map(function (r) {
|
|
|
|
return r % 128
|
|
|
|
})
|
|
|
|
arr = arr.filter(function (r) {
|
|
|
|
/* strip non-printables: if we transform into desirable range we have a propability bias, so I suppose we better skip this character */
|
|
|
|
return r === 45 || r >= 47 && r <= 57 || r >= 64 && r <= 90 || r >= 97 && r <= 122;
|
|
|
|
});
|
|
|
|
string += String.fromCharCode.apply(String, arr);
|
|
|
|
}
|
|
|
|
return string.substring(0, length)
|
|
|
|
}
|
|
|
|
|
|
|
|
_onPairDeviceInitiate(sender) {
|
|
|
|
let roomSecret = this.getRandomString(64);
|
|
|
|
let roomKey = this._createRoomKey(sender, roomSecret);
|
2023-01-22 17:43:54 +01:00
|
|
|
if (sender.roomKey) this._removeRoomKey(sender.roomKey);
|
2023-01-10 05:07:57 +01:00
|
|
|
sender.roomKey = roomKey;
|
|
|
|
this._send(sender, {
|
|
|
|
type: 'pair-device-initiated',
|
|
|
|
roomSecret: roomSecret,
|
|
|
|
roomKey: roomKey
|
|
|
|
});
|
|
|
|
this._joinRoom(sender, 'secret', roomSecret);
|
|
|
|
}
|
|
|
|
|
|
|
|
_onPairDeviceJoin(sender, message) {
|
|
|
|
if (sender.roomKeyRate >= 10) {
|
|
|
|
this._send(sender, { type: 'pair-device-join-key-rate-limit' });
|
2018-09-21 16:05:03 +02:00
|
|
|
return;
|
|
|
|
}
|
2023-01-10 05:07:57 +01:00
|
|
|
sender.roomKeyRate += 1;
|
|
|
|
setTimeout(_ => sender.roomKeyRate -= 1, 10000);
|
|
|
|
if (!this._roomSecrets[message.roomKey] || sender.id === this._roomSecrets[message.roomKey].creator.id) {
|
|
|
|
this._send(sender, { type: 'pair-device-join-key-invalid' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const roomSecret = this._roomSecrets[message.roomKey].roomSecret;
|
|
|
|
const creator = this._roomSecrets[message.roomKey].creator;
|
|
|
|
this._removeRoomKey(message.roomKey);
|
|
|
|
this._send(sender, {
|
|
|
|
type: 'pair-device-joined',
|
|
|
|
roomSecret: roomSecret,
|
2023-02-11 00:52:37 +01:00
|
|
|
peerId: creator.id
|
2023-01-10 05:07:57 +01:00
|
|
|
});
|
|
|
|
this._send(creator, {
|
|
|
|
type: 'pair-device-joined',
|
|
|
|
roomSecret: roomSecret,
|
2023-02-11 00:52:37 +01:00
|
|
|
peerId: sender.id
|
2023-01-10 05:07:57 +01:00
|
|
|
});
|
|
|
|
this._joinRoom(sender, 'secret', roomSecret);
|
|
|
|
this._removeRoomKey(sender.roomKey);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
_onPairDeviceCancel(sender) {
|
|
|
|
if (sender.roomKey) {
|
|
|
|
this._send(sender, {
|
|
|
|
type: 'pair-device-canceled',
|
|
|
|
roomKey: sender.roomKey,
|
|
|
|
});
|
|
|
|
this._removeRoomKey(sender.roomKey);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_createRoomKey(creator, roomSecret) {
|
|
|
|
let roomKey;
|
|
|
|
do {
|
|
|
|
// get randomInt until keyRoom not occupied
|
|
|
|
roomKey = crypto.randomInt(1000000, 1999999).toString().substring(1); // include numbers with leading 0s
|
|
|
|
} while (roomKey in this._roomSecrets)
|
|
|
|
|
|
|
|
this._roomSecrets[roomKey] = {
|
|
|
|
roomSecret: roomSecret,
|
|
|
|
creator: creator
|
|
|
|
}
|
|
|
|
|
|
|
|
return roomKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
_removeRoomKey(roomKey) {
|
|
|
|
if (roomKey in this._roomSecrets) {
|
|
|
|
this._roomSecrets[roomKey].creator.roomKey = null
|
|
|
|
delete this._roomSecrets[roomKey];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_joinRoom(peer, roomType = 'ip', roomSecret = '') {
|
|
|
|
const room = roomType === 'ip' ? peer.ip : roomSecret;
|
|
|
|
|
2023-03-03 12:54:21 +01:00
|
|
|
if (this._rooms[room] && this._rooms[room][peer.id]) {
|
|
|
|
this._leaveRoom(peer, roomType, roomSecret);
|
|
|
|
}
|
|
|
|
|
2018-09-21 16:05:03 +02:00
|
|
|
// if room doesn't exist, create it
|
2023-01-10 05:07:57 +01:00
|
|
|
if (!this._rooms[room]) {
|
|
|
|
this._rooms[room] = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
this._notifyPeers(peer, roomType, roomSecret);
|
|
|
|
|
|
|
|
// add peer to room
|
|
|
|
this._rooms[room][peer.id] = peer;
|
|
|
|
// add secret to peer
|
|
|
|
if (roomType === 'secret') {
|
|
|
|
peer.addRoomSecret(roomSecret);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-10 23:47:39 +01:00
|
|
|
_leaveRoom(peer, roomType = 'ip', roomSecret = '', disconnect = false) {
|
2023-01-10 05:07:57 +01:00
|
|
|
const room = roomType === 'ip' ? peer.ip : roomSecret;
|
|
|
|
|
|
|
|
if (!this._rooms[room] || !this._rooms[room][peer.id]) return;
|
|
|
|
this._cancelKeepAlive(this._rooms[room][peer.id]);
|
|
|
|
|
|
|
|
// delete the peer
|
|
|
|
delete this._rooms[room][peer.id];
|
|
|
|
|
2023-03-06 03:36:46 +01:00
|
|
|
if (roomType === 'ip') {
|
|
|
|
peer.socket.terminate();
|
|
|
|
}
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
//if room is empty, delete the room
|
|
|
|
if (!Object.keys(this._rooms[room]).length) {
|
|
|
|
delete this._rooms[room];
|
|
|
|
} else {
|
|
|
|
// notify all other peers
|
|
|
|
for (const otherPeerId in this._rooms[room]) {
|
|
|
|
const otherPeer = this._rooms[room][otherPeerId];
|
|
|
|
this._send(otherPeer, {
|
|
|
|
type: 'peer-left',
|
|
|
|
peerId: peer.id,
|
|
|
|
roomType: roomType,
|
2023-02-10 23:47:39 +01:00
|
|
|
roomSecret: roomSecret,
|
|
|
|
disconnect: disconnect
|
2023-01-10 05:07:57 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
//remove secret from peer
|
|
|
|
if (roomType === 'secret') {
|
|
|
|
peer.removeRoomSecret(roomSecret);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
2023-01-10 05:07:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
_notifyPeers(peer, roomType = 'ip', roomSecret = '') {
|
|
|
|
const room = roomType === 'ip' ? peer.ip : roomSecret;
|
|
|
|
if (!this._rooms[room]) return;
|
2018-09-21 16:05:03 +02:00
|
|
|
|
|
|
|
// notify all other peers
|
2023-01-10 05:07:57 +01:00
|
|
|
for (const otherPeerId in this._rooms[room]) {
|
2022-11-04 17:35:55 +01:00
|
|
|
if (otherPeerId === peer.id) continue;
|
2023-01-10 05:07:57 +01:00
|
|
|
const otherPeer = this._rooms[room][otherPeerId];
|
2018-09-21 16:05:03 +02:00
|
|
|
this._send(otherPeer, {
|
|
|
|
type: 'peer-joined',
|
2023-01-10 05:07:57 +01:00
|
|
|
peer: peer.getInfo(),
|
|
|
|
roomType: roomType,
|
|
|
|
roomSecret: roomSecret
|
2018-09-21 16:05:03 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// notify peer about the other peers
|
|
|
|
const otherPeers = [];
|
2023-01-10 05:07:57 +01:00
|
|
|
for (const otherPeerId in this._rooms[room]) {
|
2022-11-04 17:35:55 +01:00
|
|
|
if (otherPeerId === peer.id) continue;
|
2023-01-10 05:07:57 +01:00
|
|
|
otherPeers.push(this._rooms[room][otherPeerId].getInfo());
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
this._send(peer, {
|
|
|
|
type: 'peers',
|
2023-01-10 05:07:57 +01:00
|
|
|
peers: otherPeers,
|
|
|
|
roomType: roomType,
|
|
|
|
roomSecret: roomSecret
|
2018-09-21 16:05:03 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
_joinSecretRooms(peer, roomSecrets) {
|
|
|
|
for (let i=0; i<roomSecrets.length; i++) {
|
|
|
|
this._joinRoom(peer, 'secret', roomSecrets[i])
|
|
|
|
}
|
|
|
|
}
|
2018-09-21 16:05:03 +02:00
|
|
|
|
2023-02-10 23:47:39 +01:00
|
|
|
_leaveAllSecretRooms(peer, disconnect = false) {
|
2023-01-10 13:55:32 +01:00
|
|
|
for (let i=0; i<peer.roomSecrets.length; i++) {
|
2023-02-10 23:47:39 +01:00
|
|
|
this._leaveRoom(peer, 'secret', peer.roomSecrets[i], disconnect);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_send(peer, message) {
|
2020-03-24 15:23:20 +01:00
|
|
|
if (!peer) return;
|
|
|
|
if (this._wss.readyState !== this._wss.OPEN) return;
|
2018-09-21 16:05:03 +02:00
|
|
|
message = JSON.stringify(message);
|
2023-01-10 05:07:57 +01:00
|
|
|
peer.socket.send(message);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
_keepAlive(peer) {
|
2018-09-21 20:25:54 +02:00
|
|
|
this._cancelKeepAlive(peer);
|
2023-02-10 23:41:04 +01:00
|
|
|
let timeout = 500;
|
2018-09-21 20:09:49 +02:00
|
|
|
if (!peer.lastBeat) {
|
|
|
|
peer.lastBeat = Date.now();
|
|
|
|
}
|
2018-09-21 16:05:03 +02:00
|
|
|
if (Date.now() - peer.lastBeat > 2 * timeout) {
|
|
|
|
this._leaveRoom(peer);
|
2023-01-10 05:07:57 +01:00
|
|
|
this._leaveAllSecretRooms(peer);
|
2018-09-21 16:05:03 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-09-21 20:09:49 +02:00
|
|
|
this._send(peer, { type: 'ping' });
|
|
|
|
|
2018-09-21 16:05:03 +02:00
|
|
|
peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
|
|
|
|
}
|
|
|
|
|
|
|
|
_cancelKeepAlive(peer) {
|
2018-09-21 20:34:49 +02:00
|
|
|
if (peer && peer.timerId) {
|
2018-09-21 16:05:03 +02:00
|
|
|
clearTimeout(peer.timerId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Peer {
|
|
|
|
|
|
|
|
constructor(socket, request) {
|
|
|
|
// set socket
|
|
|
|
this.socket = socket;
|
|
|
|
|
|
|
|
// set remote ip
|
2018-10-09 15:45:07 +02:00
|
|
|
this._setIP(request);
|
2018-09-21 16:05:03 +02:00
|
|
|
|
|
|
|
// set peer id
|
2023-03-06 00:06:57 +01:00
|
|
|
this._setPeerId(request)
|
2022-12-30 17:49:14 +01:00
|
|
|
|
2018-09-21 16:05:03 +02:00
|
|
|
// is WebRTC supported ?
|
|
|
|
this.rtcSupported = request.url.indexOf('webrtc') > -1;
|
2022-12-30 17:49:14 +01:00
|
|
|
|
2022-12-23 00:05:00 +01:00
|
|
|
// set name
|
2018-10-09 15:45:07 +02:00
|
|
|
this._setName(request);
|
2022-12-30 17:49:14 +01:00
|
|
|
|
2018-09-21 16:05:03 +02:00
|
|
|
// for keepalive
|
|
|
|
this.timerId = 0;
|
|
|
|
this.lastBeat = Date.now();
|
2023-01-10 05:07:57 +01:00
|
|
|
|
|
|
|
this.roomSecrets = [];
|
|
|
|
this.roomKey = null;
|
|
|
|
this.roomKeyRate = 0;
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
2018-10-09 15:45:07 +02:00
|
|
|
_setIP(request) {
|
Check for CF-Connecting-IP and decreased timeout
When hosting Snapdrop behind Cloudflare, X-Forwarded-For is useless. Furthermore, I'm hosting my installation behind another internal proxy, so, in the end, X-Forwarder-For is set to the internal proxy's IP for all the peer, which can see each other regardless being on different networks. To fix this I made _setIP check if the header "cf-connecting-ip" exists, then sets the IP accordingly.
Lastly, when a peer changes network (e.g. a phone switches from wifi to mobile data), the function _leaveRoom is not called and the peer stays visible to others connected to the same room for a whole minute: I adjusted the timeout to what I think is a more reasonable value (500ms, so _leaveRoom is called after 1s).
2022-11-24 13:51:39 +01:00
|
|
|
if (request.headers['cf-connecting-ip']) {
|
|
|
|
this.ip = request.headers['cf-connecting-ip'].split(/\s*,\s*/)[0];
|
|
|
|
} else if (request.headers['x-forwarded-for']) {
|
2018-10-09 15:45:07 +02:00
|
|
|
this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
|
|
|
|
} else {
|
|
|
|
this.ip = request.connection.remoteAddress;
|
|
|
|
}
|
2023-02-04 17:34:20 +01:00
|
|
|
|
|
|
|
// remove the prefix used for IPv4-translated addresses
|
|
|
|
if (this.ip.substring(0,7) === "::ffff:")
|
|
|
|
this.ip = this.ip.substring(7);
|
|
|
|
|
2019-02-18 22:52:05 +01:00
|
|
|
// IPv4 and IPv6 use different values to refer to localhost
|
2022-12-23 02:38:56 +01:00
|
|
|
// put all peers on the same network as the server into the same room as well
|
2023-02-04 17:34:20 +01:00
|
|
|
if (this.ip === '::1' || this.ipIsPrivate(this.ip)) {
|
2022-12-22 01:05:49 +01:00
|
|
|
this.ip = '127.0.0.1';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ipIsPrivate(ip) {
|
2023-02-04 17:34:20 +01:00
|
|
|
// if ip is IPv4
|
|
|
|
if (!ip.includes(":")) {
|
2022-12-23 02:38:56 +01:00
|
|
|
// 10.0.0.0 - 10.255.255.255 || 172.16.0.0 - 172.31.255.255 || 192.168.0.0 - 192.168.255.255
|
|
|
|
return /^(10)\.(.*)\.(.*)\.(.*)$/.test(ip) || /^(172)\.(1[6-9]|2[0-9]|3[0-1])\.(.*)\.(.*)$/.test(ip) || /^(192)\.(168)\.(.*)\.(.*)$/.test(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// else: ip is IPv6
|
|
|
|
const firstWord = ip.split(":").find(el => !!el); //get first not empty word
|
|
|
|
|
|
|
|
// The original IPv6 Site Local addresses (fec0::/10) are deprecated. Range: fec0 - feff
|
|
|
|
if (/^fe[c-f][0-f]$/.test(firstWord))
|
|
|
|
return true;
|
|
|
|
|
2023-02-04 17:34:20 +01:00
|
|
|
// These days Unique Local Addresses (ULA) are used in place of Site Local.
|
2022-12-23 02:38:56 +01:00
|
|
|
// Range: fc00 - fcff
|
|
|
|
else if (/^fc[0-f]{2}$/.test(firstWord))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Range: fd00 - fcff
|
|
|
|
else if (/^fd[0-f]{2}$/.test(firstWord))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Link local addresses (prefixed with fe80) are not routable
|
|
|
|
else if (firstWord === "fe80")
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Discard Prefix
|
|
|
|
else if (firstWord === "100")
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Any other IP address is not Unique Local Address (ULA)
|
|
|
|
return false;
|
2018-10-09 15:45:07 +02:00
|
|
|
}
|
|
|
|
|
2023-03-06 00:06:57 +01:00
|
|
|
_setPeerId(request) {
|
|
|
|
const searchParams = new URL(request.url, "http://server").searchParams;
|
|
|
|
let peerId = searchParams.get("peer_id");
|
|
|
|
let peerIdHash = searchParams.get("peer_id_hash");
|
|
|
|
if (peerId && Peer.isValidUuid(peerId) && this.isPeerIdHashValid(peerId, peerIdHash)) {
|
|
|
|
this.id = peerId;
|
|
|
|
} else {
|
|
|
|
this.id = crypto.randomUUID();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-09 15:45:07 +02:00
|
|
|
toString() {
|
|
|
|
return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
|
|
|
|
}
|
|
|
|
|
|
|
|
_setName(req) {
|
2020-12-16 04:16:21 +01:00
|
|
|
let ua = parser(req.headers['user-agent']);
|
|
|
|
|
|
|
|
|
2021-03-10 15:25:03 +01:00
|
|
|
let deviceName = '';
|
2022-12-23 00:05:00 +01:00
|
|
|
|
2021-03-10 15:25:03 +01:00
|
|
|
if (ua.os && ua.os.name) {
|
|
|
|
deviceName = ua.os.name.replace('Mac OS', 'Mac') + ' ';
|
|
|
|
}
|
2022-12-23 00:05:00 +01:00
|
|
|
|
2021-03-10 15:49:45 +01:00
|
|
|
if (ua.device.model) {
|
|
|
|
deviceName += ua.device.model;
|
2020-12-16 04:16:21 +01:00
|
|
|
} else {
|
2021-03-10 15:49:45 +01:00
|
|
|
deviceName += ua.browser.name;
|
2020-12-16 04:16:21 +01:00
|
|
|
}
|
|
|
|
|
2021-03-10 15:49:45 +01:00
|
|
|
if(!deviceName)
|
|
|
|
deviceName = 'Unknown Device';
|
|
|
|
|
2020-12-19 21:05:48 +01:00
|
|
|
const displayName = uniqueNamesGenerator({
|
|
|
|
length: 2,
|
|
|
|
separator: ' ',
|
|
|
|
dictionaries: [colors, animals],
|
|
|
|
style: 'capital',
|
|
|
|
seed: this.id.hashCode()
|
|
|
|
})
|
|
|
|
|
2018-10-09 15:45:07 +02:00
|
|
|
this.name = {
|
|
|
|
model: ua.device.model,
|
|
|
|
os: ua.os.name,
|
|
|
|
browser: ua.browser.name,
|
2019-08-28 16:46:04 +02:00
|
|
|
type: ua.device.type,
|
2020-12-19 21:05:48 +01:00
|
|
|
deviceName,
|
|
|
|
displayName
|
2018-10-09 15:45:07 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
getInfo() {
|
|
|
|
return {
|
|
|
|
id: this.id,
|
|
|
|
name: this.name,
|
|
|
|
rtcSupported: this.rtcSupported
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
static isValidUuid(uuid) {
|
|
|
|
return /^([0-9]|[a-f]){8}-(([0-9]|[a-f]){4}-){3}([0-9]|[a-f]){12}$/.test(uuid);
|
|
|
|
}
|
|
|
|
|
2023-03-06 00:06:57 +01:00
|
|
|
isPeerIdHashValid(peerId, peerIdHash) {
|
|
|
|
return peerIdHash === peerId.hashCode128BitSalted();
|
|
|
|
}
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
addRoomSecret(roomSecret) {
|
2023-01-10 13:55:32 +01:00
|
|
|
if (!(roomSecret in this.roomSecrets)) {
|
2023-01-10 05:07:57 +01:00
|
|
|
this.roomSecrets.push(roomSecret);
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
2023-01-10 05:07:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
removeRoomSecret(roomSecret) {
|
|
|
|
if (roomSecret in this.roomSecrets) {
|
|
|
|
delete this.roomSecrets[roomSecret];
|
|
|
|
}
|
|
|
|
}
|
2018-09-21 16:05:03 +02:00
|
|
|
}
|
|
|
|
|
2020-12-19 21:05:48 +01:00
|
|
|
Object.defineProperty(String.prototype, 'hashCode', {
|
2022-12-23 05:33:36 +01:00
|
|
|
value: function() {
|
2023-03-06 00:06:57 +01:00
|
|
|
return cyrb53(this);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Object.defineProperty(String.prototype, 'hashCode128BitSalted', {
|
|
|
|
value: function() {
|
|
|
|
return hasher.hashCode128BitSalted(this);
|
2020-12-19 21:05:48 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-03-06 00:06:57 +01:00
|
|
|
const hasher = (() => {
|
|
|
|
let seeds;
|
|
|
|
return {
|
|
|
|
hashCode128BitSalted(str) {
|
|
|
|
if (!seeds) {
|
|
|
|
// seeds are created on first call to salt hash.
|
|
|
|
seeds = [4];
|
|
|
|
for (let i=0; i<4; i++) {
|
|
|
|
const randomBuffer = new Uint32Array(1);
|
|
|
|
crypto.webcrypto.getRandomValues(randomBuffer);
|
|
|
|
seeds[i] = randomBuffer[0];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let hashCode = "";
|
|
|
|
for (let i=0; i<4; i++) {
|
|
|
|
hashCode += cyrb53(str, seeds[i]);
|
|
|
|
}
|
|
|
|
return hashCode;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
})()
|
|
|
|
|
|
|
|
/*
|
|
|
|
cyrb53 (c) 2018 bryc (github.com/bryc)
|
|
|
|
A fast and simple hash function with decent collision resistance.
|
|
|
|
Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
|
|
|
|
Public domain. Attribution appreciated.
|
|
|
|
*/
|
|
|
|
const cyrb53 = function(str, seed = 0) {
|
|
|
|
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
|
|
|
|
for (let i = 0, ch; i < str.length; i++) {
|
|
|
|
ch = str.charCodeAt(i);
|
|
|
|
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
|
|
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
|
|
}
|
|
|
|
h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909);
|
|
|
|
h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909);
|
|
|
|
return 4294967296 * (2097151 & h2) + (h1>>>0);
|
|
|
|
};
|
|
|
|
|
2023-01-17 10:50:28 +01:00
|
|
|
new PairDropServer();
|