闭社主体 forked from https://github.com/tootsuite/mastodon
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.

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