-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (55 loc) · 1.77 KB
/
server.js
File metadata and controls
60 lines (55 loc) · 1.77 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
import * as env from 'lib0/environment'
import * as jwt from 'lib0/crypto/jwt'
import * as ecdsa from 'lib0/crypto/ecdsa'
import * as json from 'lib0/json'
import { Server } from 'socket.io'
import { registerYSocketIOServer } from './socketio.js'
import http from 'http'
import { randomUUID } from 'crypto'
const authPublicKey = env.getConf('auth-public-key')
/** @type {CryptoKey | null} */
let wsServerPublicKey = null
if (authPublicKey) {
ecdsa
.importKeyJwk(json.parse(env.ensureConf('auth-public-key')))
.then((key) => { wsServerPublicKey = key })
}
/**
* @param {Object} opts
* @param {number} opts.port
* @param {import('./storage.js').AbstractStorage} opts.store
* @param {string} [opts.redisPrefix]
*/
export const createYSocketIOServer = async ({
redisPrefix = 'y',
port,
store
}) => {
const httpServer = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ ok: true }))
})
const io = new Server(httpServer)
const server = await registerYSocketIOServer(io, store, {
redisPrefix,
authenticate: async (socket) => {
if (!wsServerPublicKey) return { userid: randomUUID().toString() }
const token = socket.handshake.query.yauth
if (!token) return null
// verify that the user has a valid token
const { payload: userToken } = await jwt.verifyJwt(
wsServerPublicKey,
typeof token === 'string' ? token : token[0]
)
if (!userToken.yuserid) return null
return { userid: userToken.yuserid }
}
})
httpServer.listen(port, undefined, undefined)
const oriDestroy = server.destroy
server.destroy = async () => {
await oriDestroy.bind(server)()
await new Promise((resolve) => httpServer.close(resolve))
}
return server
}