Router.js 10 KB

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