index.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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.id, 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.accessTokenId = result.rows[0].id;
  251. req.scopes = result.rows[0].scopes.split(' ');
  252. req.accountId = result.rows[0].account_id;
  253. req.chosenLanguages = result.rows[0].chosen_languages;
  254. req.allowNotifications = req.scopes.some(scope => ['read', 'read:notifications'].includes(scope));
  255. req.deviceId = result.rows[0].device_id;
  256. resolve();
  257. });
  258. });
  259. });
  260. /**
  261. * @param {any} req
  262. * @param {boolean=} required
  263. * @return {Promise.<void>}
  264. */
  265. const accountFromRequest = (req, required = true) => new Promise((resolve, reject) => {
  266. const authorization = req.headers.authorization;
  267. const location = url.parse(req.url, true);
  268. const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
  269. if (!authorization && !accessToken) {
  270. if (required) {
  271. const err = new Error('Missing access token');
  272. err.status = 401;
  273. reject(err);
  274. return;
  275. } else {
  276. resolve();
  277. return;
  278. }
  279. }
  280. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  281. resolve(accountFromToken(token, req));
  282. });
  283. /**
  284. * @param {any} req
  285. * @return {string}
  286. */
  287. const channelNameFromPath = req => {
  288. const { path, query } = req;
  289. const onlyMedia = isTruthy(query.only_media);
  290. switch(path) {
  291. case '/api/v1/streaming/user':
  292. return 'user';
  293. case '/api/v1/streaming/user/notification':
  294. return 'user:notification';
  295. case '/api/v1/streaming/public':
  296. return onlyMedia ? 'public:media' : 'public';
  297. case '/api/v1/streaming/public/local':
  298. return onlyMedia ? 'public:local:media' : 'public:local';
  299. case '/api/v1/streaming/public/remote':
  300. return onlyMedia ? 'public:remote:media' : 'public:remote';
  301. case '/api/v1/streaming/hashtag':
  302. return 'hashtag';
  303. case '/api/v1/streaming/hashtag/local':
  304. return 'hashtag:local';
  305. case '/api/v1/streaming/direct':
  306. return 'direct';
  307. case '/api/v1/streaming/list':
  308. return 'list';
  309. default:
  310. return undefined;
  311. }
  312. };
  313. const PUBLIC_CHANNELS = [
  314. 'public',
  315. 'public:media',
  316. 'public:local',
  317. 'public:local:media',
  318. 'public:remote',
  319. 'public:remote:media',
  320. 'hashtag',
  321. 'hashtag:local',
  322. ];
  323. /**
  324. * @param {any} req
  325. * @param {string} channelName
  326. * @return {Promise.<void>}
  327. */
  328. const checkScopes = (req, channelName) => new Promise((resolve, reject) => {
  329. log.silly(req.requestId, `Checking OAuth scopes for ${channelName}`);
  330. // When accessing public channels, no scopes are needed
  331. if (PUBLIC_CHANNELS.includes(channelName)) {
  332. resolve();
  333. return;
  334. }
  335. // The `read` scope has the highest priority, if the token has it
  336. // then it can access all streams
  337. const requiredScopes = ['read'];
  338. // When accessing specifically the notifications stream,
  339. // we need a read:notifications, while in all other cases,
  340. // we can allow access with read:statuses. Mind that the
  341. // user stream will not contain notifications unless
  342. // the token has either read or read:notifications scope
  343. // as well, this is handled separately.
  344. if (channelName === 'user:notification') {
  345. requiredScopes.push('read:notifications');
  346. } else {
  347. requiredScopes.push('read:statuses');
  348. }
  349. if (requiredScopes.some(requiredScope => req.scopes.includes(requiredScope))) {
  350. resolve();
  351. return;
  352. }
  353. const err = new Error('Access token does not cover required scopes');
  354. err.status = 401;
  355. reject(err);
  356. });
  357. /**
  358. * @param {any} info
  359. * @param {function(boolean, number, string): void} callback
  360. */
  361. const wsVerifyClient = (info, callback) => {
  362. // When verifying the websockets connection, we no longer pre-emptively
  363. // check OAuth scopes and drop the connection if they're missing. We only
  364. // drop the connection if access without token is not allowed by environment
  365. // variables. OAuth scope checks are moved to the point of subscription
  366. // to a specific stream.
  367. accountFromRequest(info.req, alwaysRequireAuth).then(() => {
  368. callback(true, undefined, undefined);
  369. }).catch(err => {
  370. log.error(info.req.requestId, err.toString());
  371. callback(false, 401, 'Unauthorized');
  372. });
  373. };
  374. /**
  375. * @typedef SystemMessageHandlers
  376. * @property {function(): void} onKill
  377. */
  378. /**
  379. * @param {any} req
  380. * @param {SystemMessageHandlers} eventHandlers
  381. * @return {function(string): void}
  382. */
  383. const createSystemMessageListener = (req, eventHandlers) => {
  384. return message => {
  385. const json = parseJSON(message);
  386. if (!json) return;
  387. const { event } = json;
  388. log.silly(req.requestId, `System message for ${req.accountId}: ${event}`);
  389. if (event === 'kill') {
  390. log.verbose(req.requestId, `Closing connection for ${req.accountId} due to expired access token`);
  391. eventHandlers.onKill();
  392. }
  393. };
  394. };
  395. /**
  396. * @param {any} req
  397. * @param {any} res
  398. */
  399. const subscribeHttpToSystemChannel = (req, res) => {
  400. const systemChannelId = `timeline:access_token:${req.accessTokenId}`;
  401. const listener = createSystemMessageListener(req, {
  402. onKill () {
  403. res.end();
  404. },
  405. });
  406. res.on('close', () => {
  407. unsubscribe(`${redisPrefix}${systemChannelId}`, listener);
  408. });
  409. subscribe(`${redisPrefix}${systemChannelId}`, listener);
  410. };
  411. /**
  412. * @param {any} req
  413. * @param {any} res
  414. * @param {function(Error=): void} next
  415. */
  416. const authenticationMiddleware = (req, res, next) => {
  417. if (req.method === 'OPTIONS') {
  418. next();
  419. return;
  420. }
  421. accountFromRequest(req, alwaysRequireAuth).then(() => checkScopes(req, channelNameFromPath(req))).then(() => {
  422. subscribeHttpToSystemChannel(req, res);
  423. }).then(() => {
  424. next();
  425. }).catch(err => {
  426. next(err);
  427. });
  428. };
  429. /**
  430. * @param {Error} err
  431. * @param {any} req
  432. * @param {any} res
  433. * @param {function(Error=): void} next
  434. */
  435. const errorMiddleware = (err, req, res, next) => {
  436. log.error(req.requestId, err.toString());
  437. if (res.headersSent) {
  438. next(err);
  439. return;
  440. }
  441. res.writeHead(err.status || 500, { 'Content-Type': 'application/json' });
  442. res.end(JSON.stringify({ error: err.status ? err.toString() : 'An unexpected error occurred' }));
  443. };
  444. /**
  445. * @param {array}
  446. * @param {number=} shift
  447. * @return {string}
  448. */
  449. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  450. /**
  451. * @param {string} listId
  452. * @param {any} req
  453. * @return {Promise.<void>}
  454. */
  455. const authorizeListAccess = (listId, req) => new Promise((resolve, reject) => {
  456. const { accountId } = req;
  457. pgPool.connect((err, client, done) => {
  458. if (err) {
  459. reject();
  460. return;
  461. }
  462. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [listId], (err, result) => {
  463. done();
  464. if (err || result.rows.length === 0 || result.rows[0].account_id !== accountId) {
  465. reject();
  466. return;
  467. }
  468. resolve();
  469. });
  470. });
  471. });
  472. /**
  473. * @param {string[]} ids
  474. * @param {any} req
  475. * @param {function(string, string): void} output
  476. * @param {function(string[], function(string): void): void} attachCloseHandler
  477. * @param {boolean=} needsFiltering
  478. * @param {boolean=} notificationOnly
  479. * @return {function(string): void}
  480. */
  481. const streamFrom = (ids, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  482. const accountId = req.accountId || req.remoteAddress;
  483. const streamType = notificationOnly ? ' (notification)' : '';
  484. log.verbose(req.requestId, `Starting stream from ${ids.join(', ')} for ${accountId}${streamType}`);
  485. const listener = message => {
  486. const json = parseJSON(message);
  487. if (!json) return;
  488. const { event, payload, queued_at } = json;
  489. const transmit = () => {
  490. const now = new Date().getTime();
  491. const delta = now - queued_at;
  492. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  493. log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  494. output(event, encodedPayload);
  495. };
  496. if (notificationOnly && event !== 'notification') {
  497. return;
  498. }
  499. if (event === 'notification' && !req.allowNotifications) {
  500. return;
  501. }
  502. // Only messages that may require filtering are statuses, since notifications
  503. // are already personalized and deletes do not matter
  504. if (!needsFiltering || event !== 'update') {
  505. transmit();
  506. return;
  507. }
  508. const unpackedPayload = payload;
  509. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  510. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  511. if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
  512. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  513. return;
  514. }
  515. // When the account is not logged in, it is not necessary to confirm the block or mute
  516. if (!req.accountId) {
  517. transmit();
  518. return;
  519. }
  520. pgPool.connect((err, client, done) => {
  521. if (err) {
  522. log.error(err);
  523. return;
  524. }
  525. const queries = [
  526. 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)),
  527. ];
  528. if (accountDomain) {
  529. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  530. }
  531. Promise.all(queries).then(values => {
  532. done();
  533. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  534. return;
  535. }
  536. transmit();
  537. }).catch(err => {
  538. done();
  539. log.error(err);
  540. });
  541. });
  542. };
  543. ids.forEach(id => {
  544. subscribe(`${redisPrefix}${id}`, listener);
  545. });
  546. if (attachCloseHandler) {
  547. attachCloseHandler(ids.map(id => `${redisPrefix}${id}`), listener);
  548. }
  549. return listener;
  550. };
  551. /**
  552. * @param {any} req
  553. * @param {any} res
  554. * @return {function(string, string): void}
  555. */
  556. const streamToHttp = (req, res) => {
  557. const accountId = req.accountId || req.remoteAddress;
  558. res.setHeader('Content-Type', 'text/event-stream');
  559. res.setHeader('Cache-Control', 'no-store');
  560. res.setHeader('Transfer-Encoding', 'chunked');
  561. res.write(':)\n');
  562. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  563. req.on('close', () => {
  564. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  565. clearInterval(heartbeat);
  566. });
  567. return (event, payload) => {
  568. res.write(`event: ${event}\n`);
  569. res.write(`data: ${payload}\n\n`);
  570. };
  571. };
  572. /**
  573. * @param {any} req
  574. * @param {function(): void} [closeHandler]
  575. * @return {function(string[], function(string): void)}
  576. */
  577. const streamHttpEnd = (req, closeHandler = undefined) => (ids, listener) => {
  578. req.on('close', () => {
  579. ids.forEach(id => {
  580. unsubscribe(id, listener);
  581. });
  582. if (closeHandler) {
  583. closeHandler();
  584. }
  585. });
  586. };
  587. /**
  588. * @param {any} req
  589. * @param {any} ws
  590. * @param {string[]} streamName
  591. * @return {function(string, string): void}
  592. */
  593. const streamToWs = (req, ws, streamName) => (event, payload) => {
  594. if (ws.readyState !== ws.OPEN) {
  595. log.error(req.requestId, 'Tried writing to closed socket');
  596. return;
  597. }
  598. ws.send(JSON.stringify({ stream: streamName, event, payload }));
  599. };
  600. /**
  601. * @param {any} res
  602. */
  603. const httpNotFound = res => {
  604. res.writeHead(404, { 'Content-Type': 'application/json' });
  605. res.end(JSON.stringify({ error: 'Not found' }));
  606. };
  607. app.use(setRequestId);
  608. app.use(setRemoteAddress);
  609. app.use(allowCrossDomain);
  610. app.get('/api/v1/streaming/health', (req, res) => {
  611. res.writeHead(200, { 'Content-Type': 'text/plain' });
  612. res.end('OK');
  613. });
  614. app.use(authenticationMiddleware);
  615. app.use(errorMiddleware);
  616. app.get('/api/v1/streaming/*', (req, res) => {
  617. channelNameToIds(req, channelNameFromPath(req), req.query).then(({ channelIds, options }) => {
  618. const onSend = streamToHttp(req, res);
  619. const onEnd = streamHttpEnd(req, subscriptionHeartbeat(channelIds));
  620. streamFrom(channelIds, req, onSend, onEnd, options.needsFiltering, options.notificationOnly);
  621. }).catch(err => {
  622. log.verbose(req.requestId, 'Subscription error:', err.toString());
  623. httpNotFound(res);
  624. });
  625. });
  626. const wss = new WebSocketServer({ server, verifyClient: wsVerifyClient });
  627. /**
  628. * @typedef StreamParams
  629. * @property {string} [tag]
  630. * @property {string} [list]
  631. * @property {string} [only_media]
  632. */
  633. /**
  634. * @param {any} req
  635. * @param {string} name
  636. * @param {StreamParams} params
  637. * @return {Promise.<{ channelIds: string[], options: { needsFiltering: boolean, notificationOnly: boolean } }>}
  638. */
  639. const channelNameToIds = (req, name, params) => new Promise((resolve, reject) => {
  640. switch(name) {
  641. case 'user':
  642. resolve({
  643. channelIds: req.deviceId ? [`timeline:${req.accountId}`, `timeline:${req.accountId}:${req.deviceId}`] : [`timeline:${req.accountId}`],
  644. options: { needsFiltering: false, notificationOnly: false },
  645. });
  646. break;
  647. case 'user:notification':
  648. resolve({
  649. channelIds: [`timeline:${req.accountId}`],
  650. options: { needsFiltering: false, notificationOnly: true },
  651. });
  652. break;
  653. case 'public':
  654. resolve({
  655. channelIds: ['timeline:public'],
  656. options: { needsFiltering: true, notificationOnly: false },
  657. });
  658. break;
  659. case 'public:local':
  660. resolve({
  661. channelIds: ['timeline:public:local'],
  662. options: { needsFiltering: true, notificationOnly: false },
  663. });
  664. break;
  665. case 'public:remote':
  666. resolve({
  667. channelIds: ['timeline:public:remote'],
  668. options: { needsFiltering: true, notificationOnly: false },
  669. });
  670. break;
  671. case 'public:media':
  672. resolve({
  673. channelIds: ['timeline:public:media'],
  674. options: { needsFiltering: true, notificationOnly: false },
  675. });
  676. break;
  677. case 'public:local:media':
  678. resolve({
  679. channelIds: ['timeline:public:local:media'],
  680. options: { needsFiltering: true, notificationOnly: false },
  681. });
  682. break;
  683. case 'public:remote:media':
  684. resolve({
  685. channelIds: ['timeline:public:remote:media'],
  686. options: { needsFiltering: true, notificationOnly: false },
  687. });
  688. break;
  689. case 'direct':
  690. resolve({
  691. channelIds: [`timeline:direct:${req.accountId}`],
  692. options: { needsFiltering: false, notificationOnly: false },
  693. });
  694. break;
  695. case 'hashtag':
  696. if (!params.tag || params.tag.length === 0) {
  697. reject('No tag for stream provided');
  698. } else {
  699. resolve({
  700. channelIds: [`timeline:hashtag:${params.tag.toLowerCase()}`],
  701. options: { needsFiltering: true, notificationOnly: false },
  702. });
  703. }
  704. break;
  705. case 'hashtag:local':
  706. if (!params.tag || params.tag.length === 0) {
  707. reject('No tag for stream provided');
  708. } else {
  709. resolve({
  710. channelIds: [`timeline:hashtag:${params.tag.toLowerCase()}:local`],
  711. options: { needsFiltering: true, notificationOnly: false },
  712. });
  713. }
  714. break;
  715. case 'list':
  716. authorizeListAccess(params.list, req).then(() => {
  717. resolve({
  718. channelIds: [`timeline:list:${params.list}`],
  719. options: { needsFiltering: false, notificationOnly: false },
  720. });
  721. }).catch(() => {
  722. reject('Not authorized to stream this list');
  723. });
  724. break;
  725. default:
  726. reject('Unknown stream type');
  727. }
  728. });
  729. /**
  730. * @param {string} channelName
  731. * @param {StreamParams} params
  732. * @return {string[]}
  733. */
  734. const streamNameFromChannelName = (channelName, params) => {
  735. if (channelName === 'list') {
  736. return [channelName, params.list];
  737. } else if (['hashtag', 'hashtag:local'].includes(channelName)) {
  738. return [channelName, params.tag];
  739. } else {
  740. return [channelName];
  741. }
  742. };
  743. /**
  744. * @typedef WebSocketSession
  745. * @property {any} socket
  746. * @property {any} request
  747. * @property {Object.<string, { listener: function(string): void, stopHeartbeat: function(): void }>} subscriptions
  748. */
  749. /**
  750. * @param {WebSocketSession} session
  751. * @param {string} channelName
  752. * @param {StreamParams} params
  753. */
  754. const subscribeWebsocketToChannel = ({ socket, request, subscriptions }, channelName, params) =>
  755. checkScopes(request, channelName).then(() => channelNameToIds(request, channelName, params)).then(({ channelIds, options }) => {
  756. if (subscriptions[channelIds.join(';')]) {
  757. return;
  758. }
  759. const onSend = streamToWs(request, socket, streamNameFromChannelName(channelName, params));
  760. const stopHeartbeat = subscriptionHeartbeat(channelIds);
  761. const listener = streamFrom(channelIds, request, onSend, undefined, options.needsFiltering, options.notificationOnly);
  762. subscriptions[channelIds.join(';')] = {
  763. listener,
  764. stopHeartbeat,
  765. };
  766. }).catch(err => {
  767. log.verbose(request.requestId, 'Subscription error:', err.toString());
  768. socket.send(JSON.stringify({ error: err.toString() }));
  769. });
  770. /**
  771. * @param {WebSocketSession} session
  772. * @param {string} channelName
  773. * @param {StreamParams} params
  774. */
  775. const unsubscribeWebsocketFromChannel = ({ socket, request, subscriptions }, channelName, params) =>
  776. channelNameToIds(request, channelName, params).then(({ channelIds }) => {
  777. log.verbose(request.requestId, `Ending stream from ${channelIds.join(', ')} for ${request.accountId}`);
  778. const subscription = subscriptions[channelIds.join(';')];
  779. if (!subscription) {
  780. return;
  781. }
  782. const { listener, stopHeartbeat } = subscription;
  783. channelIds.forEach(channelId => {
  784. unsubscribe(`${redisPrefix}${channelId}`, listener);
  785. });
  786. stopHeartbeat();
  787. delete subscriptions[channelIds.join(';')];
  788. }).catch(err => {
  789. log.verbose(request.requestId, 'Unsubscription error:', err);
  790. socket.send(JSON.stringify({ error: err.toString() }));
  791. });
  792. /**
  793. * @param {WebSocketSession} session
  794. */
  795. const subscribeWebsocketToSystemChannel = ({ socket, request, subscriptions }) => {
  796. const systemChannelId = `timeline:access_token:${request.accessTokenId}`;
  797. const listener = createSystemMessageListener(request, {
  798. onKill () {
  799. socket.close();
  800. },
  801. });
  802. subscribe(`${redisPrefix}${systemChannelId}`, listener);
  803. subscriptions[systemChannelId] = {
  804. listener,
  805. stopHeartbeat: () => {},
  806. };
  807. };
  808. /**
  809. * @param {string|string[]} arrayOrString
  810. * @return {string}
  811. */
  812. const firstParam = arrayOrString => {
  813. if (Array.isArray(arrayOrString)) {
  814. return arrayOrString[0];
  815. } else {
  816. return arrayOrString;
  817. }
  818. };
  819. wss.on('connection', (ws, req) => {
  820. const location = url.parse(req.url, true);
  821. req.requestId = uuid.v4();
  822. req.remoteAddress = ws._socket.remoteAddress;
  823. /**
  824. * @type {WebSocketSession}
  825. */
  826. const session = {
  827. socket: ws,
  828. request: req,
  829. subscriptions: {},
  830. };
  831. const onEnd = () => {
  832. const keys = Object.keys(session.subscriptions);
  833. keys.forEach(channelIds => {
  834. const { listener, stopHeartbeat } = session.subscriptions[channelIds];
  835. channelIds.split(';').forEach(channelId => {
  836. unsubscribe(`${redisPrefix}${channelId}`, listener);
  837. });
  838. stopHeartbeat();
  839. });
  840. };
  841. ws.on('close', onEnd);
  842. ws.on('error', onEnd);
  843. ws.on('message', data => {
  844. const json = parseJSON(data);
  845. if (!json) return;
  846. const { type, stream, ...params } = json;
  847. if (type === 'subscribe') {
  848. subscribeWebsocketToChannel(session, firstParam(stream), params);
  849. } else if (type === 'unsubscribe') {
  850. unsubscribeWebsocketFromChannel(session, firstParam(stream), params);
  851. } else {
  852. // Unknown action type
  853. }
  854. });
  855. subscribeWebsocketToSystemChannel(session);
  856. if (location.query.stream) {
  857. subscribeWebsocketToChannel(session, firstParam(location.query.stream), location.query);
  858. }
  859. });
  860. wss.startAutoPing(30000);
  861. attachServerWithConfig(server, address => {
  862. log.info(`Worker ${workerId} now listening on ${address}`);
  863. });
  864. const onExit = () => {
  865. log.info(`Worker ${workerId} exiting, bye bye`);
  866. server.close();
  867. process.exit(0);
  868. };
  869. const onError = (err) => {
  870. log.error(err);
  871. server.close();
  872. process.exit(0);
  873. };
  874. process.on('SIGINT', onExit);
  875. process.on('SIGTERM', onExit);
  876. process.on('exit', onExit);
  877. process.on('uncaughtException', onError);
  878. };
  879. /**
  880. * @param {any} server
  881. * @param {function(string): void} [onSuccess]
  882. */
  883. const attachServerWithConfig = (server, onSuccess) => {
  884. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  885. server.listen(process.env.SOCKET || process.env.PORT, () => {
  886. if (onSuccess) {
  887. fs.chmodSync(server.address(), 0o666);
  888. onSuccess(server.address());
  889. }
  890. });
  891. } else {
  892. server.listen(+process.env.PORT || 4000, process.env.BIND || '127.0.0.1', () => {
  893. if (onSuccess) {
  894. onSuccess(`${server.address().address}:${server.address().port}`);
  895. }
  896. });
  897. }
  898. };
  899. /**
  900. * @param {function(Error=): void} onSuccess
  901. */
  902. const onPortAvailable = onSuccess => {
  903. const testServer = http.createServer();
  904. testServer.once('error', err => {
  905. onSuccess(err);
  906. });
  907. testServer.once('listening', () => {
  908. testServer.once('close', () => onSuccess());
  909. testServer.close();
  910. });
  911. attachServerWithConfig(testServer);
  912. };
  913. onPortAvailable(err => {
  914. if (err) {
  915. log.error('Could not start server, the port or socket is in use');
  916. return;
  917. }
  918. throng({
  919. workers: numWorkers,
  920. lifetime: Infinity,
  921. start: startWorker,
  922. master: startMaster,
  923. });
  924. });