Router.js 10 KB

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