index.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 uuid = require('uuid');
  12. const fs = require('fs');
  13. const WebSocket = require('ws');
  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.warn(`Starting streaming API server master with ${numWorkers} workers`);
  82. };
  83. const startWorker = (workerId) => {
  84. log.warn(`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 WebSocket.Server({ 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. ws.isAlive = true;
  824. ws.on('pong', () => {
  825. ws.isAlive = true;
  826. });
  827. /**
  828. * @type {WebSocketSession}
  829. */
  830. const session = {
  831. socket: ws,
  832. request: req,
  833. subscriptions: {},
  834. };
  835. const onEnd = () => {
  836. const keys = Object.keys(session.subscriptions);
  837. keys.forEach(channelIds => {
  838. const { listener, stopHeartbeat } = session.subscriptions[channelIds];
  839. channelIds.split(';').forEach(channelId => {
  840. unsubscribe(`${redisPrefix}${channelId}`, listener);
  841. });
  842. stopHeartbeat();
  843. });
  844. };
  845. ws.on('close', onEnd);
  846. ws.on('error', onEnd);
  847. ws.on('message', data => {
  848. const json = parseJSON(data);
  849. if (!json) return;
  850. const { type, stream, ...params } = json;
  851. if (type === 'subscribe') {
  852. subscribeWebsocketToChannel(session, firstParam(stream), params);
  853. } else if (type === 'unsubscribe') {
  854. unsubscribeWebsocketFromChannel(session, firstParam(stream), params);
  855. } else {
  856. // Unknown action type
  857. }
  858. });
  859. subscribeWebsocketToSystemChannel(session);
  860. if (location.query.stream) {
  861. subscribeWebsocketToChannel(session, firstParam(location.query.stream), location.query);
  862. }
  863. });
  864. setInterval(() => {
  865. wss.clients.forEach(ws => {
  866. if (ws.isAlive === false) {
  867. ws.terminate();
  868. return;
  869. }
  870. ws.isAlive = false;
  871. ws.ping('', false);
  872. });
  873. }, 30000);
  874. attachServerWithConfig(server, address => {
  875. log.warn(`Worker ${workerId} now listening on ${address}`);
  876. });
  877. const onExit = () => {
  878. log.warn(`Worker ${workerId} exiting`);
  879. server.close();
  880. process.exit(0);
  881. };
  882. const onError = (err) => {
  883. log.error(err);
  884. server.close();
  885. process.exit(0);
  886. };
  887. process.on('SIGINT', onExit);
  888. process.on('SIGTERM', onExit);
  889. process.on('exit', onExit);
  890. process.on('uncaughtException', onError);
  891. };
  892. /**
  893. * @param {any} server
  894. * @param {function(string): void} [onSuccess]
  895. */
  896. const attachServerWithConfig = (server, onSuccess) => {
  897. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  898. server.listen(process.env.SOCKET || process.env.PORT, () => {
  899. if (onSuccess) {
  900. fs.chmodSync(server.address(), 0o666);
  901. onSuccess(server.address());
  902. }
  903. });
  904. } else {
  905. server.listen(+process.env.PORT || 4000, process.env.BIND || '127.0.0.1', () => {
  906. if (onSuccess) {
  907. onSuccess(`${server.address().address}:${server.address().port}`);
  908. }
  909. });
  910. }
  911. };
  912. /**
  913. * @param {function(Error=): void} onSuccess
  914. */
  915. const onPortAvailable = onSuccess => {
  916. const testServer = http.createServer();
  917. testServer.once('error', err => {
  918. onSuccess(err);
  919. });
  920. testServer.once('listening', () => {
  921. testServer.once('close', () => onSuccess());
  922. testServer.close();
  923. });
  924. attachServerWithConfig(testServer);
  925. };
  926. onPortAvailable(err => {
  927. if (err) {
  928. log.error('Could not start server, the port or socket is in use');
  929. return;
  930. }
  931. throng({
  932. workers: numWorkers,
  933. lifetime: Infinity,
  934. start: startWorker,
  935. master: startMaster,
  936. });
  937. });