-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathauth-websocket.middleware.ts
More file actions
134 lines (114 loc) · 3.88 KB
/
Copy pathauth-websocket.middleware.ts
File metadata and controls
134 lines (114 loc) · 3.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import { ClientProxy } from '@nestjs/microservices';
import { Socket } from 'socket.io';
import { firstValueFrom } from 'rxjs';
import { timeout } from 'rxjs/operators';
import { BlacklistService } from '@app/common';
import { User } from '@entities';
export interface AuthWebsocket extends Socket {
user: User;
}
export type SocketIOMiddleware = {
(client: Socket, next: (err?: Error) => void);
};
/* This middleware will intercept connection requests during the handshake enabling authentication to
* occur before the connection is established.
*/
export const AuthWebsocketMiddleware = (
authService: ClientProxy,
blacklistService: BlacklistService,
windowSeconds: number = 60,
maxAttempts: number = 5,
): SocketIOMiddleware => {
// In-memory rate limiting
const attempts = new Map<string, { count: number; resetAt: number }>();
// Cleanup expired entries every minute
setInterval(() => {
const now = Date.now();
for (const [ip, record] of attempts.entries()) {
if (now > record.resetAt) {
attempts.delete(ip);
}
}
}, 60_000);
const trackAttempt = (ip: string): boolean => {
const now = Date.now();
const record = attempts.get(ip);
if (!record || now > record.resetAt) {
attempts.set(ip, { count: 1, resetAt: now + windowSeconds * 1000 });
return false;
}
record.count++;
return record.count > maxAttempts;
};
const resetAttempts = (ip: string): void => {
attempts.delete(ip);
};
return async (socket: Socket, next) => {
const authSocket = socket as AuthWebsocket;
const ip = socket.handshake.address;
try {
/* Get the JWT from the header */
const { token } = socket.handshake.auth;
if (!token) {
const isRateLimited = trackAttempt(ip);
if (isRateLimited) {
return next(new Error('Too many failed authentication attempts'));
}
return next(new Error('Unauthorized'));
}
const jwt = (Array.isArray(token) ? token[0] : token).split(' ')[1];
if (!jwt) {
const isRateLimited = trackAttempt(ip);
if (isRateLimited) {
return next(new Error('Too many failed authentication attempts'));
}
return next(new Error('Unauthorized'));
}
const isBlacklisted = await blacklistService.isTokenBlacklisted(jwt);
if (isBlacklisted) {
const isRateLimited = trackAttempt(ip);
if (isRateLimited) {
return next(new Error('Too many failed authentication attempts'));
}
return next(new Error('Unauthorized'));
}
/* Request authentication of the jwt from the API service. */
const response = authService
.send<User>('authenticate-websocket-token', {
jwt,
})
.pipe(timeout(2000));
const user = await firstValueFrom(response);
if (!user) {
const isRateLimited = trackAttempt(ip);
if (isRateLimited) {
return next(new Error('Too many failed authentication attempts'));
}
return next(new Error('Unauthorized'));
}
// Success - reset rate limit counter
resetAttempts(ip);
authSocket.user = user;
next();
} catch (err) {
const e = err as any;
// Note: socket.io automatically disconnects after next(error), no need for explicit disconnect
if (
e?.name === 'TimeoutError' ||
e?.code === 'ECONNREFUSED' ||
e?.code === 'NO_RESPONDERS' ||
e?.message?.includes('No responders')
) {
return next(new Error('Auth service unavailable'));
} else {
// Rate limit other auth failures
const isRateLimited = trackAttempt(ip);
if (isRateLimited) {
return next(new Error('Too many failed authentication attempts'));
}
console.error('AuthWebsocketMiddleware error:', err);
return next(new Error('Unauthorized'));
}
}
};
};