feat(server): support socketio auth field (#8595)

fix AF-1531
This commit is contained in:
forehalo
2024-10-25 03:27:02 +00:00
parent 10963da706
commit 08319bc560
5 changed files with 45 additions and 29 deletions
@@ -1,4 +1,5 @@
import { GatewayMetadata } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { defineStartupConfig, ModuleConfig } from '../config';
@@ -6,7 +7,7 @@ declare module '../config' {
interface AppConfig {
websocket: ModuleConfig<
GatewayMetadata & {
requireAuthentication?: boolean;
canActivate?: (socket: Socket) => Promise<boolean>;
}
>;
}
@@ -16,5 +17,4 @@ defineStartupConfig('websocket', {
// see: https://socket.io/docs/v4/server-options/#maxhttpbuffersize
transports: ['websocket'],
maxHttpBufferSize: 1e8, // 100 MB
requireAuthentication: true,
});
@@ -10,6 +10,7 @@ import { IoAdapter } from '@nestjs/platform-socket.io';
import { Server } from 'socket.io';
import { Config } from '../config';
import { AuthenticationRequired } from '../error';
export const SocketIoAdapterImpl = Symbol('SocketIoAdapterImpl');
@@ -19,8 +20,31 @@ export class SocketIoAdapter extends IoAdapter {
}
override createIOServer(port: number, options?: any): Server {
const config = this.app.get(WEBSOCKET_OPTIONS);
return super.createIOServer(port, { ...config, ...options });
const config = this.app.get(WEBSOCKET_OPTIONS) as Config['websocket'];
const server: Server = super.createIOServer(port, {
...config,
...options,
});
if (config.canActivate) {
server.use((socket, next) => {
// @ts-expect-error checked
config
.canActivate(socket)
.then(pass => {
if (pass) {
next();
} else {
throw new AuthenticationRequired();
}
})
.catch(e => {
next(e);
});
});
}
return server;
}
}