1
0

index.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. // @ts-check
  2. const os = require('os');
  3. const throng = require('throng');
  4. const dotenv = require('dotenv');
  5. const express = require('express');
  6. const http = require('http');
  7. const redis = require('redis');
  8. const pg = require('pg');
  9. const log = require('npmlog');
  10. const url = require('url');
  11. const { WebSocketServer } = require('@clusterws/cws');
  12. const uuid = require('uuid');
  13. const fs = require('fs');
  14. const env = process.env.NODE_ENV || 'development';
  15. const alwaysRequireAuth = process.env.LIMITED_FEDERATION_MODE === 'true' || process.env.WHITELIST_MODE === 'true' || process.env.AUTHORIZED_FETCH === 'true';
  16. dotenv.config({
  17. path: env === 'production' ? '.env.production' : '.env',
  18. });
  19. log.level = process.env.LOG_LEVEL || 'verbose';
  20. /**
  21. * @param {string} dbUrl
  22. * @return {Object.<string, any>}
  23. */
  24. const dbUrlToConfig = (dbUrl) => {
  25. if (!dbUrl) {
  26. return {};
  27. }
  28. const params = url.parse(dbUrl, true);
  29. const config = {};
  30. if (params.auth) {
  31. [config.user, config.password] = params.auth.split(':');
  32. }
  33. if (params.hostname) {
  34. config.host = params.hostname;
  35. }
  36. if (params.port) {
  37. config.port = params.port;
  38. }
  39. if (params.pathname) {
  40. config.database = params.pathname.split('/')[1];
  41. }
  42. const ssl = params.query && params.query.ssl;
  43. if (ssl && ssl === 'true' || ssl === '1') {
  44. config.ssl = true;
  45. }
  46. return config;
  47. };
  48. /**
  49. * @param {Object.<string, any>} defaultConfig
  50. * @param {string} redisUrl
  51. */
  52. const redisUrlToClient = (defaultConfig, redisUrl) => {
  53. const config = defaultConfig;
  54. if (!redisUrl) {
  55. return redis.createClient(config);
  56. }
  57. if (redisUrl.startsWith('unix://')) {
  58. return redis.createClient(redisUrl.slice(7), config);
  59. }
  60. return redis.createClient(Object.assign(config, {
  61. url: redisUrl,
  62. }));
  63. };
  64. const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  65. /**
  66. * @param {string} json
  67. * @return {Object.<string, any>|null}
  68. */
  69. const parseJSON = (json) => {
  70. try {
  71. return JSON.parse(json);
  72. } catch (err) {
  73. log.error(err);
  74. return null;
  75. }
  76. };
  77. const startMaster = () => {
  78. if (!process.env.SOCKET && process.env.PORT && isNaN(+process.env.PORT)) {
  79. log.warn('UNIX domain socket is now supported by using SOCKET. Please migrate from PORT hack.');
  80. }
  81. log.info(`Starting streaming API server master with ${numWorkers} workers`);
  82. };
  83. const startWorker = (workerId) => {
  84. log.info(`Starting worker ${workerId}`);
  85. const pgConfigs = {
  86. development: {
  87. user: process.env.DB_USER || pg.defaults.user,
  88. password: process.env.DB_PASS || pg.defaults.password,
  89. database: process.env.DB_NAME || 'mastodon_development',
  90. host: process.env.DB_HOST || pg.defaults.host,
  91. port: process.env.DB_PORT || pg.defaults.port,
  92. max: 10,
  93. },
  94. production: {
  95. user: process.env.DB_USER || 'mastodon',
  96. password: process.env.DB_PASS || '',
  97. database: process.env.DB_NAME || 'mastodon_production',
  98. host: process.env.DB_HOST || 'localhost',
  99. port: process.env.DB_PORT || 5432,
  100. max: 10,
  101. },
  102. };
  103. if (!!process.env.DB_SSLMODE && process.env.DB_SSLMODE !== 'disable') {
  104. pgConfigs.development.ssl = true;
  105. pgConfigs.production.ssl = true;
  106. }
  107. const app = express();
  108. app.set('trusted proxy', process.env.TRUSTED_PROXY_IP || 'loopback,uniquelocal');
  109. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  110. const server = http.createServer(app);
  111. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  112. const redisParams = {
  113. host: process.env.REDIS_HOST || '127.0.0.1',
  114. port: process.env.REDIS_PORT || 6379,
  115. db: process.env.REDIS_DB || 0,
  116. password: process.env.REDIS_PASSWORD || undefined,
  117. };
  118. if (redisNamespace) {
  119. redisParams.namespace = redisNamespace;
  120. }
  121. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  122. const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  123. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  124. /**
  125. * @type {Object.<string, Array.<function(string): void>>}
  126. */
  127. const subs = {};
  128. redisSubscribeClient.on('message', (channel, message) => {
  129. const callbacks = subs[channel];
  130. log.silly(`New message on channel ${channel}`);
  131. if (!callbacks) {
  132. return;
  133. }
  134. callbacks.forEach(callback => callback(message));
  135. });
  136. /**
  137. * @param {string[]} channels
  138. * @return {function(): void}
  139. */
  140. const subscriptionHeartbeat = channels => {
  141. const interval = 6 * 60;
  142. const tellSubscribed = () => {
  143. channels.forEach(channel => redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval * 3));
  144. };
  145. tellSubscribed();
  146. const heartbeat = setInterval(tellSubscribed, interval * 1000);
  147. return () => {
  148. clearInterval(heartbeat);
  149. };
  150. };
  151. /**
  152. * @param {string} channel
  153. * @param {function(string): void} callback
  154. */
  155. const subscribe = (channel, callback) => {
  156. log.silly(`Adding listener for ${channel}`);
  157. subs[channel] = subs[channel] || [];
  158. if (subs[channel].length === 0) {
  159. log.verbose(`Subscribe ${channel}`);
  160. redisSubscribeClient.subscribe(channel);
  161. }
  162. subs[channel].push(callback);
  163. };
  164. /**
  165. * @param {string} channel
  166. * @param {function(string): void} callback
  167. */
  168. const unsubscribe = (channel, callback) => {
  169. log.silly(`Removing listener for ${channel}`);
  170. if (!subs[channel]) {
  171. return;
  172. }
  173. subs[channel] = subs[channel].filter(item => item !== callback);
  174. if (subs[channel].length === 0) {
  175. log.verbose(`Unsubscribe ${channel}`);
  176. redisSubscribeClient.unsubscribe(channel);
  177. delete subs[channel];
  178. }
  179. };
  180. const FALSE_VALUES = [
  181. false,
  182. 0,
  183. "0",
  184. "f",
  185. "F",
  186. "false",
  187. "FALSE",
  188. "off",
  189. "OFF"
  190. ];
  191. /**
  192. * @param {any} value
  193. * @return {boolean}
  194. */
  195. const isTruthy = value =>
  196. value && !FALSE_VALUES.includes(value);
  197. /**
  198. * @param {any} req
  199. * @param {any} res
  200. * @param {function(Error=): void}
  201. */
  202. const allowCrossDomain = (req, res, next) => {
  203. res.header('Access-Control-Allow-Origin', '*');
  204. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  205. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  206. next();
  207. };
  208. /**
  209. * @param {any} req
  210. * @param {any} res
  211. * @param {function(Error=): void}
  212. */
  213. const setRequestId = (req, res, next) => {
  214. req.requestId = uuid.v4();
  215. res.header('X-Request-Id', req.requestId);
  216. next();
  217. };
  218. /**
  219. * @param {any} req
  220. * @param {any} res
  221. * @param {function(Error=): void}
  222. */
  223. const setRemoteAddress = (req, res, next) => {
  224. req.remoteAddress = req.connection.remoteAddress;
  225. next();
  226. };
  227. /**
  228. * @param {string} token
  229. * @param {any} req
  230. * @return {Promise.<void>}
  231. */
  232. const accountFromToken = (token, req) => new Promise((resolve, reject) => {
  233. pgPool.connect((err, client, done) => {
  234. if (err) {
  235. reject(err);
  236. return;
  237. }
  238. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.chosen_languages, oauth_access_tokens.scopes, devices.device_id FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id LEFT OUTER JOIN devices ON oauth_access_tokens.id = devices.access_token_id WHERE oauth_access_tokens.token = $1 AND oauth_access_tokens.revoked_at IS NULL LIMIT 1', [token], (err, result) => {
  239. done();
  240. if (err) {
  241. reject(err);
  242. return;
  243. }
  244. if (result.rows.length === 0) {
  245. err = new Error('Invalid access token');
  246. err.status = 401;
  247. reject(err);
  248. return;
  249. }
  250. req.scopes = result.rows[0].scopes.split(' ');
  251. req.accountId = result.rows[0].account_id;
  252. req.chosenLanguages = result.rows[0].chosen_languages;
  253. req.allowNotifications = req.scopes.some(scope => ['read', 'read:notifications'].includes(scope));
  254. req.deviceId = result.rows[0].device_id;
  255. resolve();
  256. });
  257. });
  258. });
  259. /**
  260. * @param {any} req
  261. * @param {boolean=} required
  262. * @return {Promise.<void>}
  263. */
  264. const accountFromRequest = (req, required = true) => new Promise((resolve, reject) => {
  265. const authorization = req.headers.authorization;
  266. const location = url.parse(req.url, true);
  267. const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
  268. if (!authorization && !accessToken) {
  269. if (required) {
  270. const err = new Error('Missing access token');
  271. err.status = 401;
  272. reject(err);
  273. return;
  274. } else {
  275. resolve();
  276. return;
  277. }
  278. }
  279. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  280. resolve(accountFromToken(token, req));
  281. });
  282. /**
  283. * @param {any} req
  284. * @return {string}
  285. */
  286. const channelNameFromPath = req => {
  287. const { path, query } = req;
  288. const onlyMedia = isTruthy(query.only_media);
  289. switch(path) {
  290. case '/api/v1/streaming/user':
  291. return 'user';
  292. case '/api/v1/streaming/user/notification':
  293. return 'user:notification';
  294. case '/api/v1/streaming/public':
  295. return onlyMedia ? 'public:media' : 'public';
  296. case '/api/v1/streaming/public/local':
  297. return onlyMedia ? 'public:local:media' : 'public:local';
  298. case '/api/v1/streaming/public/remote':
  299. return onlyMedia ? 'public:remote:media' : 'public:remote';
  300. case '/api/v1/streaming/hashtag':
  301. return 'hashtag';
  302. case '/api/v1/streaming/hashtag/local':
  303. return 'hashtag:local';
  304. case '/api/v1/streaming/direct':
  305. return 'direct';
  306. case '/api/v1/streaming/list':
  307. return 'list';
  308. }
  309. };
  310. const PUBLIC_CHANNELS = [
  311. 'public',
  312. 'public:media',
  313. 'public:local',
  314. 'public:local:media',
  315. 'public:remote',
  316. 'public:remote:media',
  317. 'hashtag',
  318. 'hashtag:local',
  319. ];
  320. /**
  321. * @param {any} req
  322. * @param {string} channelName
  323. * @return {Promise.<void>}
  324. */
  325. const checkScopes = (req, channelName) => new Promise((resolve, reject) => {
  326. log.silly(req.requestId, `Checking OAuth scopes for ${channelName}`);
  327. // When accessing public channels, no scopes are needed
  328. if (PUBLIC_CHANNELS.includes(channelName)) {
  329. resolve();
  330. return;
  331. }
  332. // The `read` scope has the highest priority, if the token has it
  333. // then it can access all streams
  334. const requiredScopes = ['read'];
  335. // When accessing specifically the notifications stream,
  336. // we need a read:notifications, while in all other cases,
  337. // we can allow access with read:statuses. Mind that the
  338. // user stream will not contain notifications unless
  339. // the token has either read or read:notifications scope
  340. // as well, this is handled separately.
  341. if (channelName === 'user:notification') {
  342. requiredScopes.push('read:notifications');
  343. } else {
  344. requiredScopes.push('read:statuses');
  345. }
  346. if (requiredScopes.some(requiredScope => req.scopes.includes(requiredScope))) {
  347. resolve();
  348. return;
  349. }
  350. const err = new Error('Access token does not cover required scopes');
  351. err.status = 401;
  352. reject(err);
  353. });
  354. /**
  355. * @param {any} info
  356. * @param {function(boolean, number, string): void} callback
  357. */
  358. const wsVerifyClient = (info, callback) => {
  359. // When verifying the websockets connection, we no longer pre-emptively
  360. // check OAuth scopes and drop the connection if they're missing. We only
  361. // drop the connection if access without token is not allowed by environment
  362. // variables. OAuth scope checks are moved to the point of subscription
  363. // to a specific stream.
  364. accountFromRequest(info.req, alwaysRequireAuth).then(() => {
  365. callback(true, undefined, undefined);
  366. }).catch(err => {
  367. log.error(info.req.requestId, err.toString());
  368. callback(false, 401, 'Unauthorized');
  369. });
  370. };
  371. /**
  372. * @param {any} req
  373. * @param {any} res
  374. * @param {function(Error=): void} next
  375. */
  376. const authenticationMiddleware = (req, res, next) => {
  377. if (req.method === 'OPTIONS') {
  378. next();
  379. return;
  380. }
  381. accountFromRequest(req, alwaysRequireAuth).then(() => checkScopes(req, channelNameFromPath(req))).then(() => {
  382. next();
  383. }).catch(err => {
  384. next(err);
  385. });
  386. };
  387. /**
  388. * @param {Error} err
  389. * @param {any} req
  390. * @param {any} res
  391. * @param {function(Error=): void} next
  392. */
  393. const errorMiddleware = (err, req, res, next) => {
  394. log.error(req.requestId, err.toString());
  395. if (res.headersSent) {
  396. return next(err);
  397. }
  398. res.writeHead(err.status || 500, { 'Content-Type': 'application/json' });
  399. res.end(JSON.stringify({ error: err.status ? err.toString() : 'An unexpected error occurred' }));
  400. };
  401. /**
  402. * @param {array}
  403. * @param {number=} shift
  404. * @return {string}
  405. */
  406. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  407. /**
  408. * @param {string} listId
  409. * @param {any} req
  410. * @return {Promise.<void>}
  411. */
  412. const authorizeListAccess = (listId, req) => new Promise((resolve, reject) => {
  413. const { accountId } = req;
  414. pgPool.connect((err, client, done) => {
  415. if (err) {
  416. reject();
  417. return;
  418. }
  419. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [listId], (err, result) => {
  420. done();
  421. if (err || result.rows.length === 0 || result.rows[0].account_id !== accountId) {
  422. reject();
  423. return;
  424. }
  425. resolve();
  426. });
  427. });
  428. });
  429. /**
  430. * @param {string[]} ids
  431. * @param {any} req
  432. * @param {function(string, string): void} output
  433. * @param {function(string[], function(string): void): void} attachCloseHandler
  434. * @param {boolean=} needsFiltering
  435. * @param {boolean=} notificationOnly
  436. * @return {function(string): void}
  437. */
  438. const streamFrom = (ids, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  439. const accountId = req.accountId || req.remoteAddress;
  440. const streamType = notificationOnly ? ' (notification)' : '';
  441. log.verbose(req.requestId, `Starting stream from ${ids.join(', ')} for ${accountId}${streamType}`);
  442. const listener = message => {
  443. const json = parseJSON(message);
  444. if (!json) return;
  445. const { event, payload, queued_at } = json;
  446. const transmit = () => {
  447. const now = new Date().getTime();
  448. const delta = now - queued_at;
  449. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  450. log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  451. output(event, encodedPayload);
  452. };
  453. if (notificationOnly && event !== 'notification') {
  454. return;
  455. }
  456. if (event === 'notification' && !req.allowNotifications) {
  457. return;
  458. }
  459. // Only messages that may require filtering are statuses, since notifications
  460. // are already personalized and deletes do not matter
  461. if (!needsFiltering || event !== 'update') {
  462. transmit();
  463. return;
  464. }
  465. const unpackedPayload = payload;
  466. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  467. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  468. if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
  469. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  470. return;
  471. }
  472. // When the account is not logged in, it is not necessary to confirm the block or mute
  473. if (!req.accountId) {
  474. transmit();
  475. return;
  476. }
  477. pgPool.connect((err, client, done) => {
  478. if (err) {
  479. log.error(err);
  480. return;
  481. }
  482. const queries = [
  483. client.query(`SELECT 1 FROM blocks WHERE (account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})) OR (account_id = $2 AND target_account_id = $1) UNION SELECT 1 FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})`, [req.accountId, unpackedPayload.account.id].concat(targetAccountIds)),
  484. ];
  485. if (accountDomain) {
  486. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  487. }
  488. Promise.all(queries).then(values => {
  489. done();
  490. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  491. return;
  492. }
  493. transmit();
  494. }).catch(err => {
  495. done();
  496. log.error(err);
  497. });
  498. });
  499. };
  500. ids.forEach(id => {
  501. subscribe(`${redisPrefix}${id}`, listener);
  502. });
  503. if (attachCloseHandler) {
  504. attachCloseHandler(ids.map(id => `${redisPrefix}${id}`), listener);
  505. }
  506. return listener;
  507. };
  508. /**
  509. * @param {any} req
  510. * @param {any} res
  511. * @return {function(string, string): void}
  512. */
  513. const streamToHttp = (req, res) => {
  514. const accountId = req.accountId || req.remoteAddress;
  515. res.setHeader('Content-Type', 'text/event-stream');
  516. res.setHeader('Cache-Control', 'no-store');
  517. res.setHeader('Transfer-Encoding', 'chunked');
  518. res.write(':)\n');
  519. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  520. req.on('close', () => {
  521. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  522. clearInterval(heartbeat);
  523. });
  524. return (event, payload) => {
  525. res.write(`event: ${event}\n`);
  526. res.write(`data: ${payload}\n\n`);
  527. };
  528. };
  529. /**
  530. * @param {any} req
  531. * @param {function(): void} [closeHandler]
  532. * @return {function(string[], function(string): void)}
  533. */
  534. const streamHttpEnd = (req, closeHandler = undefined) => (ids, listener) => {
  535. req.on('close', () => {
  536. ids.forEach(id => {
  537. unsubscribe(id, listener);
  538. });
  539. if (closeHandler) {
  540. closeHandler();
  541. }
  542. });
  543. };
  544. /**
  545. * @param {any} req
  546. * @param {any} ws
  547. * @param {string[]} streamName
  548. * @return {function(string, string): void}
  549. */
  550. const streamToWs = (req, ws, streamName) => (event, payload) => {
  551. if (ws.readyState !== ws.OPEN) {
  552. log.error(req.requestId, 'Tried writing to closed socket');
  553. return;
  554. }
  555. ws.send(JSON.stringify({ stream: streamName, event, payload }));
  556. };
  557. /**
  558. * @param {any} res
  559. */
  560. const httpNotFound = res => {
  561. res.writeHead(404, { 'Content-Type': 'application/json' });
  562. res.end(JSON.stringify({ error: 'Not found' }));
  563. };
  564. app.use(setRequestId);
  565. app.use(setRemoteAddress);
  566. app.use(allowCrossDomain);
  567. app.get('/api/v1/streaming/health', (req, res) => {
  568. res.writeHead(200, { 'Content-Type': 'text/plain' });
  569. res.end('OK');
  570. });
  571. app.use(authenticationMiddleware);
  572. app.use(errorMiddleware);
  573. app.get('/api/v1/streaming/*', (req, res) => {
  574. channelNameToIds(req, channelNameFromPath(req), req.query).then(({ channelIds, options }) => {
  575. const onSend = streamToHttp(req, res);
  576. const onEnd = streamHttpEnd(req, subscriptionHeartbeat(channelIds));
  577. streamFrom(channelIds, req, onSend, onEnd, options.needsFiltering, options.notificationOnly);
  578. }).catch(err => {
  579. log.verbose(req.requestId, 'Subscription error:', err.toString());
  580. httpNotFound(res);
  581. });
  582. });
  583. const wss = new WebSocketServer({ server, verifyClient: wsVerifyClient });
  584. /**
  585. * @typedef StreamParams
  586. * @property {string} [tag]
  587. * @property {string} [list]
  588. * @property {string} [only_media]
  589. */
  590. /**
  591. * @param {any} req
  592. * @param {string} name
  593. * @param {StreamParams} params
  594. * @return {Promise.<{ channelIds: string[], options: { needsFiltering: boolean, notificationOnly: boolean } }>}
  595. */
  596. const channelNameToIds = (req, name, params) => new Promise((resolve, reject) => {
  597. switch(name) {
  598. case 'user':
  599. resolve({
  600. channelIds: req.deviceId ? [`timeline:${req.accountId}`, `timeline:${req.accountId}:${req.deviceId}`] : [`timeline:${req.accountId}`],
  601. options: { needsFiltering: false, notificationOnly: false },
  602. });
  603. break;
  604. case 'user:notification':
  605. resolve({
  606. channelIds: [`timeline:${req.accountId}`],
  607. options: { needsFiltering: false, notificationOnly: true },
  608. });
  609. break;
  610. case 'public':
  611. resolve({
  612. channelIds: ['timeline:public'],
  613. options: { needsFiltering: true, notificationOnly: false },
  614. });
  615. break;
  616. case 'public:local':
  617. resolve({
  618. channelIds: ['timeline:public:local'],
  619. options: { needsFiltering: true, notificationOnly: false },
  620. });
  621. break;
  622. case 'public:remote':
  623. resolve({
  624. channelIds: ['timeline:public:remote'],
  625. options: { needsFiltering: true, notificationOnly: false },
  626. });
  627. break;
  628. case 'public:media':
  629. resolve({
  630. channelIds: ['timeline:public:media'],
  631. options: { needsFiltering: true, notificationOnly: false },
  632. });
  633. break;
  634. case 'public:local:media':
  635. resolve({
  636. channelIds: ['timeline:public:local:media'],
  637. options: { needsFiltering: true, notificationOnly: false },
  638. });
  639. break;
  640. case 'public:remote:media':
  641. resolve({
  642. channelIds: ['timeline:public:remote:media'],
  643. options: { needsFiltering: true, notificationOnly: false },
  644. });
  645. break;
  646. case 'direct':
  647. resolve({
  648. channelIds: [`timeline:direct:${req.accountId}`],
  649. options: { needsFiltering: false, notificationOnly: false },
  650. });
  651. break;
  652. case 'hashtag':
  653. if (!params.tag || params.tag.length === 0) {
  654. reject('No tag for stream provided');
  655. } else {
  656. resolve({
  657. channelIds: [`timeline:hashtag:${params.tag.toLowerCase()}`],
  658. options: { needsFiltering: true, notificationOnly: false },
  659. });
  660. }
  661. break;
  662. case 'hashtag:local':
  663. if (!params.tag || params.tag.length === 0) {
  664. reject('No tag for stream provided');
  665. } else {
  666. resolve({
  667. channelIds: [`timeline:hashtag:${params.tag.toLowerCase()}:local`],
  668. options: { needsFiltering: true, notificationOnly: false },
  669. });
  670. }
  671. break;
  672. case 'list':
  673. authorizeListAccess(params.list, req).then(() => {
  674. resolve({
  675. channelIds: [`timeline:list:${params.list}`],
  676. options: { needsFiltering: false, notificationOnly: false },
  677. });
  678. }).catch(() => {
  679. reject('Not authorized to stream this list');
  680. });
  681. break;
  682. default:
  683. reject('Unknown stream type');
  684. }
  685. });
  686. /**
  687. * @param {string} channelName
  688. * @param {StreamParams} params
  689. * @return {string[]}
  690. */
  691. const streamNameFromChannelName = (channelName, params) => {
  692. if (channelName === 'list') {
  693. return [channelName, params.list];
  694. } else if (['hashtag', 'hashtag:local'].includes(channelName)) {
  695. return [channelName, params.tag];
  696. } else {
  697. return [channelName];
  698. }
  699. };
  700. /**
  701. * @typedef WebSocketSession
  702. * @property {any} socket
  703. * @property {any} request
  704. * @property {Object.<string, { listener: function(string): void, stopHeartbeat: function(): void }>} subscriptions
  705. */
  706. /**
  707. * @param {WebSocketSession} session
  708. * @param {string} channelName
  709. * @param {StreamParams} params
  710. */
  711. const subscribeWebsocketToChannel = ({ socket, request, subscriptions }, channelName, params) =>
  712. checkScopes(request, channelName).then(() => channelNameToIds(request, channelName, params)).then(({ channelIds, options }) => {
  713. if (subscriptions[channelIds.join(';')]) {
  714. return;
  715. }
  716. const onSend = streamToWs(request, socket, streamNameFromChannelName(channelName, params));
  717. const stopHeartbeat = subscriptionHeartbeat(channelIds);
  718. const listener = streamFrom(channelIds, request, onSend, undefined, options.needsFiltering, options.notificationOnly);
  719. subscriptions[channelIds.join(';')] = {
  720. listener,
  721. stopHeartbeat,
  722. };
  723. }).catch(err => {
  724. log.verbose(request.requestId, 'Subscription error:', err.toString());
  725. socket.send(JSON.stringify({ error: err.toString() }));
  726. });
  727. /**
  728. * @param {WebSocketSession} session
  729. * @param {string} channelName
  730. * @param {StreamParams} params
  731. */
  732. const unsubscribeWebsocketFromChannel = ({ socket, request, subscriptions }, channelName, params) =>
  733. channelNameToIds(request, channelName, params).then(({ channelIds }) => {
  734. log.verbose(request.requestId, `Ending stream from ${channelIds.join(', ')} for ${request.accountId}`);
  735. const subscription = subscriptions[channelIds.join(';')];
  736. if (!subscription) {
  737. return;
  738. }
  739. const { listener, stopHeartbeat } = subscription;
  740. channelIds.forEach(channelId => {
  741. unsubscribe(`${redisPrefix}${channelId}`, listener);
  742. });
  743. stopHeartbeat();
  744. delete subscriptions[channelIds.join(';')];
  745. }).catch(err => {
  746. log.verbose(request.requestId, 'Unsubscription error:', err);
  747. socket.send(JSON.stringify({ error: err.toString() }));
  748. });
  749. /**
  750. * @param {string|string[]} arrayOrString
  751. * @return {string}
  752. */
  753. const firstParam = arrayOrString => {
  754. if (Array.isArray(arrayOrString)) {
  755. return arrayOrString[0];
  756. } else {
  757. return arrayOrString;
  758. }
  759. };
  760. wss.on('connection', (ws, req) => {
  761. const location = url.parse(req.url, true);
  762. req.requestId = uuid.v4();
  763. req.remoteAddress = ws._socket.remoteAddress;
  764. /**
  765. * @type {WebSocketSession}
  766. */
  767. const session = {
  768. socket: ws,
  769. request: req,
  770. subscriptions: {},
  771. };
  772. const onEnd = () => {
  773. const keys = Object.keys(session.subscriptions);
  774. keys.forEach(channelIds => {
  775. const { listener, stopHeartbeat } = session.subscriptions[channelIds];
  776. channelIds.split(';').forEach(channelId => {
  777. unsubscribe(`${redisPrefix}${channelId}`, listener);
  778. });
  779. stopHeartbeat();
  780. });
  781. };
  782. ws.on('close', onEnd);
  783. ws.on('error', onEnd);
  784. ws.on('message', data => {
  785. const json = parseJSON(data);
  786. if (!json) return;
  787. const { type, stream, ...params } = json;
  788. if (type === 'subscribe') {
  789. subscribeWebsocketToChannel(session, firstParam(stream), params);
  790. } else if (type === 'unsubscribe') {
  791. unsubscribeWebsocketFromChannel(session, firstParam(stream), params)
  792. } else {
  793. // Unknown action type
  794. }
  795. });
  796. if (location.query.stream) {
  797. subscribeWebsocketToChannel(session, firstParam(location.query.stream), location.query);
  798. }
  799. });
  800. wss.startAutoPing(30000);
  801. attachServerWithConfig(server, address => {
  802. log.info(`Worker ${workerId} now listening on ${address}`);
  803. });
  804. const onExit = () => {
  805. log.info(`Worker ${workerId} exiting, bye bye`);
  806. server.close();
  807. process.exit(0);
  808. };
  809. const onError = (err) => {
  810. log.error(err);
  811. server.close();
  812. process.exit(0);
  813. };
  814. process.on('SIGINT', onExit);
  815. process.on('SIGTERM', onExit);
  816. process.on('exit', onExit);
  817. process.on('uncaughtException', onError);
  818. };
  819. /**
  820. * @param {any} server
  821. * @param {function(string): void} [onSuccess]
  822. */
  823. const attachServerWithConfig = (server, onSuccess) => {
  824. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  825. server.listen(process.env.SOCKET || process.env.PORT, () => {
  826. if (onSuccess) {
  827. fs.chmodSync(server.address(), 0o666);
  828. onSuccess(server.address());
  829. }
  830. });
  831. } else {
  832. server.listen(+process.env.PORT || 4000, process.env.BIND || '127.0.0.1', () => {
  833. if (onSuccess) {
  834. onSuccess(`${server.address().address}:${server.address().port}`);
  835. }
  836. });
  837. }
  838. };
  839. /**
  840. * @param {function(Error=): void} onSuccess
  841. */
  842. const onPortAvailable = onSuccess => {
  843. const testServer = http.createServer();
  844. testServer.once('error', err => {
  845. onSuccess(err);
  846. });
  847. testServer.once('listening', () => {
  848. testServer.once('close', () => onSuccess());
  849. testServer.close();
  850. });
  851. attachServerWithConfig(testServer);
  852. };
  853. onPortAvailable(err => {
  854. if (err) {
  855. log.error('Could not start server, the port or socket is in use');
  856. return;
  857. }
  858. throng({
  859. workers: numWorkers,
  860. lifetime: Infinity,
  861. start: startWorker,
  862. master: startMaster,
  863. });
  864. });