fix(api): secure web-socket access

This commit is contained in:
yassinedorbozgithub 2024-10-10 19:20:49 +01:00
parent 5681a810aa
commit d3ef4ea448
2 changed files with 39 additions and 22 deletions

View File

@ -128,6 +128,9 @@ export class ChannelService {
); );
if (!req.session?.passport?.user?.id) { if (!req.session?.passport?.user?.id) {
setTimeout(() => {
req.socket.client.conn.close();
}, 300);
throw new UnauthorizedException( throw new UnauthorizedException(
'Only authenticated users are allowed to use this channel', 'Only authenticated users are allowed to use this channel',
); );

View File

@ -207,31 +207,45 @@ export class WebsocketGateway
// Handle session // Handle session
this.io.use((client, next) => { this.io.use((client, next) => {
this.logger.verbose('Client connected, attempting to load session.'); this.logger.verbose('Client connected, attempting to load session.');
if (client.request.headers.cookie) { try {
const cookies = cookie.parse(client.request.headers.cookie); const { searchParams } = new URL(`ws://localhost${client.request.url}`);
if (cookies && config.session.name in cookies) { if (client.request.headers.cookie) {
const sessionID = cookieParser.signedCookie( const cookies = cookie.parse(client.request.headers.cookie);
cookies[config.session.name], if (cookies && config.session.name in cookies) {
config.session.secret, const sessionID = cookieParser.signedCookie(
); cookies[config.session.name],
if (sessionID) { config.session.secret,
return this.loadSession(sessionID, (err, session) => { );
if (err) { if (sessionID) {
this.logger.warn( return this.loadSession(sessionID, (err, session) => {
'Unable to load session, creating a new one ...', if (err || !session) {
err, this.logger.warn(
); 'Unable to load session, creating a new one ...',
return this.createAndStoreSession(client, next); err,
} );
client.data.session = session; if (searchParams.get('channel') === 'offline') {
client.data.sessionID = sessionID; return this.createAndStoreSession(client, next);
next(); } else {
}); return next(new Error('Unauthorized: Unknown session ID'));
}
}
client.data.session = session;
client.data.sessionID = sessionID;
next();
});
} else {
return next(new Error('Unable to parse session ID from cookie'));
}
} }
} else if (searchParams.get('channel') === 'offline') {
return this.createAndStoreSession(client, next);
} else {
return next(new Error('Unauthorized to connect to WS'));
} }
} catch (e) {
this.logger.warn('Something unexpected happening');
return next(e);
} }
return this.createAndStoreSession(client, next);
}); });
} }