From 30ca47c2d8c176e48f679d61bd409b406a53fc35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Tue, 9 Jun 2020 15:51:14 +0200 Subject: [PATCH 1/4] Enabling stricter lint: forbidding usage of any See #168 --- back/.eslintrc.json | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/back/.eslintrc.json b/back/.eslintrc.json index 0cee14a3..3aab37d9 100644 --- a/back/.eslintrc.json +++ b/back/.eslintrc.json @@ -7,7 +7,8 @@ }, "extends": [ "eslint:recommended", - "plugin:@typescript-eslint/eslint-recommended" + "plugin:@typescript-eslint/eslint-recommended", + "plugin:@typescript-eslint/recommended-requiring-type-checking" ], "globals": { "Atomics": "readonly", @@ -16,12 +17,14 @@ "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 2018, - "sourceType": "module" + "sourceType": "module", + "project": "./tsconfig.json" }, "plugins": [ "@typescript-eslint" ], "rules": { - "no-unused-vars": "off" + "no-unused-vars": "off", + "@typescript-eslint/no-explicit-any": "error" } -} \ No newline at end of file +} From ac0b7a7361d31f61db6d5cb37934dd9fb2af6692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Tue, 9 Jun 2020 15:54:54 +0200 Subject: [PATCH 2/4] Turning let into const where applicable --- back/src/Controller/AuthenticateController.ts | 6 +- back/src/Controller/IoSocketController.ts | 64 +++++++++---------- back/src/Model/Group.ts | 2 +- back/src/Model/World.ts | 18 +++--- back/tests/WorldTest.ts | 18 +++--- 5 files changed, 54 insertions(+), 54 deletions(-) diff --git a/back/src/Controller/AuthenticateController.ts b/back/src/Controller/AuthenticateController.ts index 4e617509..45e195fc 100644 --- a/back/src/Controller/AuthenticateController.ts +++ b/back/src/Controller/AuthenticateController.ts @@ -16,15 +16,15 @@ export class AuthenticateController { login(){ // For now, let's completely forget the /login route. this.App.post("/login", (req: Request, res: Response) => { - let param = req.body; + const param = req.body; /*if(!param.name){ return res.status(BAD_REQUEST).send({ message: "email parameter is empty" }); }*/ //TODO check user email for The Coding Machine game - let userId = uuid(); - let token = Jwt.sign({name: param.name, userId: userId}, SECRET_KEY, {expiresIn: '24h'}); + const userId = uuid(); + const token = Jwt.sign({name: param.name, userId: userId}, SECRET_KEY, {expiresIn: '24h'}); return res.status(OK).send({ token: token, mapUrlStart: URL_ROOM_STARTED, diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index c8006ce9..646464e1 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -79,9 +79,9 @@ export class IoSocketController { * @param token */ searchClientByToken(token: string): ExSocketInterface | null { - let clients: Array = Object.values(this.Io.sockets.sockets); + const clients: Array = Object.values(this.Io.sockets.sockets); for (let i = 0; i < clients.length; i++) { - let client: ExSocketInterface = clients[i]; + const client: ExSocketInterface = clients[i]; if (client.token !== token) { continue } @@ -93,9 +93,9 @@ export class IoSocketController { private sendUpdateGroupEvent(group: Group): void { // Let's get the room of the group. To do this, let's get anyone in the group and find its room. // Note: this is suboptimal - let userId = group.getUsers()[0].id; - let client: ExSocketInterface = this.searchClientByIdOrFail(userId); - let roomId = client.roomId; + const userId = group.getUsers()[0].id; + const client: ExSocketInterface = this.searchClientByIdOrFail(userId); + const roomId = client.roomId; this.Io.in(roomId).emit(SockerIoEvent.GROUP_CREATE_UPDATE, { position: group.getPosition(), groupId: group.getId() @@ -104,19 +104,19 @@ export class IoSocketController { private sendDeleteGroupEvent(uuid: string, lastUser: UserInterface): void { // Let's get the room of the group. To do this, let's get anyone in the group and find its room. - let userId = lastUser.id; - let client: ExSocketInterface = this.searchClientByIdOrFail(userId); - let roomId = client.roomId; + const userId = lastUser.id; + const client: ExSocketInterface = this.searchClientByIdOrFail(userId); + const roomId = client.roomId; this.Io.in(roomId).emit(SockerIoEvent.GROUP_DELETE, uuid); } ioConnection() { this.Io.on(SockerIoEvent.CONNECTION, (socket: Socket) => { - let client : ExSocketInterface = socket as ExSocketInterface; + const client : ExSocketInterface = socket as ExSocketInterface; this.sockets.set(client.userId, client); // Let's log server load when a user joins - let srvSockets = this.Io.sockets.sockets; + const srvSockets = this.Io.sockets.sockets; this.nbClientsGauge.inc({ host: os.hostname() }); console.log(new Date().toISOString() + ' A user joined (', Object.keys(srvSockets).length, ' connected users)'); si.currentLoad().then(data => console.log(' Current load: ', data.avgload)); @@ -133,19 +133,19 @@ export class IoSocketController { */ socket.on(SockerIoEvent.JOIN_ROOM, (message: any, answerFn): void => { try { - let roomId = message.roomId; + const roomId = message.roomId; if (typeof(roomId) !== 'string') { socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}); return; } - let position = this.hydratePositionReceive(message.position); + const position = this.hydratePositionReceive(message.position); if (position instanceof Error) { socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); return; } - let Client = (socket as ExSocketInterface); + const Client = (socket as ExSocketInterface); if (Client.roomId === roomId) { return; @@ -155,18 +155,18 @@ export class IoSocketController { this.leaveRoom(Client); //join new previous room - let world = this.joinRoom(Client, roomId, position); + const world = this.joinRoom(Client, roomId, position); //add function to refresh position user in real time. //this.refreshUserPosition(Client); - let messageUserJoined = new MessageUserJoined(Client.userId, Client.name, Client.character, Client.position); + const messageUserJoined = new MessageUserJoined(Client.userId, Client.name, Client.character, Client.position); socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserJoined); // The answer shall contain the list of all users of the room with their positions: - let listOfUsers = Array.from(world.getUsers(), ([key, user]) => { - let player = this.searchClientByIdOrFail(user.id); + const listOfUsers = Array.from(world.getUsers(), ([key, user]) => { + const player = this.searchClientByIdOrFail(user.id); return new MessageUserPosition(user.id, player.name, player.character, player.position); }); answerFn(listOfUsers); @@ -178,19 +178,19 @@ export class IoSocketController { socket.on(SockerIoEvent.USER_POSITION, (message: any): void => { try { - let position = this.hydratePositionReceive(message); + const position = this.hydratePositionReceive(message); if (position instanceof Error) { socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); return; } - let Client = (socket as ExSocketInterface); + const Client = (socket as ExSocketInterface); // sending to all clients in room except sender Client.position = position; // update position in the world - let world = this.Worlds.get(Client.roomId); + const world = this.Worlds.get(Client.roomId); if (!world) { console.error("Could not find world with id '", Client.roomId, "'"); return; @@ -206,7 +206,7 @@ export class IoSocketController { socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => { //send only at user - let client = this.sockets.get(data.receiverId); + const client = this.sockets.get(data.receiverId); if (client === undefined) { console.warn("While exchanging a WebRTC signal: client with id ", data.receiverId, " does not exist. This might be a race condition."); return; @@ -216,7 +216,7 @@ export class IoSocketController { socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => { //send only at user - let client = this.sockets.get(data.receiverId); + const client = this.sockets.get(data.receiverId); if (client === undefined) { console.warn("While exchanging a WebRTC offer: client with id ", data.receiverId, " does not exist. This might be a race condition."); return; @@ -225,7 +225,7 @@ export class IoSocketController { }); socket.on(SockerIoEvent.DISCONNECT, () => { - let Client = (socket as ExSocketInterface); + const Client = (socket as ExSocketInterface); try { //leave room this.leaveRoom(Client); @@ -245,7 +245,7 @@ export class IoSocketController { this.sockets.delete(Client.userId); // Let's log server load when a user leaves - let srvSockets = this.Io.sockets.sockets; + const srvSockets = this.Io.sockets.sockets; this.nbClientsGauge.dec({ host: os.hostname() }); console.log('A user left (', Object.keys(srvSockets).length, ' connected users)'); si.currentLoad().then(data => console.log('Current load: ', data.avgload)); @@ -255,7 +255,7 @@ export class IoSocketController { // Let's send the user id to the user socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: SetPlayerDetailsMessage, answerFn) => { - let Client = (socket as ExSocketInterface); + const Client = (socket as ExSocketInterface); Client.name = playerDetails.name; Client.character = playerDetails.character; answerFn(Client.userId); @@ -264,7 +264,7 @@ export class IoSocketController { } searchClientByIdOrFail(userId: string): ExSocketInterface { - let client: ExSocketInterface|undefined = this.sockets.get(userId); + const client: ExSocketInterface|undefined = this.sockets.get(userId); if (client === undefined) { throw new Error("Could not find user with id " + userId); } @@ -277,7 +277,7 @@ export class IoSocketController { Client.to(Client.roomId).emit(SockerIoEvent.USER_LEFT, Client.userId); //user leave previous world - let world : World|undefined = this.Worlds.get(Client.roomId); + const world : World|undefined = this.Worlds.get(Client.roomId); if(world){ world.leave(Client); } @@ -337,13 +337,13 @@ export class IoSocketController { if (this.Io.sockets.adapter.rooms[roomId].length < 2 /*|| this.Io.sockets.adapter.rooms[roomId].length >= 4*/) { return; } - let clients: Array = (Object.values(this.Io.sockets.sockets) as Array) + const clients: Array = (Object.values(this.Io.sockets.sockets) as Array) .filter((client: ExSocketInterface) => client.webRtcRoomId && client.webRtcRoomId === roomId); //send start at one client to initialise offer webrtc //send all users in room to create PeerConnection in front clients.forEach((client: ExSocketInterface, index: number) => { - let clientsId = clients.reduce((tabs: Array, clientId: ExSocketInterface, indexClientId: number) => { + const clientsId = clients.reduce((tabs: Array, clientId: ExSocketInterface, indexClientId: number) => { if (!clientId.userId || clientId.userId === client.userId) { return tabs; } @@ -395,13 +395,13 @@ export class IoSocketController { if (Client === undefined) { return; }*/ - let Client = this.searchClientByIdOrFail(userId); + const Client = this.searchClientByIdOrFail(userId); this.joinWebRtcRoom(Client, group.getId()); } //disconnect user disConnectedUser(userId: string, group: Group) { - let Client = this.searchClientByIdOrFail(userId); + const Client = this.searchClientByIdOrFail(userId); Client.to(group.getId()).emit(SockerIoEvent.WEBRTC_DISCONNECT, { userId: userId }); @@ -411,7 +411,7 @@ export class IoSocketController { // However! In the rare case where the WebRTC connection is not yet established, if we close the connection on one of the player, // the other player will try connecting until a timeout happens (during this time, the connection icon will be displayed for nothing). // So we also send the disconnect event to the other player. - for (let user of group.getUsers()) { + for (const user of group.getUsers()) { Client.emit(SockerIoEvent.WEBRTC_DISCONNECT, { userId: user.id }); diff --git a/back/src/Model/Group.ts b/back/src/Model/Group.ts index d71a0585..ed09b0cd 100644 --- a/back/src/Model/Group.ts +++ b/back/src/Model/Group.ts @@ -68,7 +68,7 @@ export class Group { isPartOfGroup(user: UserInterface): boolean { - return this.users.indexOf(user) !== -1; + return this.users.includes(user); } /*removeFromGroup(users: UserInterface[]): void diff --git a/back/src/Model/World.ts b/back/src/Model/World.ts index 5f70a32f..51129857 100644 --- a/back/src/Model/World.ts +++ b/back/src/Model/World.ts @@ -62,7 +62,7 @@ export class World { } public leave(user : Identificable){ - let userObj = this.users.get(user.userId); + const userObj = this.users.get(user.userId); if (userObj === undefined) { console.warn('User ', user.userId, 'does not belong to world! It should!'); } @@ -73,7 +73,7 @@ export class World { } public updatePosition(socket : Identificable, userPosition: PointInterface): void { - let user = this.users.get(socket.userId); + const user = this.users.get(socket.userId); if(typeof user === 'undefined') { return; } @@ -83,15 +83,15 @@ export class World { if (typeof user.group === 'undefined') { // If the user is not part of a group: // should he join a group? - let closestItem: UserInterface|Group|null = this.searchClosestAvailableUserOrGroup(user); + const closestItem: UserInterface|Group|null = this.searchClosestAvailableUserOrGroup(user); if (closestItem !== null) { if (closestItem instanceof Group) { // Let's join the group! closestItem.join(user); } else { - let closestUser : UserInterface = closestItem; - let group: Group = new Group([ + const closestUser : UserInterface = closestItem; + const group: Group = new Group([ user, closestUser ], this.connectCallback, this.disconnectCallback); @@ -102,7 +102,7 @@ export class World { } else { // If the user is part of a group: // should he leave the group? - let distance = World.computeDistanceBetweenPositions(user.position, user.group.getPosition()); + const distance = World.computeDistanceBetweenPositions(user.position, user.group.getPosition()); if (distance > this.groupRadius) { this.leaveGroup(user); } @@ -120,7 +120,7 @@ export class World { * @param user */ private leaveGroup(user: UserInterface): void { - let group = user.group; + const group = user.group; if (typeof group === 'undefined') { throw new Error("The user is part of no group"); } @@ -158,7 +158,7 @@ export class World { return; } - let distance = World.computeDistance(user, currentUser); // compute distance between peers. + const distance = World.computeDistance(user, currentUser); // compute distance between peers. if(distance <= minimumDistanceFound && distance <= this.minDistance) { minimumDistanceFound = distance; @@ -204,7 +204,7 @@ export class World { if (group.isFull()) { return; } - let distance = World.computeDistanceBetweenPositions(user.position, group.getPosition()); + const distance = World.computeDistanceBetweenPositions(user.position, group.getPosition()); if(distance <= minimumDistanceFound && distance <= this.groupRadius) { minimumDistanceFound = distance; matchingItem = group; diff --git a/back/tests/WorldTest.ts b/back/tests/WorldTest.ts index 88c87430..c436eed7 100644 --- a/back/tests/WorldTest.ts +++ b/back/tests/WorldTest.ts @@ -6,14 +6,14 @@ import { Group } from "../src/Model/Group"; describe("World", () => { it("should connect user1 and user2", () => { let connectCalledNumber: number = 0; - let connect: ConnectCallback = (user: string, group: Group): void => { + const connect: ConnectCallback = (user: string, group: Group): void => { connectCalledNumber++; } - let disconnect: DisconnectCallback = (user: string, group: Group): void => { + const disconnect: DisconnectCallback = (user: string, group: Group): void => { } - let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); + const world = new World(connect, disconnect, 160, 160, () => {}, () => {}); world.join({ userId: "foo" }, new Point(100, 100)); @@ -33,14 +33,14 @@ describe("World", () => { it("should connect 3 users", () => { let connectCalled: boolean = false; - let connect: ConnectCallback = (user: string, group: Group): void => { + const connect: ConnectCallback = (user: string, group: Group): void => { connectCalled = true; } - let disconnect: DisconnectCallback = (user: string, group: Group): void => { + const disconnect: DisconnectCallback = (user: string, group: Group): void => { } - let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); + const world = new World(connect, disconnect, 160, 160, () => {}, () => {}); world.join({ userId: "foo" }, new Point(100, 100)); @@ -62,14 +62,14 @@ describe("World", () => { it("should disconnect user1 and user2", () => { let connectCalled: boolean = false; let disconnectCallNumber: number = 0; - let connect: ConnectCallback = (user: string, group: Group): void => { + const connect: ConnectCallback = (user: string, group: Group): void => { connectCalled = true; } - let disconnect: DisconnectCallback = (user: string, group: Group): void => { + const disconnect: DisconnectCallback = (user: string, group: Group): void => { disconnectCallNumber++; } - let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); + const world = new World(connect, disconnect, 160, 160, () => {}, () => {}); world.join({ userId: "foo" }, new Point(100, 100)); From a373626e24d6a5bcd403a2f430ba81209a9055f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Tue, 9 Jun 2020 23:07:19 +0200 Subject: [PATCH 3/4] Removing all "any" from back. To do this, I used generic-type-guard package which generates both an interface AND a valid type guard from code. With this, we are 100% sure that the messages we receive are validated at runtime! The client cannot pass us an object that is invalid! \o/ --- back/package.json | 7 +- back/src/Controller/AuthenticateController.ts | 7 +- back/src/Controller/IoSocketController.ts | 97 ++++++++++--------- back/src/Model/Websocket/ExSocketInterface.ts | 3 +- back/src/Model/Websocket/JoinRoomMessage.ts | 9 ++ back/src/Model/Websocket/MessageUserJoined.ts | 1 - back/src/Model/Websocket/PointInterface.ts | 16 ++- .../Websocket/SetPlayerDetailsMessage.ts | 12 ++- .../Model/Websocket/UserInGroupInterface.ts | 5 + .../Model/Websocket/WebRtcSignalMessage.ts | 10 ++ back/yarn.lock | 5 + 11 files changed, 113 insertions(+), 59 deletions(-) create mode 100644 back/src/Model/Websocket/JoinRoomMessage.ts create mode 100644 back/src/Model/Websocket/UserInGroupInterface.ts create mode 100644 back/src/Model/Websocket/WebRtcSignalMessage.ts diff --git a/back/package.json b/back/package.json index 9f698575..a20c876f 100644 --- a/back/package.json +++ b/back/package.json @@ -16,7 +16,8 @@ "type": "git", "url": "git+https://github.com/thecodingmachine/workadventure.git" }, - "contributors": [{ + "contributors": [ + { "name": "Grégoire Parant", "email": "g.parant@thecodingmachine.com" }, @@ -27,7 +28,8 @@ { "name": "Arthmaël Poly", "email": "a.poly@thecodingmachine.com" - }], + } + ], "license": "SEE LICENSE IN LICENSE.txt", "bugs": { "url": "https://github.com/thecodingmachine/workadventure/issues" @@ -41,6 +43,7 @@ "@types/uuidv4": "^5.0.0", "body-parser": "^1.19.0", "express": "^4.17.1", + "generic-type-guard": "^3.2.0", "http-status-codes": "^1.4.0", "jsonwebtoken": "^8.5.1", "prom-client": "^12.0.0", diff --git a/back/src/Controller/AuthenticateController.ts b/back/src/Controller/AuthenticateController.ts index 45e195fc..71e538a4 100644 --- a/back/src/Controller/AuthenticateController.ts +++ b/back/src/Controller/AuthenticateController.ts @@ -4,6 +4,11 @@ import {BAD_REQUEST, OK} from "http-status-codes"; import {SECRET_KEY, URL_ROOM_STARTED} from "../Enum/EnvironmentVariable"; //TODO fix import by "_Enum/..." import { uuid } from 'uuidv4'; +export interface TokenInterface { + name: string, + userId: string +} + export class AuthenticateController { App : Application; @@ -24,7 +29,7 @@ export class AuthenticateController { }*/ //TODO check user email for The Coding Machine game const userId = uuid(); - const token = Jwt.sign({name: param.name, userId: userId}, SECRET_KEY, {expiresIn: '24h'}); + const token = Jwt.sign({name: param.name, userId: userId} as TokenInterface, SECRET_KEY, {expiresIn: '24h'}); return res.status(OK).send({ token: token, mapUrlStart: URL_ROOM_STARTED, diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 646464e1..78efe558 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -8,12 +8,17 @@ import {SECRET_KEY, MINIMUM_DISTANCE, GROUP_RADIUS} from "../Enum/EnvironmentVar import {World} from "../Model/World"; import {Group} from "_Model/Group"; import {UserInterface} from "_Model/UserInterface"; -import {SetPlayerDetailsMessage} from "_Model/Websocket/SetPlayerDetailsMessage"; +import {isSetPlayerDetailsMessage,} from "../Model/Websocket/SetPlayerDetailsMessage"; import {MessageUserJoined} from "../Model/Websocket/MessageUserJoined"; import {MessageUserMoved} from "../Model/Websocket/MessageUserMoved"; import si from "systeminformation"; import {Gauge} from "prom-client"; import os from 'os'; +import {TokenInterface} from "../Controller/AuthenticateController"; +import {isJoinRoomMessageInterface} from "../Model/Websocket/JoinRoomMessage"; +import {isPointInterface, PointInterface} from "../Model/Websocket/PointInterface"; +import {isWebRtcSignalMessageInterface} from "../Model/Websocket/WebRtcSignalMessage"; +import {UserInGroupInterface} from "../Model/Websocket/UserInGroupInterface"; enum SockerIoEvent { CONNECTION = "connection", @@ -23,7 +28,6 @@ enum SockerIoEvent { USER_MOVED = "user-moved", // From server to client USER_LEFT = "user-left", // From server to client WEBRTC_SIGNAL = "webrtc-signal", - WEBRTC_OFFER = "webrtc-offer", WEBRTC_START = "webrtc-start", WEBRTC_DISCONNECT = "webrtc-disconect", MESSAGE_ERROR = "message-error", @@ -61,10 +65,15 @@ export class IoSocketController { if(this.searchClientByToken(socket.handshake.query.token)){ return next(new Error('Authentication error')); } - Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: any) => { + Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: object) => { if (err) { return next(new Error('Authentication error')); } + + if (!this.isValidToken(tokenDecoded)) { + return next(new Error('Authentication error, invalid token structure')); + } + (socket as ExSocketInterface).token = tokenDecoded; (socket as ExSocketInterface).userId = tokenDecoded.userId; next(); @@ -74,14 +83,24 @@ export class IoSocketController { this.ioConnection(); } + private isValidToken(token: object): token is TokenInterface { + if (typeof((token as TokenInterface).userId) !== 'string') { + return false; + } + if (typeof((token as TokenInterface).name) !== 'string') { + return false; + } + return true; + } + /** * * @param token */ searchClientByToken(token: string): ExSocketInterface | null { - const clients: Array = Object.values(this.Io.sockets.sockets); + const clients: ExSocketInterface[] = Object.values(this.Io.sockets.sockets) as ExSocketInterface[]; for (let i = 0; i < clients.length; i++) { - const client: ExSocketInterface = clients[i]; + const client = clients[i]; if (client.token !== token) { continue } @@ -131,20 +150,15 @@ export class IoSocketController { x: user x position on map y: user y position on map */ - socket.on(SockerIoEvent.JOIN_ROOM, (message: any, answerFn): void => { + socket.on(SockerIoEvent.JOIN_ROOM, (message: unknown, answerFn): void => { try { + if (!isJoinRoomMessageInterface(message)) { + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Invalid JOIN_ROOM message.'}); + console.warn('Invalid JOIN_ROOM message received: ', message); + return; + } const roomId = message.roomId; - if (typeof(roomId) !== 'string') { - socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}); - return; - } - const position = this.hydratePositionReceive(message.position); - if (position instanceof Error) { - socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); - return; - } - const Client = (socket as ExSocketInterface); if (Client.roomId === roomId) { @@ -155,7 +169,7 @@ export class IoSocketController { this.leaveRoom(Client); //join new previous room - const world = this.joinRoom(Client, roomId, position); + const world = this.joinRoom(Client, roomId, message.position); //add function to refresh position user in real time. //this.refreshUserPosition(Client); @@ -176,11 +190,11 @@ export class IoSocketController { } }); - socket.on(SockerIoEvent.USER_POSITION, (message: any): void => { + socket.on(SockerIoEvent.USER_POSITION, (position: unknown): void => { try { - const position = this.hydratePositionReceive(message); - if (position instanceof Error) { - socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); + if (!isPointInterface(position)) { + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Invalid USER_POSITION message.'}); + console.warn('Invalid USER_POSITION message received: ', position); return; } @@ -204,7 +218,12 @@ export class IoSocketController { } }); - socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => { + socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: unknown) => { + if (!isWebRtcSignalMessageInterface(data)) { + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Invalid WEBRTC_SIGNAL message.'}); + console.warn('Invalid WEBRTC_SIGNAL message received: ', data); + return; + } //send only at user const client = this.sockets.get(data.receiverId); if (client === undefined) { @@ -214,16 +233,6 @@ export class IoSocketController { return client.emit(SockerIoEvent.WEBRTC_SIGNAL, data); }); - socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => { - //send only at user - const client = this.sockets.get(data.receiverId); - if (client === undefined) { - console.warn("While exchanging a WebRTC offer: client with id ", data.receiverId, " does not exist. This might be a race condition."); - return; - } - client.emit(SockerIoEvent.WEBRTC_OFFER, data); - }); - socket.on(SockerIoEvent.DISCONNECT, () => { const Client = (socket as ExSocketInterface); try { @@ -254,7 +263,12 @@ export class IoSocketController { }); // Let's send the user id to the user - socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: SetPlayerDetailsMessage, answerFn) => { + socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: unknown, answerFn) => { + if (!isSetPlayerDetailsMessage(playerDetails)) { + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Invalid SET_PLAYER_DETAILS message.'}); + console.warn('Invalid SET_PLAYER_DETAILS message received: ', playerDetails); + return; + } const Client = (socket as ExSocketInterface); Client.name = playerDetails.name; Client.character = playerDetails.character; @@ -288,7 +302,7 @@ export class IoSocketController { } } - private joinRoom(Client : ExSocketInterface, roomId: string, position: Point): World { + private joinRoom(Client : ExSocketInterface, roomId: string, position: PointInterface): World { //join user in room Client.join(roomId); this.nbClientsPerRoomGauge.inc({ host: os.hostname(), room: roomId }); @@ -343,7 +357,7 @@ export class IoSocketController { //send all users in room to create PeerConnection in front clients.forEach((client: ExSocketInterface, index: number) => { - const clientsId = clients.reduce((tabs: Array, clientId: ExSocketInterface, indexClientId: number) => { + const clientsId = clients.reduce((tabs: Array, clientId: ExSocketInterface, indexClientId: number) => { if (!clientId.userId || clientId.userId === client.userId) { return tabs; } @@ -359,19 +373,6 @@ export class IoSocketController { }); } - //Hydrate and manage error - hydratePositionReceive(message: any): Point | Error { - try { - if (!message.x || !message.y || !message.direction || message.moving === undefined) { - return new Error("invalid point message sent"); - } - return new Point(message.x, message.y, message.direction, message.moving); - } catch (err) { - //TODO log error - return new Error(err); - } - } - /** permit to share user position ** users position will send in event 'user-position' ** The data sent is an array with information for each user : diff --git a/back/src/Model/Websocket/ExSocketInterface.ts b/back/src/Model/Websocket/ExSocketInterface.ts index df72321f..e821e296 100644 --- a/back/src/Model/Websocket/ExSocketInterface.ts +++ b/back/src/Model/Websocket/ExSocketInterface.ts @@ -1,9 +1,10 @@ import {Socket} from "socket.io"; import {PointInterface} from "./PointInterface"; import {Identificable} from "./Identificable"; +import {TokenInterface} from "../../Controller/AuthenticateController"; export interface ExSocketInterface extends Socket, Identificable { - token: any; + token: TokenInterface; roomId: string; webRtcRoomId: string; userId: string; diff --git a/back/src/Model/Websocket/JoinRoomMessage.ts b/back/src/Model/Websocket/JoinRoomMessage.ts new file mode 100644 index 00000000..16613488 --- /dev/null +++ b/back/src/Model/Websocket/JoinRoomMessage.ts @@ -0,0 +1,9 @@ +import * as tg from "generic-type-guard"; +import {isPointInterface} from "./PointInterface"; + +export const isJoinRoomMessageInterface = + new tg.IsInterface().withProperties({ + roomId: tg.isString, + position: isPointInterface, + }).get(); +export type JoinRoomMessageInterface = tg.GuardedType; diff --git a/back/src/Model/Websocket/MessageUserJoined.ts b/back/src/Model/Websocket/MessageUserJoined.ts index fff9db5d..d3143a6b 100644 --- a/back/src/Model/Websocket/MessageUserJoined.ts +++ b/back/src/Model/Websocket/MessageUserJoined.ts @@ -1,4 +1,3 @@ -import {Point} from "./MessageUserPosition"; import {PointInterface} from "_Model/Websocket/PointInterface"; export class MessageUserJoined { diff --git a/back/src/Model/Websocket/PointInterface.ts b/back/src/Model/Websocket/PointInterface.ts index 61b02339..afb07a23 100644 --- a/back/src/Model/Websocket/PointInterface.ts +++ b/back/src/Model/Websocket/PointInterface.ts @@ -1,5 +1,17 @@ -export interface PointInterface { +import * as tg from "generic-type-guard"; + +/*export interface PointInterface { readonly x: number; readonly y: number; readonly direction: string; -} + readonly moving: boolean; +}*/ + +export const isPointInterface = + new tg.IsInterface().withProperties({ + x: tg.isNumber, + y: tg.isNumber, + direction: tg.isString, + moving: tg.isBoolean + }).get(); +export type PointInterface = tg.GuardedType; diff --git a/back/src/Model/Websocket/SetPlayerDetailsMessage.ts b/back/src/Model/Websocket/SetPlayerDetailsMessage.ts index 2f3cc707..21461812 100644 --- a/back/src/Model/Websocket/SetPlayerDetailsMessage.ts +++ b/back/src/Model/Websocket/SetPlayerDetailsMessage.ts @@ -1,4 +1,8 @@ -export interface SetPlayerDetailsMessage { - name: string, - character: string -} +import * as tg from "generic-type-guard"; + +export const isSetPlayerDetailsMessage = + new tg.IsInterface().withProperties({ + name: tg.isString, + character: tg.isString + }).get(); +export type SetPlayerDetailsMessage = tg.GuardedType; diff --git a/back/src/Model/Websocket/UserInGroupInterface.ts b/back/src/Model/Websocket/UserInGroupInterface.ts new file mode 100644 index 00000000..26cc5fd4 --- /dev/null +++ b/back/src/Model/Websocket/UserInGroupInterface.ts @@ -0,0 +1,5 @@ +export interface UserInGroupInterface { + userId: string, + name: string, + initiator: boolean +} diff --git a/back/src/Model/Websocket/WebRtcSignalMessage.ts b/back/src/Model/Websocket/WebRtcSignalMessage.ts new file mode 100644 index 00000000..7edffdfa --- /dev/null +++ b/back/src/Model/Websocket/WebRtcSignalMessage.ts @@ -0,0 +1,10 @@ +import * as tg from "generic-type-guard"; + +export const isWebRtcSignalMessageInterface = + new tg.IsInterface().withProperties({ + userId: tg.isString, + receiverId: tg.isString, + roomId: tg.isString, + signal: tg.isUnknown + }).get(); +export type WebRtcSignalMessageInterface = tg.GuardedType; diff --git a/back/yarn.lock b/back/yarn.lock index 28223723..f660a5c8 100644 --- a/back/yarn.lock +++ b/back/yarn.lock @@ -790,6 +790,11 @@ functional-red-black-tree@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" +generic-type-guard@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/generic-type-guard/-/generic-type-guard-3.2.0.tgz#1fb136f934730c776486526b8a21fe96b067e691" + integrity sha512-EkkrXYbOtJ3VPB+SOrU7EhwY65rZErItGtBg5wAqywaj07BOubwOZqMYaxOWekJ9akioGqXIsw1fYk3wwbWsDQ== + get-stdin@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" From 928e486de569d4f603df172b5e199ab0594216eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Wed, 10 Jun 2020 12:32:39 +0200 Subject: [PATCH 4/4] Fixing token management --- back/src/Controller/IoSocketController.ts | 5 ++++- back/src/Model/Websocket/ExSocketInterface.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 78efe558..edda6de9 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -60,13 +60,16 @@ export class IoSocketController { // Completely commented for now, as we do not use the "/login" route at all. this.Io.use((socket: Socket, next) => { if (!socket.handshake.query || !socket.handshake.query.token) { + console.error('An authentication error happened, a user tried to connect without a token.'); return next(new Error('Authentication error')); } if(this.searchClientByToken(socket.handshake.query.token)){ + console.error('An authentication error happened, a user tried to connect while its token is already connected.'); return next(new Error('Authentication error')); } Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: object) => { if (err) { + console.error('An authentication error happened, invalid JsonWebToken.', err); return next(new Error('Authentication error')); } @@ -74,7 +77,7 @@ export class IoSocketController { return next(new Error('Authentication error, invalid token structure')); } - (socket as ExSocketInterface).token = tokenDecoded; + (socket as ExSocketInterface).token = socket.handshake.query.token; (socket as ExSocketInterface).userId = tokenDecoded.userId; next(); }); diff --git a/back/src/Model/Websocket/ExSocketInterface.ts b/back/src/Model/Websocket/ExSocketInterface.ts index e821e296..5827ccc9 100644 --- a/back/src/Model/Websocket/ExSocketInterface.ts +++ b/back/src/Model/Websocket/ExSocketInterface.ts @@ -4,7 +4,7 @@ import {Identificable} from "./Identificable"; import {TokenInterface} from "../../Controller/AuthenticateController"; export interface ExSocketInterface extends Socket, Identificable { - token: TokenInterface; + token: string; roomId: string; webRtcRoomId: string; userId: string;