index.js 31 KB

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