index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. const os = require('os');
  2. const throng = require('throng');
  3. const dotenv = require('dotenv');
  4. const express = require('express');
  5. const http = require('http');
  6. const redis = require('redis');
  7. const pg = require('pg');
  8. const log = require('npmlog');
  9. const url = require('url');
  10. const WebSocket = require('uws');
  11. const uuid = require('uuid');
  12. const env = process.env.NODE_ENV || 'development';
  13. dotenv.config({
  14. path: env === 'production' ? '.env.production' : '.env',
  15. });
  16. log.level = process.env.LOG_LEVEL || 'verbose';
  17. const dbUrlToConfig = (dbUrl) => {
  18. if (!dbUrl) {
  19. return {};
  20. }
  21. const params = url.parse(dbUrl);
  22. const config = {};
  23. if (params.auth) {
  24. [config.user, config.password] = params.auth.split(':');
  25. }
  26. if (params.hostname) {
  27. config.host = params.hostname;
  28. }
  29. if (params.port) {
  30. config.port = params.port;
  31. }
  32. if (params.pathname) {
  33. config.database = params.pathname.split('/')[1];
  34. }
  35. const ssl = params.query && params.query.ssl;
  36. if (ssl) {
  37. config.ssl = ssl === 'true' || ssl === '1';
  38. }
  39. return config;
  40. };
  41. const redisUrlToClient = (defaultConfig, redisUrl) => {
  42. const config = defaultConfig;
  43. if (!redisUrl) {
  44. return redis.createClient(config);
  45. }
  46. if (redisUrl.startsWith('unix://')) {
  47. return redis.createClient(redisUrl.slice(7), config);
  48. }
  49. return redis.createClient(Object.assign(config, {
  50. url: redisUrl,
  51. }));
  52. };
  53. const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  54. const startMaster = () => {
  55. log.info(`Starting streaming API server master with ${numWorkers} workers`);
  56. };
  57. const startWorker = (workerId) => {
  58. log.info(`Starting worker ${workerId}`);
  59. const pgConfigs = {
  60. development: {
  61. user: process.env.DB_USER || pg.defaults.user,
  62. password: process.env.DB_PASS || pg.defaults.password,
  63. database: process.env.DB_NAME || 'mastodon_development',
  64. host: process.env.DB_HOST || pg.defaults.host,
  65. port: process.env.DB_PORT || pg.defaults.port,
  66. max: 10,
  67. },
  68. production: {
  69. user: process.env.DB_USER || 'mastodon',
  70. password: process.env.DB_PASS || '',
  71. database: process.env.DB_NAME || 'mastodon_production',
  72. host: process.env.DB_HOST || 'localhost',
  73. port: process.env.DB_PORT || 5432,
  74. max: 10,
  75. },
  76. };
  77. const app = express();
  78. app.set('trusted proxy', process.env.TRUSTED_PROXY_IP || 'loopback,uniquelocal');
  79. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  80. const server = http.createServer(app);
  81. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  82. const redisParams = {
  83. host: process.env.REDIS_HOST || '127.0.0.1',
  84. port: process.env.REDIS_PORT || 6379,
  85. db: process.env.REDIS_DB || 0,
  86. password: process.env.REDIS_PASSWORD,
  87. };
  88. if (redisNamespace) {
  89. redisParams.namespace = redisNamespace;
  90. }
  91. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  92. const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  93. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  94. const subs = {};
  95. redisSubscribeClient.on('message', (channel, message) => {
  96. const callbacks = subs[channel];
  97. log.silly(`New message on channel ${channel}`);
  98. if (!callbacks) {
  99. return;
  100. }
  101. callbacks.forEach(callback => callback(message));
  102. });
  103. const subscriptionHeartbeat = (channel) => {
  104. const interval = 6*60;
  105. const tellSubscribed = () => {
  106. redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval*3);
  107. };
  108. tellSubscribed();
  109. const heartbeat = setInterval(tellSubscribed, interval*1000);
  110. return () => {
  111. clearInterval(heartbeat);
  112. };
  113. };
  114. const subscribe = (channel, callback) => {
  115. log.silly(`Adding listener for ${channel}`);
  116. subs[channel] = subs[channel] || [];
  117. if (subs[channel].length === 0) {
  118. log.verbose(`Subscribe ${channel}`);
  119. redisSubscribeClient.subscribe(channel);
  120. }
  121. subs[channel].push(callback);
  122. };
  123. const unsubscribe = (channel, callback) => {
  124. log.silly(`Removing listener for ${channel}`);
  125. subs[channel] = subs[channel].filter(item => item !== callback);
  126. if (subs[channel].length === 0) {
  127. log.verbose(`Unsubscribe ${channel}`);
  128. redisSubscribeClient.unsubscribe(channel);
  129. }
  130. };
  131. const allowCrossDomain = (req, res, next) => {
  132. res.header('Access-Control-Allow-Origin', '*');
  133. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  134. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  135. next();
  136. };
  137. const setRequestId = (req, res, next) => {
  138. req.requestId = uuid.v4();
  139. res.header('X-Request-Id', req.requestId);
  140. next();
  141. };
  142. const setRemoteAddress = (req, res, next) => {
  143. req.remoteAddress = req.connection.remoteAddress;
  144. next();
  145. };
  146. const accountFromToken = (token, req, next) => {
  147. pgPool.connect((err, client, done) => {
  148. if (err) {
  149. next(err);
  150. return;
  151. }
  152. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.filtered_languages FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 AND oauth_access_tokens.revoked_at IS NULL LIMIT 1', [token], (err, result) => {
  153. done();
  154. if (err) {
  155. next(err);
  156. return;
  157. }
  158. if (result.rows.length === 0) {
  159. err = new Error('Invalid access token');
  160. err.statusCode = 401;
  161. next(err);
  162. return;
  163. }
  164. req.accountId = result.rows[0].account_id;
  165. req.filteredLanguages = result.rows[0].filtered_languages;
  166. next();
  167. });
  168. });
  169. };
  170. const accountFromRequest = (req, next, required = true) => {
  171. const authorization = req.headers.authorization;
  172. const location = url.parse(req.url, true);
  173. const accessToken = location.query.access_token;
  174. if (!authorization && !accessToken) {
  175. if (required) {
  176. const err = new Error('Missing access token');
  177. err.statusCode = 401;
  178. next(err);
  179. return;
  180. } else {
  181. next();
  182. return;
  183. }
  184. }
  185. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  186. accountFromToken(token, req, next);
  187. };
  188. const PUBLIC_STREAMS = [
  189. 'public',
  190. 'public:local',
  191. 'hashtag',
  192. 'hashtag:local',
  193. ];
  194. const wsVerifyClient = (info, cb) => {
  195. const location = url.parse(info.req.url, true);
  196. const authRequired = !PUBLIC_STREAMS.some(stream => stream === location.query.stream);
  197. accountFromRequest(info.req, err => {
  198. if (!err) {
  199. cb(true, undefined, undefined);
  200. } else {
  201. log.error(info.req.requestId, err.toString());
  202. cb(false, 401, 'Unauthorized');
  203. }
  204. }, authRequired);
  205. };
  206. const PUBLIC_ENDPOINTS = [
  207. '/api/v1/streaming/public',
  208. '/api/v1/streaming/public/local',
  209. '/api/v1/streaming/hashtag',
  210. '/api/v1/streaming/hashtag/local',
  211. ];
  212. const authenticationMiddleware = (req, res, next) => {
  213. if (req.method === 'OPTIONS') {
  214. next();
  215. return;
  216. }
  217. const authRequired = !PUBLIC_ENDPOINTS.some(endpoint => endpoint === req.path);
  218. accountFromRequest(req, next, authRequired);
  219. };
  220. const errorMiddleware = (err, req, res, {}) => {
  221. log.error(req.requestId, err.toString());
  222. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  223. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  224. };
  225. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  226. const authorizeListAccess = (id, req, next) => {
  227. pgPool.connect((err, client, done) => {
  228. if (err) {
  229. next(false);
  230. return;
  231. }
  232. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [id], (err, result) => {
  233. done();
  234. if (err || result.rows.length === 0 || result.rows[0].account_id !== req.accountId) {
  235. next(false);
  236. return;
  237. }
  238. next(true);
  239. });
  240. });
  241. };
  242. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  243. const accountId = req.accountId || req.remoteAddress;
  244. const streamType = notificationOnly ? ' (notification)' : '';
  245. log.verbose(req.requestId, `Starting stream from ${id} for ${accountId}${streamType}`);
  246. const listener = message => {
  247. const { event, payload, queued_at } = JSON.parse(message);
  248. const transmit = () => {
  249. const now = new Date().getTime();
  250. const delta = now - queued_at;
  251. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  252. log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  253. output(event, encodedPayload);
  254. };
  255. if (notificationOnly && event !== 'notification') {
  256. return;
  257. }
  258. // Only messages that may require filtering are statuses, since notifications
  259. // are already personalized and deletes do not matter
  260. if (needsFiltering && event === 'update') {
  261. pgPool.connect((err, client, done) => {
  262. if (err) {
  263. log.error(err);
  264. return;
  265. }
  266. const unpackedPayload = payload;
  267. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  268. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  269. if (Array.isArray(req.filteredLanguages) && req.filteredLanguages.indexOf(unpackedPayload.language) !== -1) {
  270. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  271. done();
  272. return;
  273. }
  274. if (req.accountId) {
  275. const queries = [
  276. 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)),
  277. ];
  278. if (accountDomain) {
  279. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  280. }
  281. Promise.all(queries).then(values => {
  282. done();
  283. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  284. return;
  285. }
  286. transmit();
  287. }).catch(err => {
  288. done();
  289. log.error(err);
  290. });
  291. } else {
  292. done();
  293. transmit();
  294. }
  295. });
  296. } else {
  297. transmit();
  298. }
  299. };
  300. subscribe(`${redisPrefix}${id}`, listener);
  301. attachCloseHandler(`${redisPrefix}${id}`, listener);
  302. };
  303. // Setup stream output to HTTP
  304. const streamToHttp = (req, res) => {
  305. const accountId = req.accountId || req.remoteAddress;
  306. res.setHeader('Content-Type', 'text/event-stream');
  307. res.setHeader('Transfer-Encoding', 'chunked');
  308. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  309. req.on('close', () => {
  310. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  311. clearInterval(heartbeat);
  312. });
  313. return (event, payload) => {
  314. res.write(`event: ${event}\n`);
  315. res.write(`data: ${payload}\n\n`);
  316. };
  317. };
  318. // Setup stream end for HTTP
  319. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  320. req.on('close', () => {
  321. unsubscribe(id, listener);
  322. if (closeHandler) {
  323. closeHandler();
  324. }
  325. });
  326. };
  327. // Setup stream output to WebSockets
  328. const streamToWs = (req, ws) => (event, payload) => {
  329. if (ws.readyState !== ws.OPEN) {
  330. log.error(req.requestId, 'Tried writing to closed socket');
  331. return;
  332. }
  333. ws.send(JSON.stringify({ event, payload }));
  334. };
  335. // Setup stream end for WebSockets
  336. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  337. const accountId = req.accountId || req.remoteAddress;
  338. ws.on('close', () => {
  339. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  340. unsubscribe(id, listener);
  341. if (closeHandler) {
  342. closeHandler();
  343. }
  344. });
  345. ws.on('error', () => {
  346. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  347. unsubscribe(id, listener);
  348. if (closeHandler) {
  349. closeHandler();
  350. }
  351. });
  352. };
  353. app.use(setRequestId);
  354. app.use(setRemoteAddress);
  355. app.use(allowCrossDomain);
  356. app.use(authenticationMiddleware);
  357. app.use(errorMiddleware);
  358. app.get('/api/v1/streaming/user', (req, res) => {
  359. const channel = `timeline:${req.accountId}`;
  360. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  361. });
  362. app.get('/api/v1/streaming/user/notification', (req, res) => {
  363. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  364. });
  365. app.get('/api/v1/streaming/public', (req, res) => {
  366. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true);
  367. });
  368. app.get('/api/v1/streaming/public/local', (req, res) => {
  369. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true);
  370. });
  371. app.get('/api/v1/streaming/hashtag', (req, res) => {
  372. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  373. });
  374. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  375. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  376. });
  377. app.get('/api/v1/streaming/list', (req, res) => {
  378. const listId = req.query.list;
  379. authorizeListAccess(listId, req, authorized => {
  380. if (!authorized) {
  381. res.writeHead(404, { 'Content-Type': 'application/json' });
  382. res.end(JSON.stringify({ error: 'Not found' }));
  383. return;
  384. }
  385. const channel = `timeline:list:${listId}`;
  386. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  387. });
  388. });
  389. const wss = new WebSocket.Server({ server, verifyClient: wsVerifyClient });
  390. wss.on('connection', ws => {
  391. const req = ws.upgradeReq;
  392. const location = url.parse(req.url, true);
  393. req.requestId = uuid.v4();
  394. req.remoteAddress = ws._socket.remoteAddress;
  395. ws.isAlive = true;
  396. ws.on('pong', () => {
  397. ws.isAlive = true;
  398. });
  399. switch(location.query.stream) {
  400. case 'user':
  401. const channel = `timeline:${req.accountId}`;
  402. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  403. break;
  404. case 'user:notification':
  405. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  406. break;
  407. case 'public':
  408. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  409. break;
  410. case 'public:local':
  411. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  412. break;
  413. case 'hashtag':
  414. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  415. break;
  416. case 'hashtag:local':
  417. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  418. break;
  419. case 'list':
  420. const listId = location.query.list;
  421. authorizeListAccess(listId, req, authorized => {
  422. if (!authorized) {
  423. ws.close();
  424. return;
  425. }
  426. const channel = `timeline:list:${listId}`;
  427. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  428. });
  429. break;
  430. default:
  431. ws.close();
  432. }
  433. });
  434. setInterval(() => {
  435. wss.clients.forEach(ws => {
  436. if (ws.isAlive === false) {
  437. ws.terminate();
  438. return;
  439. }
  440. ws.isAlive = false;
  441. ws.ping('', false, true);
  442. });
  443. }, 30000);
  444. server.listen(process.env.PORT || 4000, process.env.BIND || '0.0.0.0', () => {
  445. log.info(`Worker ${workerId} now listening on ${server.address().address}:${server.address().port}`);
  446. });
  447. const onExit = () => {
  448. log.info(`Worker ${workerId} exiting, bye bye`);
  449. server.close();
  450. process.exit(0);
  451. };
  452. const onError = (err) => {
  453. log.error(err);
  454. server.close();
  455. process.exit(0);
  456. };
  457. process.on('SIGINT', onExit);
  458. process.on('SIGTERM', onExit);
  459. process.on('exit', onExit);
  460. process.on('uncaughtException', onError);
  461. };
  462. throng({
  463. workers: numWorkers,
  464. lifetime: Infinity,
  465. start: startWorker,
  466. master: startMaster,
  467. });