Skip to content

Commit 550b494

Browse files
committed
Fix: Move authentication to Socket.IO connection handler
- Remove allowRequest middleware (doesn't have access to auth) - Validate auth token in connection handler using socket.handshake.auth - Add detailed logging for auth token - Disconnect unauthorized clients immediately
1 parent bced1cb commit 550b494

2 files changed

Lines changed: 21 additions & 37 deletions

File tree

src/index.ts

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -81,45 +81,10 @@ const io = new Server(httpServer, {
8181
transports: ['websocket', 'polling'],
8282
pingTimeout: 60000,
8383
pingInterval: 25000,
84-
// 鉴权中间件
85-
allowRequest: (req, callback) => {
86-
// 详细日志
87-
console.log('[WatchRoom] Connection attempt from:', req.headers.origin);
88-
console.log('[WatchRoom] URL:', req.url);
89-
90-
// 尝试从多个地方获取认证信息
91-
const authHeader = req.headers.authorization;
92-
const urlParams = new URL(req.url || '', 'http://localhost').searchParams;
93-
const authFromQuery = urlParams.get('auth');
94-
95-
console.log('[WatchRoom] Authorization header:', authHeader);
96-
console.log('[WatchRoom] Auth from query:', authFromQuery);
97-
console.log('[WatchRoom] Expected AUTH_KEY:', AUTH_KEY);
98-
99-
// 检查 Authorization header
100-
if (authHeader === `Bearer ${AUTH_KEY}`) {
101-
console.log('[WatchRoom] ✅ Authentication successful (via header)');
102-
callback(null, true);
103-
return;
104-
}
105-
106-
// 检查 query 参数(作为备用方案)
107-
if (authFromQuery === AUTH_KEY) {
108-
console.log('[WatchRoom] ✅ Authentication successful (via query)');
109-
callback(null, true);
110-
return;
111-
}
112-
113-
console.log('[WatchRoom] ❌ Authentication failed');
114-
console.log('[WatchRoom] Received header:', authHeader);
115-
console.log('[WatchRoom] Received query:', authFromQuery);
116-
console.log('[WatchRoom] Expected:', `Bearer ${AUTH_KEY}`);
117-
callback('Unauthorized', false);
118-
},
11984
});
12085

12186
// 初始化观影室服务器
122-
const watchRoomServer = new WatchRoomServer(io);
87+
const watchRoomServer = new WatchRoomServer(io, AUTH_KEY);
12388

12489
// 启动服务器
12590
httpServer.listen(PORT, () => {

src/watch-room-server.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,13 @@ export class WatchRoomServer {
1616
private members: Map<string, Map<string, Member>> = new Map();
1717
private socketToRoom: Map<string, RoomMemberInfo> = new Map();
1818
private cleanupInterval: NodeJS.Timeout | null = null;
19+
private authKey: string;
1920

20-
constructor(private io: SocketIOServer<ClientToServerEvents, ServerToClientEvents>) {
21+
constructor(
22+
private io: SocketIOServer<ClientToServerEvents, ServerToClientEvents>,
23+
authKey?: string
24+
) {
25+
this.authKey = authKey || process.env.AUTH_KEY || '';
2126
this.setupEventHandlers();
2227
this.startCleanupTimer();
2328
}
@@ -26,6 +31,20 @@ export class WatchRoomServer {
2631
this.io.on('connection', (socket: TypedSocket) => {
2732
console.log(`[WatchRoom] Client connected: ${socket.id}`);
2833

34+
// 验证认证
35+
const auth = socket.handshake.auth as { token?: string };
36+
console.log('[WatchRoom] Auth token from handshake:', auth.token);
37+
console.log('[WatchRoom] Expected AUTH_KEY:', this.authKey);
38+
39+
if (!auth.token || auth.token !== this.authKey) {
40+
console.log('[WatchRoom] ❌ Authentication failed, disconnecting client');
41+
socket.emit('error', 'Unauthorized');
42+
socket.disconnect(true);
43+
return;
44+
}
45+
46+
console.log('[WatchRoom] ✅ Authentication successful');
47+
2948
// 创建房间
3049
socket.on('room:create', (data, callback) => {
3150
try {

0 commit comments

Comments
 (0)