Router.js 12 KB

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