You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1152 lines
30 KiB

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