Router.js 11 KB

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