index.js 35 KB

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