|
1 | 1 | import { Server } from '@hocuspocus/server'; |
| 2 | +import express, { Request, Response } from 'express'; |
| 3 | +import expressWebsockets from 'express-ws'; |
2 | 4 |
|
3 | | -const port = Number(process.env.PORT || 4444); |
| 5 | +import { PORT } from './env'; |
| 6 | +import { httpSecurity, wsSecurity } from './middlewares'; |
| 7 | +import { routes } from './routes'; |
| 8 | +import { logger } from './utils'; |
4 | 9 |
|
5 | | -const server = Server.configure({ |
6 | | - name: 'docs-y-provider', |
7 | | - port: port, |
| 10 | +export const hocuspocusServer = Server.configure({ |
| 11 | + name: 'docs-y-server', |
8 | 12 | timeout: 30000, |
9 | | - debounce: 2000, |
10 | | - maxDebounce: 30000, |
11 | 13 | quiet: true, |
12 | | -}); |
| 14 | + onConnect({ requestHeaders, connection, documentName, requestParameters }) { |
| 15 | + const roomParam = requestParameters.get('room'); |
| 16 | + const canEdit = requestHeaders['x-can-edit'] === 'True'; |
| 17 | + |
| 18 | + if (!canEdit) { |
| 19 | + connection.readOnly = true; |
| 20 | + } |
| 21 | + |
| 22 | + logger( |
| 23 | + 'Connection established:', |
| 24 | + documentName, |
| 25 | + 'userId:', |
| 26 | + requestHeaders['x-user-id'], |
| 27 | + 'canEdit:', |
| 28 | + canEdit, |
| 29 | + 'room:', |
| 30 | + requestParameters.get('room'), |
| 31 | + ); |
| 32 | + |
| 33 | + if (documentName !== roomParam) { |
| 34 | + console.error( |
| 35 | + 'Invalid room name - Probable hacking attempt:', |
| 36 | + documentName, |
| 37 | + requestParameters.get('room'), |
| 38 | + requestHeaders['x-user-id'], |
| 39 | + ); |
| 40 | + |
| 41 | + return Promise.reject(new Error('Unauthorized')); |
| 42 | + } |
13 | 43 |
|
14 | | -server.listen().catch((error) => { |
15 | | - console.error('Failed to start the server:', error); |
| 44 | + return Promise.resolve(); |
| 45 | + }, |
16 | 46 | }); |
17 | 47 |
|
18 | | -console.log('Websocket server running on port :', port); |
| 48 | +/** |
| 49 | + * init the collaboration server. |
| 50 | + * |
| 51 | + * @param port - The port on which the server listens. |
| 52 | + * @param serverSecret - The secret key for API authentication. |
| 53 | + * @returns An object containing the Express app, Hocuspocus server, and HTTP server instance. |
| 54 | + */ |
| 55 | +export const initServer = () => { |
| 56 | + const { app } = expressWebsockets(express()); |
| 57 | + app.use(express.json()); |
| 58 | + |
| 59 | + /** |
| 60 | + * Route to handle WebSocket connections |
| 61 | + */ |
| 62 | + app.ws(routes.COLLABORATION_WS, wsSecurity, (ws, req) => { |
| 63 | + logger('Incoming Origin:', req.headers['origin']); |
| 64 | + |
| 65 | + try { |
| 66 | + hocuspocusServer.handleConnection(ws, req); |
| 67 | + } catch (error) { |
| 68 | + console.error('Failed to handle WebSocket connection:', error); |
| 69 | + ws.close(); |
| 70 | + } |
| 71 | + }); |
| 72 | + |
| 73 | + type ResetConnectionsRequestQuery = { |
| 74 | + room?: string; |
| 75 | + }; |
| 76 | + |
| 77 | + /** |
| 78 | + * Route to reset connections in a room: |
| 79 | + * - If no user ID is provided, close all connections in the room |
| 80 | + * - If a user ID is provided, close connections for the user in the room |
| 81 | + */ |
| 82 | + app.post( |
| 83 | + routes.COLLABORATION_RESET_CONNECTIONS, |
| 84 | + httpSecurity, |
| 85 | + ( |
| 86 | + req: Request<object, object, object, ResetConnectionsRequestQuery>, |
| 87 | + res: Response, |
| 88 | + ) => { |
| 89 | + const room = req.query.room; |
| 90 | + const userId = req.headers['x-user-id']; |
| 91 | + |
| 92 | + logger( |
| 93 | + 'Resetting connections in room:', |
| 94 | + room, |
| 95 | + 'for user:', |
| 96 | + userId, |
| 97 | + 'room:', |
| 98 | + room, |
| 99 | + ); |
| 100 | + |
| 101 | + if (!room) { |
| 102 | + res.status(400).json({ error: 'Room name not provided' }); |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * If no user ID is provided, close all connections in the room |
| 108 | + */ |
| 109 | + if (!userId) { |
| 110 | + hocuspocusServer.closeConnections(room); |
| 111 | + } else { |
| 112 | + /** |
| 113 | + * Close connections for the user in the room |
| 114 | + */ |
| 115 | + hocuspocusServer.documents.forEach((doc) => { |
| 116 | + if (doc.name !== room) { |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + doc.getConnections().forEach((connection) => { |
| 121 | + const connectionUserId = connection.request.headers['x-user-id']; |
| 122 | + if (connectionUserId === userId) { |
| 123 | + connection.close(); |
| 124 | + } |
| 125 | + }); |
| 126 | + }); |
| 127 | + } |
| 128 | + |
| 129 | + res.status(200).json({ message: 'Connections reset' }); |
| 130 | + }, |
| 131 | + ); |
| 132 | + |
| 133 | + app.get('/ping', (req, res) => { |
| 134 | + res.status(200).json({ message: 'pong' }); |
| 135 | + }); |
| 136 | + |
| 137 | + app.use((req, res) => { |
| 138 | + logger('Invalid route:', req.url); |
| 139 | + res.status(403).json({ error: 'Forbidden' }); |
| 140 | + }); |
| 141 | + |
| 142 | + const server = app.listen(PORT, () => |
| 143 | + console.log('Listening on port :', PORT), |
| 144 | + ); |
| 145 | + |
| 146 | + return { app, server }; |
| 147 | +}; |
0 commit comments