Router.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /* eslint-disable
  2. camelcase,
  3. */
  4. const metrics = require('@overleaf/metrics')
  5. const logger = require('logger-sharelatex')
  6. const settings = require('settings-sharelatex')
  7. const WebsocketController = require('./WebsocketController')
  8. const HttpController = require('./HttpController')
  9. const HttpApiController = require('./HttpApiController')
  10. const bodyParser = require('body-parser')
  11. const base64id = require('base64id')
  12. const { UnexpectedArgumentsError } = require('./Errors')
  13. const basicAuth = require('basic-auth-connect')
  14. const httpAuth = basicAuth(function (user, pass) {
  15. const isValid =
  16. user === settings.internal.realTime.user &&
  17. pass === settings.internal.realTime.pass
  18. if (!isValid) {
  19. logger.err({ user, pass }, 'invalid login details')
  20. }
  21. return isValid
  22. })
  23. const HOSTNAME = require('os').hostname()
  24. let Router
  25. module.exports = Router = {
  26. _handleError(callback, error, client, method, attrs) {
  27. attrs = attrs || {}
  28. for (const key of ['project_id', 'user_id']) {
  29. attrs[key] = attrs[key] || client.ol_context[key]
  30. }
  31. attrs.client_id = client.id
  32. attrs.err = error
  33. attrs.method = method
  34. if (error.name === 'CodedError') {
  35. logger.warn(attrs, error.message)
  36. const serializedError = { message: error.message, code: error.info.code }
  37. callback(serializedError)
  38. } else if (error.message === 'unexpected arguments') {
  39. // the payload might be very large, put it on level info
  40. logger.log(attrs, 'unexpected arguments')
  41. metrics.inc('unexpected-arguments', 1, { status: method })
  42. const serializedError = { message: error.message }
  43. callback(serializedError)
  44. } else if (error.message === 'no project_id found on client') {
  45. logger.debug(attrs, error.message)
  46. const serializedError = { message: error.message }
  47. callback(serializedError)
  48. } else if (
  49. [
  50. 'not authorized',
  51. 'joinLeaveEpoch mismatch',
  52. 'doc updater could not load requested ops'
  53. ].includes(error.message)
  54. ) {
  55. logger.warn(attrs, error.message)
  56. const serializedError = { message: error.message }
  57. callback(serializedError)
  58. } else {
  59. logger.error(attrs, `server side error in ${method}`)
  60. // Don't return raw error to prevent leaking server side info
  61. const serializedError = {
  62. message: 'Something went wrong in real-time service'
  63. }
  64. callback(serializedError)
  65. }
  66. },
  67. _handleInvalidArguments(client, method, args) {
  68. const error = new UnexpectedArgumentsError()
  69. let callback = args[args.length - 1]
  70. if (typeof callback !== 'function') {
  71. callback = function () {}
  72. }
  73. const attrs = { arguments: args }
  74. Router._handleError(callback, error, client, method, attrs)
  75. },
  76. configure(app, io, session) {
  77. app.set('io', io)
  78. app.get('/clients', HttpController.getConnectedClients)
  79. app.get('/clients/:client_id', HttpController.getConnectedClient)
  80. app.post(
  81. '/project/:project_id/message/:message',
  82. httpAuth,
  83. bodyParser.json({ limit: '5mb' }),
  84. HttpApiController.sendMessage
  85. )
  86. app.post('/drain', httpAuth, HttpApiController.startDrain)
  87. app.post(
  88. '/client/:client_id/disconnect',
  89. httpAuth,
  90. HttpApiController.disconnectClient
  91. )
  92. session.on('connection', function (error, client, session) {
  93. // init client context, we may access it in Router._handleError before
  94. // setting any values
  95. client.ol_context = {}
  96. // bail out from joinDoc when a parallel joinDoc or leaveDoc is running
  97. client.joinLeaveEpoch = 0
  98. if (client) {
  99. client.on('error', function (err) {
  100. logger.err({ clientErr: err }, 'socket.io client error')
  101. if (client.connected) {
  102. client.emit('reconnectGracefully')
  103. client.disconnect()
  104. }
  105. })
  106. }
  107. if (settings.shutDownInProgress) {
  108. client.emit('connectionRejected', { message: 'retry' })
  109. client.disconnect()
  110. return
  111. }
  112. if (
  113. client &&
  114. error &&
  115. error.message.match(/could not look up session by key/)
  116. ) {
  117. logger.warn(
  118. { err: error, client: !!client, session: !!session },
  119. 'invalid session'
  120. )
  121. // tell the client to reauthenticate if it has an invalid session key
  122. client.emit('connectionRejected', { message: 'invalid session' })
  123. client.disconnect()
  124. return
  125. }
  126. if (error) {
  127. logger.err(
  128. { err: error, client: !!client, session: !!session },
  129. 'error when client connected'
  130. )
  131. if (client) {
  132. client.emit('connectionRejected', { message: 'error' })
  133. }
  134. if (client) {
  135. client.disconnect()
  136. }
  137. return
  138. }
  139. // send positive confirmation that the client has a valid connection
  140. client.publicId = 'P.' + base64id.generateId()
  141. client.emit('connectionAccepted', null, client.publicId)
  142. metrics.inc('socket-io.connection')
  143. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  144. logger.log({ session, client_id: client.id }, 'client connected')
  145. let user
  146. if (session && session.passport && session.passport.user) {
  147. ;({ user } = session.passport)
  148. } else if (session && session.user) {
  149. ;({ user } = session)
  150. } else {
  151. user = { _id: 'anonymous-user' }
  152. }
  153. if (settings.exposeHostname) {
  154. client.on('debug.getHostname', function (callback) {
  155. if (typeof callback !== 'function') {
  156. return Router._handleInvalidArguments(
  157. client,
  158. 'debug.getHostname',
  159. arguments
  160. )
  161. }
  162. callback(HOSTNAME)
  163. })
  164. }
  165. client.on('joinProject', function (data, callback) {
  166. data = data || {}
  167. if (typeof callback !== 'function') {
  168. return Router._handleInvalidArguments(
  169. client,
  170. 'joinProject',
  171. arguments
  172. )
  173. }
  174. if (data.anonymousAccessToken) {
  175. user.anonymousAccessToken = data.anonymousAccessToken
  176. }
  177. WebsocketController.joinProject(
  178. client,
  179. user,
  180. data.project_id,
  181. function (err, ...args) {
  182. if (err) {
  183. Router._handleError(callback, err, client, 'joinProject', {
  184. project_id: data.project_id,
  185. user_id: user._id
  186. })
  187. } else {
  188. callback(null, ...args)
  189. }
  190. }
  191. )
  192. })
  193. client.on('disconnect', function () {
  194. metrics.inc('socket-io.disconnect')
  195. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  196. WebsocketController.leaveProject(io, client, function (err) {
  197. if (err) {
  198. Router._handleError(function () {}, err, client, 'leaveProject')
  199. }
  200. })
  201. })
  202. // Variadic. The possible arguments:
  203. // doc_id, callback
  204. // doc_id, fromVersion, callback
  205. // doc_id, options, callback
  206. // doc_id, fromVersion, options, callback
  207. client.on('joinDoc', function (doc_id, fromVersion, options, callback) {
  208. if (typeof fromVersion === 'function' && !options) {
  209. callback = fromVersion
  210. fromVersion = -1
  211. options = {}
  212. } else if (
  213. typeof fromVersion === 'number' &&
  214. typeof options === 'function'
  215. ) {
  216. callback = options
  217. options = {}
  218. } else if (
  219. typeof fromVersion === 'object' &&
  220. typeof options === 'function'
  221. ) {
  222. callback = options
  223. options = fromVersion
  224. fromVersion = -1
  225. } else if (
  226. typeof fromVersion === 'number' &&
  227. typeof options === 'object' &&
  228. typeof callback === 'function'
  229. ) {
  230. // Called with 4 args, things are as expected
  231. } else {
  232. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  233. }
  234. WebsocketController.joinDoc(
  235. client,
  236. doc_id,
  237. fromVersion,
  238. options,
  239. function (err, ...args) {
  240. if (err) {
  241. Router._handleError(callback, err, client, 'joinDoc', {
  242. doc_id,
  243. fromVersion
  244. })
  245. } else {
  246. callback(null, ...args)
  247. }
  248. }
  249. )
  250. })
  251. client.on('leaveDoc', function (doc_id, callback) {
  252. if (typeof callback !== 'function') {
  253. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  254. }
  255. WebsocketController.leaveDoc(client, doc_id, function (err, ...args) {
  256. if (err) {
  257. Router._handleError(callback, err, client, 'leaveDoc', {
  258. doc_id
  259. })
  260. } else {
  261. callback(null, ...args)
  262. }
  263. })
  264. })
  265. client.on('clientTracking.getConnectedUsers', function (callback) {
  266. if (typeof callback !== 'function') {
  267. return Router._handleInvalidArguments(
  268. client,
  269. 'clientTracking.getConnectedUsers',
  270. arguments
  271. )
  272. }
  273. WebsocketController.getConnectedUsers(client, function (err, users) {
  274. if (err) {
  275. Router._handleError(
  276. callback,
  277. err,
  278. client,
  279. 'clientTracking.getConnectedUsers'
  280. )
  281. } else {
  282. callback(null, users)
  283. }
  284. })
  285. })
  286. client.on('clientTracking.updatePosition', function (
  287. cursorData,
  288. callback
  289. ) {
  290. if (!callback) {
  291. callback = function () {}
  292. }
  293. if (typeof callback !== 'function') {
  294. return Router._handleInvalidArguments(
  295. client,
  296. 'clientTracking.updatePosition',
  297. arguments
  298. )
  299. }
  300. WebsocketController.updateClientPosition(client, cursorData, function (
  301. err
  302. ) {
  303. if (err) {
  304. Router._handleError(
  305. callback,
  306. err,
  307. client,
  308. 'clientTracking.updatePosition'
  309. )
  310. } else {
  311. callback()
  312. }
  313. })
  314. })
  315. client.on('applyOtUpdate', function (doc_id, update, callback) {
  316. if (typeof callback !== 'function') {
  317. return Router._handleInvalidArguments(
  318. client,
  319. 'applyOtUpdate',
  320. arguments
  321. )
  322. }
  323. WebsocketController.applyOtUpdate(client, doc_id, update, function (
  324. err
  325. ) {
  326. if (err) {
  327. Router._handleError(callback, err, client, 'applyOtUpdate', {
  328. doc_id,
  329. update
  330. })
  331. } else {
  332. callback()
  333. }
  334. })
  335. })
  336. })
  337. }
  338. }