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

697 lines
20 KiB

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