闭社主体 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.

674 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 { 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, 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 WebSocketServer({ server, verifyClient: wsVerifyClient });
  424. wss.on('connection', (ws, req) => {
  425. const location = url.parse(req.url, true);
  426. req.requestId = uuid.v4();
  427. req.remoteAddress = ws._socket.remoteAddress;
  428. let channel;
  429. switch(location.query.stream) {
  430. case 'user':
  431. channel = `timeline:${req.accountId}`;
  432. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  433. break;
  434. case 'user:notification':
  435. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  436. break;
  437. case 'public':
  438. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  439. break;
  440. case 'public:local':
  441. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  442. break;
  443. case 'public:media':
  444. streamFrom('timeline:public:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  445. break;
  446. case 'public:local:media':
  447. streamFrom('timeline:public:local:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  448. break;
  449. case 'direct':
  450. channel = `timeline:direct:${req.accountId}`;
  451. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)), true);
  452. break;
  453. case 'hashtag':
  454. if (!location.query.tag || location.query.tag.length === 0) {
  455. ws.close();
  456. return;
  457. }
  458. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  459. break;
  460. case 'hashtag:local':
  461. if (!location.query.tag || location.query.tag.length === 0) {
  462. ws.close();
  463. return;
  464. }
  465. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  466. break;
  467. case 'list':
  468. const listId = location.query.list;
  469. authorizeListAccess(listId, req, authorized => {
  470. if (!authorized) {
  471. ws.close();
  472. return;
  473. }
  474. channel = `timeline:list:${listId}`;
  475. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  476. });
  477. break;
  478. default:
  479. ws.close();
  480. }
  481. });
  482. wss.startAutoPing(30000);
  483. attachServerWithConfig(server, address => {
  484. log.info(`Worker ${workerId} now listening on ${address}`);
  485. });
  486. const onExit = () => {
  487. log.info(`Worker ${workerId} exiting, bye bye`);
  488. server.close();
  489. process.exit(0);
  490. };
  491. const onError = (err) => {
  492. log.error(err);
  493. server.close();
  494. process.exit(0);
  495. };
  496. process.on('SIGINT', onExit);
  497. process.on('SIGTERM', onExit);
  498. process.on('exit', onExit);
  499. process.on('uncaughtException', onError);
  500. };
  501. const attachServerWithConfig = (server, onSuccess) => {
  502. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  503. server.listen(process.env.SOCKET || process.env.PORT, () => {
  504. if (onSuccess) {
  505. fs.chmodSync(server.address(), 0o666);
  506. onSuccess(server.address());
  507. }
  508. });
  509. } else {
  510. server.listen(+process.env.PORT || 4000, process.env.BIND || '0.0.0.0', () => {
  511. if (onSuccess) {
  512. onSuccess(`${server.address().address}:${server.address().port}`);
  513. }
  514. });
  515. }
  516. };
  517. const onPortAvailable = onSuccess => {
  518. const testServer = http.createServer();
  519. testServer.once('error', err => {
  520. onSuccess(err);
  521. });
  522. testServer.once('listening', () => {
  523. testServer.once('close', () => onSuccess());
  524. testServer.close();
  525. });
  526. attachServerWithConfig(testServer);
  527. };
  528. onPortAvailable(err => {
  529. if (err) {
  530. log.error('Could not start server, the port or socket is in use');
  531. return;
  532. }
  533. throng({
  534. workers: numWorkers,
  535. lifetime: Infinity,
  536. start: startWorker,
  537. master: startMaster,
  538. });
  539. });