The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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