Skip to content

Commit

Permalink
fix: polishing signaling server communication with js and python clie…
Browse files Browse the repository at this point in the history
…nts; fix room membership api
  • Loading branch information
ivelin committed Jan 9, 2020
1 parent 65fa876 commit 3fe3f84
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 41 deletions.
4 changes: 2 additions & 2 deletions src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ module.exports = ({ config, realm, messageHandler }) => {
});

app.use('/:key', require('./v1/public')({ config, realm }));
app.use('/:key/:id/:token', authMiddleware, jsonParser, require('./v1/calls')({ realm, messageHandler }));
app.use('/:key/:id/:token', authMiddleware , jsonParser, require('./v1/calls')({ realm, messageHandler }));
// console.log('realm', realm)
app.use('/:key/:id/:token/room', authMiddleware, jsonParser, require('./v1/rooms')({ realm, messageHandler }));
app.use('/:key/:id/:token/room', authMiddleware, jsonParser, require('./v1/rooms')({ realm }));

return app;
};
14 changes: 14 additions & 0 deletions src/api/middleware/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,35 @@ const { Errors } = require('../../../enums');
module.exports = ({ config, realm }) => (req, res, next) => {
const { id, token, key } = req.params;

console.log('middleware: id %s , token %s, key %s',
id, token, key)

console.log('middleware: req.originalUrl %s',
req.originalUrl)

console.log('middleware: req.params %s',
req.params)

if (key !== config.key) {
console.log('Invalid key %s in request %s', key, req.originalUrl)
return res.status(401).send(Errors.INVALID_KEY);
}

if (!id) {
console.log('Invalid client id %s in request %s', id, req.originalUrl)
return res.sendStatus(401);
}

const client = realm.getClientById(id);

if (!client) {
console.log('Client id %s not found in server realm. Request url: %s',
id, req.originalUrl)
return res.sendStatus(401);
}

if (client.getToken() && token !== client.getToken()) {
console.log('Invalid token %s for client id %s', token, id)
return res.status(401).send(Errors.INVALID_TOKEN);
}

Expand Down
15 changes: 13 additions & 2 deletions src/api/v1/calls/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
const express = require('express');

module.exports = ({ realm, messageHandler }) => {
const app = express.Router();
const app = express.Router({ mergeParams: true });

console.log('calls: ...');

const handle = (req, res, next) => {
const { id } = req.params;
const { key, id, token } = req.params;

console.log('calls: Client key %s, id %s, token %s',
key, id, token);

console.error('calls: req.originalUrl %s',
req.originalUrl);

console.log('calls: req.params %s',
req.params);

if (!id) return next();

Expand Down
73 changes: 39 additions & 34 deletions src/api/v1/rooms/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ const compression = require('compression');
const crypto = require('crypto');
const requestIp = require('request-ip');

module.exports = ({ realm }) => {
// console.log('realm', realm)
// const app = new ExpressRoom(realm);

function ExpressRoom(realm) {
const app = express.Router();
const app = express.Router({ mergeParams: true });

// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
Expand All @@ -36,12 +38,12 @@ function ExpressRoom(realm) {
// app.use(myMiddleware);

function getClientPublicIp(req) {
console.log('Request', req)
console.log('Request headers', req.headers)
console.log('Request cf-connecting-ip', req.headers['cf-connecting-ip'])
console.log('Request ip', req.ip)
// console.log('Request', req)
// console.log('Request headers', req.headers)
// console.log('Request cf-connecting-ip', req.headers['cf-connecting-ip'])
console.log('rooms: getClientPublicIp Http Request ip', req.ip)
let ip = requestIp.getClientIp(req);
console.log('Final client public ip resolution', ip)
console.log('rooms: Final client public ip resolution', ip)
if (ip) {
return ip
} else {
Expand All @@ -54,71 +56,74 @@ function ExpressRoom(realm) {
}

/**
Get unique room name based on client's public IP address.
Get unique room ID based on client's public IP address.
Presumably devices located in the same physical room share the same
trusted local WiFi/LAN and hence same public IP.
Clients can find each other on the LAN once they exchange
WebRTC SDP offers via the shared pnp room.
Room name is generated such that all clients with
Room ID is generated such that all clients with
the same public IP will find each other in the same room.
Clients that do not share the same public IP should not be unable to
accidentally or intentionally join each other's rooms.
*/
app.get('/id', async (req, res) => {
app.get('/id', async (req, res, next) => {
const { id } = req.params;

console.log('rooms: Client id %s requested room id. Request url: %s, params %s',
id, req.originalUrl, req.params)

if (!id) return next();

const ip = getClientPublicIp(req)
console.log('Calculating room name for public IP', ip)
console.log('rooms: Calculating room name for public IP', ip)
const roomId = crypto
.createHmac('sha1', realm.getSecret())
.update(ip)
.digest('hex');
console.log('Calculated room name %s for public IP %s', roomId, ip)
res.json({ roomId });
console.log('rooms: Calculated room name %s for public IP %s', roomId, ip)
return res.send({ roomId });
});

/**
Get a list of all member peers in the same room (same room key).
Requires room key.
*/
app.get('/:roomId/members', (req, res) => {
const { roomId } = req.params;

app.get('/:roomId/members', (req, res, next) => {
const { id, roomId } = req.params;
console.log('rooms: Client id %s obtaining room id %s members.', id, roomId)
if (!id || !roomId) return next();
const clientsIds = realm.getRoomMembers(roomId);

console.log('rooms: Room id %s members: %s', roomId, clientsIds)
return res.send(clientsIds);
});

/**
Join a peer room.
*/
app.post('/:roomId/join', (req, res) => {
const { roomId } = req.params;

const clientsIds = realm.joinRoom(roomId);

return res.send(clientsIds);
app.post('/:roomId/join', (req, res, next) => {
const { id, roomId } = req.params;
console.log('rooms: Client id %s joining room id %s.', id, roomId)
if (!id || !roomId) return next();
const clientsIds = realm.joinRoom(id, roomId);
console.log('rooms: Room id %s members after client id %s joined: %s.',
roomId, id, clientsIds)
return res.send({ clientsIds });
});

/**
Get a list of all member peers in the same room.
*/
app.post('/:roomId/leave', (req, res) => {
app.post('/:roomId/leave', (req, res, next) => {
const { id, roomId } = req.params;

console.log('rooms: Client id %s leaving room id %s.', id, roomId)
if (!id || !roomId) return next();
const wasInRoom = realm.leaveRoom(id, roomId);

return res.send(wasInRoom);
return res.send({ wasInRoom });
});

return app;

}


module.exports = ({ realm }) => {
// console.log('realm', realm)
const app = new ExpressRoom(realm);
return app
};
3 changes: 2 additions & 1 deletion src/models/pnpRealm.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ class PnpRealm extends Realm {
}
room.add(clientId)
const roomMembers = [...room]
console.log('joined room with members', roomId, roomMembers)
console.log('Client id %s joined room %s with members %s',
clientId, roomId, roomMembers)
return roomMembers
}

Expand Down
2 changes: 1 addition & 1 deletion src/services/checkRoomMembers/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
Periodically clean up room membership.
*/
const DEFAULT_CHECK_INTERVAL = 300;
const DEFAULT_CHECK_INTERVAL = 30000;

module.exports = ({ realm, checkInterval = DEFAULT_CHECK_INTERVAL }) => {
/**
Expand Down
17 changes: 16 additions & 1 deletion src/services/webSocketServer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,28 @@ class WebSocketServer extends EventEmitter {
this._wss.on('connection', (socket, req) => this._onSocketConnection(socket, req));
this._wss.on('error', (error) => this._onSocketError(error));
}

_onSocketConnection(socket, req) {
const { query = {} } = url.parse(req.url, true);

const { id, token, key } = query;

if (!id || !token || !key) {
console.log('websockets: Invalid websocket parameters, id %s, token %s, key %s',
id, token, key)
return this._sendErrorAndClose(socket, Errors.INVALID_WS_PARAMETERS);
}

if (key !== this.config.key) {
console.log('websockets: Invalid key: %s')
return this._sendErrorAndClose(socket, Errors.INVALID_KEY);
}

const client = this.realm.getClientById(id);

if (client) {
if (token !== client.getToken()) {
console.log('websockets: ID %s is taken. Invalid token: %s', id, token)
// ID-taken, invalid token
socket.send(JSON.stringify({
type: MessageType.ID_TAKEN,
Expand Down Expand Up @@ -69,6 +73,8 @@ class WebSocketServer extends EventEmitter {
this.realm.setClient(newClient, id);
socket.send(JSON.stringify({ type: MessageType.OPEN }));

console.log('websockets: Client id %s registered.', id)

this._configureWS(socket, newClient);
}

Expand All @@ -79,6 +85,10 @@ class WebSocketServer extends EventEmitter {
socket.on('close', () => {
if (client.socket === socket) {
this.realm.removeClientById(client.getId());

console.log('websockets: Client id %s disconected.',
client.getId());

this.emit('close', client);
}
});
Expand All @@ -90,12 +100,17 @@ class WebSocketServer extends EventEmitter {

message.src = client.getId();

console.log('websockets: Client id %s sent a message %s',
client.getId(), message);

this.emit('message', client, message);
} catch (e) {
this.emit('error', e);
}
});

console.log('websockets: Client id %s connected to signaling server.',
client.getId());
this.emit('connection', client);
}

Expand Down

0 comments on commit 3fe3f84

Please sign in to comment.