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.

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