socket-io.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import loggerFactory from '~/utils/logger';
  2. import { RoomPrefix, getRoomNameWithId } from '../util/socket-io-helpers';
  3. const socketIo = require('socket.io');
  4. const expressSession = require('express-session');
  5. const passport = require('passport');
  6. const logger = loggerFactory('growi:service:socket-io');
  7. /**
  8. * Serve socket.io for server-to-client messaging
  9. */
  10. class SocketIoService {
  11. constructor(crowi) {
  12. this.crowi = crowi;
  13. this.configManager = crowi.configManager;
  14. this.guestClients = new Set();
  15. }
  16. get isInitialized() {
  17. return (this.io != null);
  18. }
  19. // Since the Order is important, attachServer() should be async
  20. async attachServer(server) {
  21. this.io = socketIo(server, {
  22. transports: ['websocket'],
  23. });
  24. // create namespace for admin
  25. this.adminNamespace = this.io.of('/admin');
  26. // setup middlewares
  27. // !!CAUTION!! -- ORDER IS IMPORTANT
  28. await this.setupSessionMiddleware();
  29. await this.setupLoginRequiredMiddleware();
  30. await this.setupAdminRequiredMiddleware();
  31. await this.setupCheckConnectionLimitsMiddleware();
  32. await this.setupStoreGuestIdEventHandler();
  33. await this.setupDefaultSocketJoinRoomsEventHandler();
  34. }
  35. getDefaultSocket() {
  36. if (this.io == null) {
  37. throw new Error('Http server has not attached yet.');
  38. }
  39. return this.io.sockets;
  40. }
  41. getAdminSocket() {
  42. if (this.io == null) {
  43. throw new Error('Http server has not attached yet.');
  44. }
  45. return this.adminNamespace;
  46. }
  47. /**
  48. * use passport session
  49. * @see https://socket.io/docs/v4/middlewares/#Compatibility-with-Express-middleware
  50. */
  51. setupSessionMiddleware() {
  52. const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
  53. this.io.use(wrap(expressSession(this.crowi.sessionConfig)));
  54. this.io.use(wrap(passport.initialize()));
  55. this.io.use(wrap(passport.session()));
  56. // express and passport session on main socket doesn't shared to child namespace socket
  57. // need to define the session for specific namespace
  58. this.getAdminSocket().use(wrap(expressSession(this.crowi.sessionConfig)));
  59. this.getAdminSocket().use(wrap(passport.initialize()));
  60. this.getAdminSocket().use(wrap(passport.session()));
  61. }
  62. /**
  63. * use loginRequired middleware
  64. */
  65. setupLoginRequiredMiddleware() {
  66. const loginRequired = require('../middlewares/login-required')(this.crowi, true, (req, res, next) => {
  67. next(new Error('Login is required to connect.'));
  68. });
  69. // convert Connect/Express middleware to Socket.io middleware
  70. this.io.use((socket, next) => {
  71. loginRequired(socket.request, {}, next);
  72. });
  73. }
  74. /**
  75. * use adminRequired middleware
  76. */
  77. setupAdminRequiredMiddleware() {
  78. const adminRequired = require('../middlewares/admin-required')(this.crowi, (req, res, next) => {
  79. next(new Error('Admin priviledge is required to connect.'));
  80. });
  81. // convert Connect/Express middleware to Socket.io middleware
  82. this.getAdminSocket().use((socket, next) => {
  83. adminRequired(socket.request, {}, next);
  84. });
  85. }
  86. /**
  87. * use checkConnectionLimits middleware
  88. */
  89. setupCheckConnectionLimitsMiddleware() {
  90. this.getAdminSocket().use(this.checkConnectionLimitsForAdmin.bind(this));
  91. this.getDefaultSocket().use(this.checkConnectionLimitsForGuest.bind(this));
  92. this.getDefaultSocket().use(this.checkConnectionLimits.bind(this));
  93. }
  94. setupStoreGuestIdEventHandler() {
  95. this.io.on('connection', (socket) => {
  96. if (socket.request.user == null) {
  97. this.guestClients.add(socket.id);
  98. socket.on('disconnect', () => {
  99. this.guestClients.delete(socket.id);
  100. });
  101. }
  102. });
  103. }
  104. setupDefaultSocketJoinRoomsEventHandler() {
  105. this.io.on('connection', (socket) => {
  106. // set event handlers for joining rooms
  107. socket.on('join:page', ({ pageId }) => {
  108. socket.join(getRoomNameWithId(RoomPrefix.PAGE, pageId));
  109. });
  110. // for user rooms
  111. const user = socket.request.user;
  112. if (user == null) {
  113. logger.debug('Socket io: An anonymous user has connected');
  114. return;
  115. }
  116. socket.join(getRoomNameWithId(RoomPrefix.USER, user._id));
  117. });
  118. }
  119. async checkConnectionLimitsForAdmin(socket, next) {
  120. const namespaceName = socket.nsp.name;
  121. if (namespaceName === '/admin') {
  122. const clients = await this.getAdminSocket().allSockets();
  123. const clientsCount = clients.length;
  124. logger.debug('Current count of clients for \'/admin\':', clientsCount);
  125. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForAdmin');
  126. if (limit <= clientsCount) {
  127. const msg = `The connection was refused because the current count of clients for '/admin' is ${clientsCount} and exceeds the limit`;
  128. logger.warn(msg);
  129. next(new Error(msg));
  130. return;
  131. }
  132. }
  133. next();
  134. }
  135. async checkConnectionLimitsForGuest(socket, next) {
  136. if (socket.request.user == null) {
  137. const clientsCount = this.guestClients.size;
  138. logger.debug('Current count of clients for guests:', clientsCount);
  139. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForGuest');
  140. if (limit <= clientsCount) {
  141. const msg = `The connection was refused because the current count of clients for guests is ${clientsCount} and exceeds the limit`;
  142. logger.warn(msg);
  143. next(new Error(msg));
  144. return;
  145. }
  146. }
  147. next();
  148. }
  149. /**
  150. * @see https://socket.io/docs/server-api/#socket-client
  151. */
  152. async checkConnectionLimits(socket, next) {
  153. // exclude admin
  154. const namespaceName = socket.nsp.name;
  155. if (namespaceName === '/admin') {
  156. next();
  157. }
  158. const clients = await this.getDefaultSocket().allSockets();
  159. const clientsCount = clients.length;
  160. logger.debug('Current count of clients for \'/\':', clientsCount);
  161. const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimit');
  162. if (limit <= clientsCount) {
  163. const msg = `The connection was refused because the current count of clients for '/' is ${clientsCount} and exceeds the limit`;
  164. logger.warn(msg);
  165. next(new Error(msg));
  166. return;
  167. }
  168. next();
  169. }
  170. }
  171. module.exports = SocketIoService;