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.

716 lines
21 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 { WebSocketServer } = require('@clusterws/cws');
  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, allowedScopes, 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, oauth_access_tokens.scopes 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. const scopes = result.rows[0].scopes.split(' ');
  173. if (allowedScopes.size > 0 && !scopes.some(scope => allowedScopes.includes(scope))) {
  174. err = new Error('Access token does not cover required scopes');
  175. err.statusCode = 401;
  176. next(err);
  177. return;
  178. }
  179. req.accountId = result.rows[0].account_id;
  180. req.chosenLanguages = result.rows[0].chosen_languages;
  181. req.allowNotifications = scopes.some(scope => ['read', 'read:notifications'].includes(scope));
  182. next();
  183. });
  184. });
  185. };
  186. const accountFromRequest = (req, next, required = true, allowedScopes = ['read']) => {
  187. const authorization = req.headers.authorization;
  188. const location = url.parse(req.url, true);
  189. const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
  190. if (!authorization && !accessToken) {
  191. if (required) {
  192. const err = new Error('Missing access token');
  193. err.statusCode = 401;
  194. next(err);
  195. return;
  196. } else {
  197. next();
  198. return;
  199. }
  200. }
  201. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  202. accountFromToken(token, allowedScopes, req, next);
  203. };
  204. const PUBLIC_STREAMS = [
  205. 'public',
  206. 'public:media',
  207. 'public:local',
  208. 'public:local:media',
  209. 'hashtag',
  210. 'hashtag:local',
  211. ];
  212. const wsVerifyClient = (info, cb) => {
  213. const location = url.parse(info.req.url, true);
  214. const authRequired = !PUBLIC_STREAMS.some(stream => stream === location.query.stream);
  215. const allowedScopes = [];
  216. if (authRequired) {
  217. allowedScopes.push('read');
  218. if (location.query.stream === 'user:notification') {
  219. allowedScopes.push('read:notifications');
  220. } else {
  221. allowedScopes.push('read:statuses');
  222. }
  223. }
  224. accountFromRequest(info.req, err => {
  225. if (!err) {
  226. cb(true, undefined, undefined);
  227. } else {
  228. log.error(info.req.requestId, err.toString());
  229. cb(false, 401, 'Unauthorized');
  230. }
  231. }, authRequired, allowedScopes);
  232. };
  233. const PUBLIC_ENDPOINTS = [
  234. '/api/v1/streaming/public',
  235. '/api/v1/streaming/public/local',
  236. '/api/v1/streaming/hashtag',
  237. '/api/v1/streaming/hashtag/local',
  238. ];
  239. const authenticationMiddleware = (req, res, next) => {
  240. if (req.method === 'OPTIONS') {
  241. next();
  242. return;
  243. }
  244. const authRequired = !PUBLIC_ENDPOINTS.some(endpoint => endpoint === req.path);
  245. const allowedScopes = [];
  246. if (authRequired) {
  247. allowedScopes.push('read');
  248. if (req.path === '/api/v1/streaming/user/notification') {
  249. allowedScopes.push('read:notifications');
  250. } else {
  251. allowedScopes.push('read:statuses');
  252. }
  253. }
  254. accountFromRequest(req, next, authRequired, allowedScopes);
  255. };
  256. const errorMiddleware = (err, req, res, {}) => {
  257. log.error(req.requestId, err.toString());
  258. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  259. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  260. };
  261. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  262. const authorizeListAccess = (id, req, next) => {
  263. pgPool.connect((err, client, done) => {
  264. if (err) {
  265. next(false);
  266. return;
  267. }
  268. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [id], (err, result) => {
  269. done();
  270. if (err || result.rows.length === 0 || result.rows[0].account_id !== req.accountId) {
  271. next(false);
  272. return;
  273. }
  274. next(true);
  275. });
  276. });
  277. };
  278. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  279. const accountId = req.accountId || req.remoteAddress;
  280. const streamType = notificationOnly ? ' (notification)' : '';
  281. log.verbose(req.requestId, `Starting stream from ${id} for ${accountId}${streamType}`);
  282. const listener = message => {
  283. const { event, payload, queued_at } = JSON.parse(message);
  284. const transmit = () => {
  285. const now = new Date().getTime();
  286. const delta = now - queued_at;
  287. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  288. log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  289. output(event, encodedPayload);
  290. };
  291. if (notificationOnly && event !== 'notification') {
  292. return;
  293. }
  294. if (event === 'notification' && !req.allowNotifications) {
  295. return;
  296. }
  297. // Only send local-only statuses to logged-in users
  298. if (event === 'update' && payload.local_only && !req.accountId) {
  299. log.silly(req.requestId, `Message ${payload.id} filtered because it was local-only`);
  300. return;
  301. }
  302. // Only messages that may require filtering are statuses, since notifications
  303. // are already personalized and deletes do not matter
  304. if (!needsFiltering || event !== 'update') {
  305. transmit();
  306. return;
  307. }
  308. const unpackedPayload = payload;
  309. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  310. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  311. if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
  312. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  313. return;
  314. }
  315. // When the account is not logged in, it is not necessary to confirm the block or mute
  316. if (!req.accountId) {
  317. transmit();
  318. return;
  319. }
  320. pgPool.connect((err, client, done) => {
  321. if (err) {
  322. log.error(err);
  323. return;
  324. }
  325. const queries = [
  326. 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)),
  327. ];
  328. if (accountDomain) {
  329. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  330. }
  331. Promise.all(queries).then(values => {
  332. done();
  333. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  334. return;
  335. }
  336. transmit();
  337. }).catch(err => {
  338. done();
  339. log.error(err);
  340. });
  341. });
  342. };
  343. subscribe(`${redisPrefix}${id}`, listener);
  344. attachCloseHandler(`${redisPrefix}${id}`, listener);
  345. };
  346. // Setup stream output to HTTP
  347. const streamToHttp = (req, res) => {
  348. const accountId = req.accountId || req.remoteAddress;
  349. res.setHeader('Content-Type', 'text/event-stream');
  350. res.setHeader('Transfer-Encoding', 'chunked');
  351. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  352. req.on('close', () => {
  353. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  354. clearInterval(heartbeat);
  355. });
  356. return (event, payload) => {
  357. res.write(`event: ${event}\n`);
  358. res.write(`data: ${payload}\n\n`);
  359. };
  360. };
  361. // Setup stream end for HTTP
  362. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  363. req.on('close', () => {
  364. unsubscribe(id, listener);
  365. if (closeHandler) {
  366. closeHandler();
  367. }
  368. });
  369. };
  370. // Setup stream output to WebSockets
  371. const streamToWs = (req, ws) => (event, payload) => {
  372. if (ws.readyState !== ws.OPEN) {
  373. log.error(req.requestId, 'Tried writing to closed socket');
  374. return;
  375. }
  376. ws.send(JSON.stringify({ event, payload }));
  377. };
  378. // Setup stream end for WebSockets
  379. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  380. const accountId = req.accountId || req.remoteAddress;
  381. ws.on('close', () => {
  382. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  383. unsubscribe(id, listener);
  384. if (closeHandler) {
  385. closeHandler();
  386. }
  387. });
  388. ws.on('error', () => {
  389. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  390. unsubscribe(id, listener);
  391. if (closeHandler) {
  392. closeHandler();
  393. }
  394. });
  395. };
  396. const httpNotFound = res => {
  397. res.writeHead(404, { 'Content-Type': 'application/json' });
  398. res.end(JSON.stringify({ error: 'Not found' }));
  399. };
  400. app.use(setRequestId);
  401. app.use(setRemoteAddress);
  402. app.use(allowCrossDomain);
  403. app.get('/api/v1/streaming/health', (req, res) => {
  404. res.writeHead(200, { 'Content-Type': 'text/plain' });
  405. res.end('OK');
  406. });
  407. app.use(authenticationMiddleware);
  408. app.use(errorMiddleware);
  409. app.get('/api/v1/streaming/user', (req, res) => {
  410. const channel = `timeline:${req.accountId}`;
  411. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  412. });
  413. app.get('/api/v1/streaming/user/notification', (req, res) => {
  414. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  415. });
  416. app.get('/api/v1/streaming/public', (req, res) => {
  417. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  418. const channel = onlyMedia ? 'timeline:public:media' : 'timeline:public';
  419. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  420. });
  421. app.get('/api/v1/streaming/public/local', (req, res) => {
  422. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  423. const channel = onlyMedia ? 'timeline:public:local:media' : 'timeline:public:local';
  424. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  425. });
  426. app.get('/api/v1/streaming/direct', (req, res) => {
  427. const channel = `timeline:direct:${req.accountId}`;
  428. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)), true);
  429. });
  430. app.get('/api/v1/streaming/hashtag', (req, res) => {
  431. const { tag } = req.query;
  432. if (!tag || tag.length === 0) {
  433. httpNotFound(res);
  434. return;
  435. }
  436. streamFrom(`timeline:hashtag:${tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  437. });
  438. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  439. const { tag } = req.query;
  440. if (!tag || tag.length === 0) {
  441. httpNotFound(res);
  442. return;
  443. }
  444. streamFrom(`timeline:hashtag:${tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  445. });
  446. app.get('/api/v1/streaming/list', (req, res) => {
  447. const listId = req.query.list;
  448. authorizeListAccess(listId, req, authorized => {
  449. if (!authorized) {
  450. httpNotFound(res);
  451. return;
  452. }
  453. const channel = `timeline:list:${listId}`;
  454. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  455. });
  456. });
  457. const wss = new WebSocketServer({ server, verifyClient: wsVerifyClient });
  458. wss.on('connection', (ws, req) => {
  459. const location = url.parse(req.url, true);
  460. req.requestId = uuid.v4();
  461. req.remoteAddress = ws._socket.remoteAddress;
  462. let channel;
  463. switch(location.query.stream) {
  464. case 'user':
  465. channel = `timeline:${req.accountId}`;
  466. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  467. break;
  468. case 'user:notification':
  469. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  470. break;
  471. case 'public':
  472. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  473. break;
  474. case 'public:local':
  475. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  476. break;
  477. case 'public:media':
  478. streamFrom('timeline:public:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  479. break;
  480. case 'public:local:media':
  481. streamFrom('timeline:public:local:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  482. break;
  483. case 'direct':
  484. channel = `timeline:direct:${req.accountId}`;
  485. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)), true);
  486. break;
  487. case 'hashtag':
  488. if (!location.query.tag || location.query.tag.length === 0) {
  489. ws.close();
  490. return;
  491. }
  492. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  493. break;
  494. case 'hashtag:local':
  495. if (!location.query.tag || location.query.tag.length === 0) {
  496. ws.close();
  497. return;
  498. }
  499. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  500. break;
  501. case 'list':
  502. const listId = location.query.list;
  503. authorizeListAccess(listId, req, authorized => {
  504. if (!authorized) {
  505. ws.close();
  506. return;
  507. }
  508. channel = `timeline:list:${listId}`;
  509. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  510. });
  511. break;
  512. default:
  513. ws.close();
  514. }
  515. });
  516. wss.startAutoPing(30000);
  517. attachServerWithConfig(server, address => {
  518. log.info(`Worker ${workerId} now listening on ${address}`);
  519. });
  520. const onExit = () => {
  521. log.info(`Worker ${workerId} exiting, bye bye`);
  522. server.close();
  523. process.exit(0);
  524. };
  525. const onError = (err) => {
  526. log.error(err);
  527. server.close();
  528. process.exit(0);
  529. };
  530. process.on('SIGINT', onExit);
  531. process.on('SIGTERM', onExit);
  532. process.on('exit', onExit);
  533. process.on('uncaughtException', onError);
  534. };
  535. const attachServerWithConfig = (server, onSuccess) => {
  536. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  537. server.listen(process.env.SOCKET || process.env.PORT, () => {
  538. if (onSuccess) {
  539. fs.chmodSync(server.address(), 0o666);
  540. onSuccess(server.address());
  541. }
  542. });
  543. } else {
  544. server.listen(+process.env.PORT || 4000, process.env.BIND || '0.0.0.0', () => {
  545. if (onSuccess) {
  546. onSuccess(`${server.address().address}:${server.address().port}`);
  547. }
  548. });
  549. }
  550. };
  551. const onPortAvailable = onSuccess => {
  552. const testServer = http.createServer();
  553. testServer.once('error', err => {
  554. onSuccess(err);
  555. });
  556. testServer.once('listening', () => {
  557. testServer.once('close', () => onSuccess());
  558. testServer.close();
  559. });
  560. attachServerWithConfig(testServer);
  561. };
  562. onPortAvailable(err => {
  563. if (err) {
  564. log.error('Could not start server, the port or socket is in use');
  565. return;
  566. }
  567. throng({
  568. workers: numWorkers,
  569. lifetime: Infinity,
  570. start: startWorker,
  571. master: startMaster,
  572. });
  573. });