Router.js 11 KB

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