-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.ts
54 lines (44 loc) · 1.54 KB
/
index.ts
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
import * as cookie from 'cookie'
import {createServer, IncomingMessage} from 'http'
import * as jwt from 'jsonwebtoken'
import {Socket} from 'net'
import * as WebSocket from 'ws'
import {AccessToken, Cookies} from '@shared'
interface AuthenticatedSocket extends WebSocket {
accessToken: AccessToken
}
const server = createServer((req, res) => res.end())
const wss = new WebSocket.Server({noServer: true})
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET!
server.on('upgrade', (request: IncomingMessage, socket: Socket, head: Buffer) => {
try {
const cookies = cookie.parse(request.headers.cookie as string)
const accessToken = jwt.verify(cookies[Cookies.AccessToken], accessTokenSecret) as AccessToken
wss.handleUpgrade(request, socket, head, ws => {
;(ws as AuthenticatedSocket).accessToken = accessToken
wss.emit('connection', ws)
})
} catch (error) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
socket.destroy()
}
})
function broadcast(message: any) {
;(wss.clients as Set<AuthenticatedSocket>).forEach(client => {
validateExpiration(client)
client.send(JSON.stringify(message))
})
}
function validateExpiration(socket: AuthenticatedSocket) {
if (new Date().getTime() / 1000 > socket.accessToken.exp) {
socket.close()
}
}
wss.on('connection', (socket: AuthenticatedSocket) => {
socket.on('message', (message: Buffer) => {
validateExpiration(socket)
const msg = {text: message.toString(), userId: socket.accessToken.userId}
broadcast(msg)
})
})
server.listen(3000)