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.

691 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 messages that may require filtering are statuses, since notifications
  269. // are already personalized and deletes do not matter
  270. if (!needsFiltering || event !== 'update') {
  271. transmit();
  272. return;
  273. }
  274. const unpackedPayload = payload;
  275. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  276. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  277. if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
  278. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  279. return;
  280. }
  281. // When the account is not logged in, it is not necessary to confirm the block or mute
  282. if (!req.accountId) {
  283. transmit();
  284. return;
  285. }
  286. pgPool.connect((err, client, done) => {
  287. if (err) {
  288. log.error(err);
  289. return;
  290. }
  291. const queries = [
  292. 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)),
  293. ];
  294. if (accountDomain) {
  295. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  296. }
  297. Promise.all(queries).then(values => {
  298. done();
  299. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  300. return;
  301. }
  302. transmit();
  303. }).catch(err => {
  304. done();
  305. log.error(err);
  306. });
  307. });
  308. };
  309. subscribe(`${redisPrefix}${id}`, listener);
  310. attachCloseHandler(`${redisPrefix}${id}`, listener);
  311. };
  312. // Setup stream output to HTTP
  313. const streamToHttp = (req, res) => {
  314. const accountId = req.accountId || req.remoteAddress;
  315. res.setHeader('Content-Type', 'text/event-stream');
  316. res.setHeader('Transfer-Encoding', 'chunked');
  317. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  318. req.on('close', () => {
  319. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  320. clearInterval(heartbeat);
  321. });
  322. return (event, payload) => {
  323. res.write(`event: ${event}\n`);
  324. res.write(`data: ${payload}\n\n`);
  325. };
  326. };
  327. // Setup stream end for HTTP
  328. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  329. req.on('close', () => {
  330. unsubscribe(id, listener);
  331. if (closeHandler) {
  332. closeHandler();
  333. }
  334. });
  335. };
  336. // Setup stream output to WebSockets
  337. const streamToWs = (req, ws) => (event, payload) => {
  338. if (ws.readyState !== ws.OPEN) {
  339. log.error(req.requestId, 'Tried writing to closed socket');
  340. return;
  341. }
  342. ws.send(JSON.stringify({ event, payload }));
  343. };
  344. // Setup stream end for WebSockets
  345. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  346. const accountId = req.accountId || req.remoteAddress;
  347. ws.on('close', () => {
  348. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  349. unsubscribe(id, listener);
  350. if (closeHandler) {
  351. closeHandler();
  352. }
  353. });
  354. ws.on('error', () => {
  355. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  356. unsubscribe(id, listener);
  357. if (closeHandler) {
  358. closeHandler();
  359. }
  360. });
  361. };
  362. const httpNotFound = res => {
  363. res.writeHead(404, { 'Content-Type': 'application/json' });
  364. res.end(JSON.stringify({ error: 'Not found' }));
  365. };
  366. app.use(setRequestId);
  367. app.use(setRemoteAddress);
  368. app.use(allowCrossDomain);
  369. app.get('/api/v1/streaming/health', (req, res) => {
  370. res.writeHead(200, { 'Content-Type': 'text/plain' });
  371. res.end('OK');
  372. });
  373. app.use(authenticationMiddleware);
  374. app.use(errorMiddleware);
  375. app.get('/api/v1/streaming/user', (req, res) => {
  376. const channel = `timeline:${req.accountId}`;
  377. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  378. });
  379. app.get('/api/v1/streaming/user/notification', (req, res) => {
  380. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  381. });
  382. app.get('/api/v1/streaming/public', (req, res) => {
  383. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  384. const channel = onlyMedia ? 'timeline:public:media' : 'timeline:public';
  385. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  386. });
  387. app.get('/api/v1/streaming/public/local', (req, res) => {
  388. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  389. const channel = onlyMedia ? 'timeline:public:local:media' : 'timeline:public:local';
  390. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  391. });
  392. app.get('/api/v1/streaming/direct', (req, res) => {
  393. const channel = `timeline:direct:${req.accountId}`;
  394. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)), true);
  395. });
  396. app.get('/api/v1/streaming/hashtag', (req, res) => {
  397. const { tag } = req.query;
  398. if (!tag || tag.length === 0) {
  399. httpNotFound(res);
  400. return;
  401. }
  402. streamFrom(`timeline:hashtag:${tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  403. });
  404. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  405. const { tag } = req.query;
  406. if (!tag || tag.length === 0) {
  407. httpNotFound(res);
  408. return;
  409. }
  410. streamFrom(`timeline:hashtag:${tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  411. });
  412. app.get('/api/v1/streaming/list', (req, res) => {
  413. const listId = req.query.list;
  414. authorizeListAccess(listId, req, authorized => {
  415. if (!authorized) {
  416. httpNotFound(res);
  417. return;
  418. }
  419. const channel = `timeline:list:${listId}`;
  420. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  421. });
  422. });
  423. const wss = new WebSocket.Server({ server, verifyClient: wsVerifyClient });
  424. wss.on('connection', ws => {
  425. const req = ws.upgradeReq;
  426. const location = url.parse(req.url, true);
  427. req.requestId = uuid.v4();
  428. req.remoteAddress = ws._socket.remoteAddress;
  429. ws.isAlive = true;
  430. ws.on('pong', () => {
  431. ws.isAlive = true;
  432. });
  433. let channel;
  434. switch(location.query.stream) {
  435. case 'user':
  436. channel = `timeline:${req.accountId}`;
  437. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  438. break;
  439. case 'user:notification':
  440. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  441. break;
  442. case 'public':
  443. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  444. break;
  445. case 'public:local':
  446. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  447. break;
  448. case 'public:media':
  449. streamFrom('timeline:public:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  450. break;
  451. case 'public:local:media':
  452. streamFrom('timeline:public:local:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  453. break;
  454. case 'direct':
  455. channel = `timeline:direct:${req.accountId}`;
  456. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)), true);
  457. break;
  458. case 'hashtag':
  459. if (!location.query.tag || location.query.tag.length === 0) {
  460. ws.close();
  461. return;
  462. }
  463. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  464. break;
  465. case 'hashtag:local':
  466. if (!location.query.tag || location.query.tag.length === 0) {
  467. ws.close();
  468. return;
  469. }
  470. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  471. break;
  472. case 'list':
  473. const listId = location.query.list;
  474. authorizeListAccess(listId, req, authorized => {
  475. if (!authorized) {
  476. ws.close();
  477. return;
  478. }
  479. channel = `timeline:list:${listId}`;
  480. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  481. });
  482. break;
  483. default:
  484. ws.close();
  485. }
  486. });
  487. setInterval(() => {
  488. wss.clients.forEach(ws => {
  489. if (ws.isAlive === false) {
  490. ws.terminate();
  491. return;
  492. }
  493. ws.isAlive = false;
  494. ws.ping('', false, true);
  495. });
  496. }, 30000);
  497. attachServerWithConfig(server, address => {
  498. log.info(`Worker ${workerId} now listening on ${address}`);
  499. });
  500. const onExit = () => {
  501. log.info(`Worker ${workerId} exiting, bye bye`);
  502. server.close();
  503. process.exit(0);
  504. };
  505. const onError = (err) => {
  506. log.error(err);
  507. server.close();
  508. process.exit(0);
  509. };
  510. process.on('SIGINT', onExit);
  511. process.on('SIGTERM', onExit);
  512. process.on('exit', onExit);
  513. process.on('uncaughtException', onError);
  514. };
  515. const attachServerWithConfig = (server, onSuccess) => {
  516. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  517. server.listen(process.env.SOCKET || process.env.PORT, () => {
  518. if (onSuccess) {
  519. fs.chmodSync(server.address(), 0o666);
  520. onSuccess(server.address());
  521. }
  522. });
  523. } else {
  524. server.listen(+process.env.PORT || 4000, process.env.BIND || '0.0.0.0', () => {
  525. if (onSuccess) {
  526. onSuccess(`${server.address().address}:${server.address().port}`);
  527. }
  528. });
  529. }
  530. };
  531. const onPortAvailable = onSuccess => {
  532. const testServer = http.createServer();
  533. testServer.once('error', err => {
  534. onSuccess(err);
  535. });
  536. testServer.once('listening', () => {
  537. testServer.once('close', () => onSuccess());
  538. testServer.close();
  539. });
  540. attachServerWithConfig(testServer);
  541. };
  542. onPortAvailable(err => {
  543. if (err) {
  544. log.error('Could not start server, the port or socket is in use');
  545. return;
  546. }
  547. throng({
  548. workers: numWorkers,
  549. lifetime: Infinity,
  550. start: startWorker,
  551. master: startMaster,
  552. });
  553. });