1
0

index.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. // @ts-check
  2. import fs from 'node:fs';
  3. import http from 'node:http';
  4. import path from 'node:path';
  5. import url from 'node:url';
  6. import cors from 'cors';
  7. import dotenv from 'dotenv';
  8. import express from 'express';
  9. import { JSDOM } from 'jsdom';
  10. import { WebSocketServer } from 'ws';
  11. import * as Database from './database.js';
  12. import { AuthenticationError, RequestError, extractStatusAndMessage as extractErrorStatusAndMessage } from './errors.js';
  13. import { logger, httpLogger, initializeLogLevel, attachWebsocketHttpLogger, createWebsocketLogger } from './logging.js';
  14. import { setupMetrics } from './metrics.js';
  15. import * as Redis from './redis.js';
  16. import { isTruthy, normalizeHashtag, firstParam } from './utils.js';
  17. const environment = process.env.NODE_ENV || 'development';
  18. // Correctly detect and load .env or .env.production file based on environment:
  19. const dotenvFile = environment === 'production' ? '.env.production' : '.env';
  20. const dotenvFilePath = path.resolve(
  21. url.fileURLToPath(
  22. new URL(path.join('..', dotenvFile), import.meta.url)
  23. )
  24. );
  25. dotenv.config({
  26. path: dotenvFilePath
  27. });
  28. initializeLogLevel(process.env, environment);
  29. /**
  30. * Declares the result type for accountFromToken / accountFromRequest.
  31. *
  32. * Note: This is here because jsdoc doesn't like importing types that
  33. * are nested in functions
  34. * @typedef ResolvedAccount
  35. * @property {string} accessTokenId
  36. * @property {string[]} scopes
  37. * @property {string} accountId
  38. * @property {string[]} chosenLanguages
  39. */
  40. /**
  41. * Attempts to safely parse a string as JSON, used when both receiving a message
  42. * from redis and when receiving a message from a client over a websocket
  43. * connection, this is why it accepts a `req` argument.
  44. * @param {string} json
  45. * @param {any?} req
  46. * @returns {Object.<string, any>|null}
  47. */
  48. const parseJSON = (json, req) => {
  49. try {
  50. return JSON.parse(json);
  51. } catch (err) {
  52. /* FIXME: This logging isn't great, and should probably be done at the
  53. * call-site of parseJSON, not in the method, but this would require changing
  54. * the signature of parseJSON to return something akin to a Result type:
  55. * [Error|null, null|Object<string,any}], and then handling the error
  56. * scenarios.
  57. */
  58. if (req) {
  59. if (req.accountId) {
  60. req.log.error({ err }, `Error parsing message from user ${req.accountId}`);
  61. } else {
  62. req.log.error({ err }, `Error parsing message from ${req.remoteAddress}`);
  63. }
  64. } else {
  65. logger.error({ err }, `Error parsing message from redis`);
  66. }
  67. return null;
  68. }
  69. };
  70. const PUBLIC_CHANNELS = [
  71. 'public',
  72. 'public:media',
  73. 'public:local',
  74. 'public:local:media',
  75. 'public:remote',
  76. 'public:remote:media',
  77. 'hashtag',
  78. 'hashtag:local',
  79. ];
  80. // Used for priming the counters/gauges for the various metrics that are
  81. // per-channel
  82. const CHANNEL_NAMES = [
  83. 'system',
  84. 'user',
  85. 'user:notification',
  86. 'list',
  87. 'direct',
  88. ...PUBLIC_CHANNELS
  89. ];
  90. const startServer = async () => {
  91. const pgPool = Database.getPool(Database.configFromEnv(process.env, environment));
  92. const metrics = setupMetrics(CHANNEL_NAMES, pgPool);
  93. const redisConfig = Redis.configFromEnv(process.env);
  94. const redisClient = Redis.createClient(redisConfig, logger);
  95. const server = http.createServer();
  96. const wss = new WebSocketServer({ noServer: true });
  97. /**
  98. * Adds a namespace to Redis keys or channel names
  99. * Fixes: https://github.com/redis/ioredis/issues/1910
  100. * @param {string} keyOrChannel
  101. * @returns {string}
  102. */
  103. function redisNamespaced(keyOrChannel) {
  104. if (redisConfig.namespace) {
  105. return `${redisConfig.namespace}:${keyOrChannel}`;
  106. } else {
  107. return keyOrChannel;
  108. }
  109. }
  110. /**
  111. * Removes the redis namespace from a channel name
  112. * @param {string} channel
  113. * @returns {string}
  114. */
  115. function redisUnnamespaced(channel) {
  116. if (typeof redisConfig.namespace === "string") {
  117. // Note: this removes the configured namespace and the colon that is used
  118. // to separate it:
  119. return channel.slice(redisConfig.namespace.length + 1);
  120. } else {
  121. return channel;
  122. }
  123. }
  124. // Set the X-Request-Id header on WebSockets:
  125. wss.on("headers", function onHeaders(headers, req) {
  126. headers.push(`X-Request-Id: ${req.id}`);
  127. });
  128. const app = express();
  129. app.set('trust proxy', process.env.TRUSTED_PROXY_IP ? process.env.TRUSTED_PROXY_IP.split(/(?:\s*,\s*|\s+)/) : 'loopback,uniquelocal');
  130. app.use(httpLogger);
  131. app.use(cors());
  132. // Handle eventsource & other http requests:
  133. server.on('request', app);
  134. // Handle upgrade requests:
  135. server.on('upgrade', async function handleUpgrade(request, socket, head) {
  136. // Setup the HTTP logger, since websocket upgrades don't get the usual http
  137. // logger. This decorates the `request` object.
  138. attachWebsocketHttpLogger(request);
  139. request.log.info("HTTP Upgrade Requested");
  140. /** @param {Error} err */
  141. const onSocketError = (err) => {
  142. request.log.error({ error: err }, err.message);
  143. };
  144. socket.on('error', onSocketError);
  145. /** @type {ResolvedAccount} */
  146. let resolvedAccount;
  147. try {
  148. resolvedAccount = await accountFromRequest(request);
  149. } catch (err) {
  150. // Unfortunately for using the on('upgrade') setup, we need to manually
  151. // write a HTTP Response to the Socket to close the connection upgrade
  152. // attempt, so the following code is to handle all of that.
  153. const {statusCode, errorMessage } = extractErrorStatusAndMessage(err);
  154. /** @type {Record<string, string | number | import('pino-http').ReqId>} */
  155. const headers = {
  156. 'Connection': 'close',
  157. 'Content-Type': 'text/plain',
  158. 'Content-Length': 0,
  159. 'X-Request-Id': request.id,
  160. 'X-Error-Message': errorMessage
  161. };
  162. // Ensure the socket is closed once we've finished writing to it:
  163. socket.once('finish', () => {
  164. socket.destroy();
  165. });
  166. // Write the HTTP response manually:
  167. socket.end(`HTTP/1.1 ${statusCode} ${http.STATUS_CODES[statusCode]}\r\n${Object.keys(headers).map((key) => `${key}: ${headers[key]}`).join('\r\n')}\r\n\r\n`);
  168. // Finally, log the error:
  169. request.log.error({
  170. err,
  171. res: {
  172. statusCode,
  173. headers
  174. }
  175. }, errorMessage);
  176. return;
  177. }
  178. // Remove the error handler, wss.handleUpgrade has its own:
  179. socket.removeListener('error', onSocketError);
  180. wss.handleUpgrade(request, socket, head, function done(ws) {
  181. request.log.info("Authenticated request & upgraded to WebSocket connection");
  182. const wsLogger = createWebsocketLogger(request, resolvedAccount);
  183. // Start the connection:
  184. wss.emit('connection', ws, request, wsLogger);
  185. });
  186. });
  187. /**
  188. * @type {Object.<string, Array.<function(Object<string, any>): void>>}
  189. */
  190. const subs = {};
  191. const redisSubscribeClient = Redis.createClient(redisConfig, logger);
  192. // When checking metrics in the browser, the favicon is requested this
  193. // prevents the request from falling through to the API Router, which would
  194. // error for this endpoint:
  195. app.get('/favicon.ico', (_req, res) => res.status(404).end());
  196. app.get('/api/v1/streaming/health', (_req, res) => {
  197. res.writeHead(200, { 'Content-Type': 'text/plain', 'Cache-Control': 'private, no-store' });
  198. res.end('OK');
  199. });
  200. app.get('/metrics', metrics.requestHandler);
  201. /**
  202. * @param {string[]} channels
  203. * @returns {function(): void}
  204. */
  205. const subscriptionHeartbeat = channels => {
  206. const interval = 6 * 60;
  207. const tellSubscribed = () => {
  208. channels.forEach(channel => redisClient.set(redisNamespaced(`subscribed:${channel}`), '1', 'EX', interval * 3));
  209. };
  210. tellSubscribed();
  211. const heartbeat = setInterval(tellSubscribed, interval * 1000);
  212. return () => {
  213. clearInterval(heartbeat);
  214. };
  215. };
  216. /**
  217. * @param {string} channel
  218. * @param {string} message
  219. */
  220. const onRedisMessage = (channel, message) => {
  221. metrics.redisMessagesReceived.inc();
  222. logger.debug(`New message on channel ${channel}`);
  223. const key = redisUnnamespaced(channel);
  224. const callbacks = subs[key];
  225. if (!callbacks) {
  226. return;
  227. }
  228. const json = parseJSON(message, null);
  229. if (!json) return;
  230. callbacks.forEach(callback => callback(json));
  231. };
  232. redisSubscribeClient.on("message", onRedisMessage);
  233. /**
  234. * @callback SubscriptionListener
  235. * @param {ReturnType<parseJSON>} json of the message
  236. * @returns void
  237. */
  238. /**
  239. * @param {string} channel
  240. * @param {SubscriptionListener} callback
  241. */
  242. const subscribe = (channel, callback) => {
  243. logger.debug(`Adding listener for ${channel}`);
  244. subs[channel] = subs[channel] || [];
  245. if (subs[channel].length === 0) {
  246. logger.debug(`Subscribe ${channel}`);
  247. redisSubscribeClient.subscribe(redisNamespaced(channel), (err, count) => {
  248. if (err) {
  249. logger.error(`Error subscribing to ${channel}`);
  250. } else if (typeof count === 'number') {
  251. metrics.redisSubscriptions.set(count);
  252. }
  253. });
  254. }
  255. subs[channel].push(callback);
  256. };
  257. /**
  258. * @param {string} channel
  259. * @param {SubscriptionListener} callback
  260. */
  261. const unsubscribe = (channel, callback) => {
  262. logger.debug(`Removing listener for ${channel}`);
  263. if (!subs[channel]) {
  264. return;
  265. }
  266. subs[channel] = subs[channel].filter(item => item !== callback);
  267. if (subs[channel].length === 0) {
  268. logger.debug(`Unsubscribe ${channel}`);
  269. // FIXME: https://github.com/redis/ioredis/issues/1910
  270. redisSubscribeClient.unsubscribe(redisNamespaced(channel), (err, count) => {
  271. if (err) {
  272. logger.error(`Error unsubscribing to ${channel}`);
  273. } else if (typeof count === 'number') {
  274. metrics.redisSubscriptions.set(count);
  275. }
  276. });
  277. delete subs[channel];
  278. }
  279. };
  280. /**
  281. * @param {http.IncomingMessage & ResolvedAccount} req
  282. * @param {string[]} necessaryScopes
  283. * @returns {boolean}
  284. */
  285. const isInScope = (req, necessaryScopes) =>
  286. req.scopes.some(scope => necessaryScopes.includes(scope));
  287. /**
  288. * @param {string} token
  289. * @param {any} req
  290. * @returns {Promise<ResolvedAccount>}
  291. */
  292. const accountFromToken = async (token, req) => {
  293. const result = await pgPool.query('SELECT oauth_access_tokens.id, 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]);
  294. if (result.rows.length === 0) {
  295. throw new AuthenticationError('Invalid access token');
  296. }
  297. req.accessTokenId = result.rows[0].id;
  298. req.scopes = result.rows[0].scopes.split(' ');
  299. req.accountId = result.rows[0].account_id;
  300. req.chosenLanguages = result.rows[0].chosen_languages;
  301. return {
  302. accessTokenId: result.rows[0].id,
  303. scopes: result.rows[0].scopes.split(' '),
  304. accountId: result.rows[0].account_id,
  305. chosenLanguages: result.rows[0].chosen_languages,
  306. };
  307. };
  308. /**
  309. * @param {any} req
  310. * @returns {Promise<ResolvedAccount>}
  311. */
  312. const accountFromRequest = (req) => new Promise((resolve, reject) => {
  313. const authorization = req.headers.authorization;
  314. const location = url.parse(req.url, true);
  315. const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
  316. if (!authorization && !accessToken) {
  317. reject(new AuthenticationError('Missing access token'));
  318. return;
  319. }
  320. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  321. resolve(accountFromToken(token, req));
  322. });
  323. /**
  324. * @param {any} req
  325. * @returns {string|undefined}
  326. */
  327. const channelNameFromPath = req => {
  328. const { path, query } = req;
  329. const onlyMedia = isTruthy(query.only_media);
  330. switch (path) {
  331. case '/api/v1/streaming/user':
  332. return 'user';
  333. case '/api/v1/streaming/user/notification':
  334. return 'user:notification';
  335. case '/api/v1/streaming/public':
  336. return onlyMedia ? 'public:media' : 'public';
  337. case '/api/v1/streaming/public/local':
  338. return onlyMedia ? 'public:local:media' : 'public:local';
  339. case '/api/v1/streaming/public/remote':
  340. return onlyMedia ? 'public:remote:media' : 'public:remote';
  341. case '/api/v1/streaming/hashtag':
  342. return 'hashtag';
  343. case '/api/v1/streaming/hashtag/local':
  344. return 'hashtag:local';
  345. case '/api/v1/streaming/direct':
  346. return 'direct';
  347. case '/api/v1/streaming/list':
  348. return 'list';
  349. default:
  350. return undefined;
  351. }
  352. };
  353. /**
  354. * @param {http.IncomingMessage & ResolvedAccount} req
  355. * @param {import('pino').Logger} logger
  356. * @param {string|undefined} channelName
  357. * @returns {Promise.<void>}
  358. */
  359. const checkScopes = (req, logger, channelName) => new Promise((resolve, reject) => {
  360. logger.debug(`Checking OAuth scopes for ${channelName}`);
  361. // When accessing public channels, no scopes are needed
  362. if (channelName && PUBLIC_CHANNELS.includes(channelName)) {
  363. resolve();
  364. return;
  365. }
  366. // The `read` scope has the highest priority, if the token has it
  367. // then it can access all streams
  368. const requiredScopes = ['read'];
  369. // When accessing specifically the notifications stream,
  370. // we need a read:notifications, while in all other cases,
  371. // we can allow access with read:statuses. Mind that the
  372. // user stream will not contain notifications unless
  373. // the token has either read or read:notifications scope
  374. // as well, this is handled separately.
  375. if (channelName === 'user:notification') {
  376. requiredScopes.push('read:notifications');
  377. } else {
  378. requiredScopes.push('read:statuses');
  379. }
  380. if (req.scopes && requiredScopes.some(requiredScope => req.scopes.includes(requiredScope))) {
  381. resolve();
  382. return;
  383. }
  384. reject(new AuthenticationError('Access token does not have the required scopes'));
  385. });
  386. /**
  387. * @typedef SystemMessageHandlers
  388. * @property {function(): void} onKill
  389. */
  390. /**
  391. * @param {any} req
  392. * @param {SystemMessageHandlers} eventHandlers
  393. * @returns {SubscriptionListener}
  394. */
  395. const createSystemMessageListener = (req, eventHandlers) => {
  396. return message => {
  397. if (!message?.event) {
  398. return;
  399. }
  400. const { event } = message;
  401. req.log.debug(`System message for ${req.accountId}: ${event}`);
  402. if (event === 'kill') {
  403. req.log.debug(`Closing connection for ${req.accountId} due to expired access token`);
  404. eventHandlers.onKill();
  405. } else if (event === 'filters_changed') {
  406. req.log.debug(`Invalidating filters cache for ${req.accountId}`);
  407. req.cachedFilters = null;
  408. }
  409. };
  410. };
  411. /**
  412. * @param {http.IncomingMessage & ResolvedAccount} req
  413. * @param {http.OutgoingMessage} res
  414. */
  415. const subscribeHttpToSystemChannel = (req, res) => {
  416. const accessTokenChannelId = `timeline:access_token:${req.accessTokenId}`;
  417. const systemChannelId = `timeline:system:${req.accountId}`;
  418. const listener = createSystemMessageListener(req, {
  419. onKill() {
  420. res.end();
  421. },
  422. });
  423. res.on('close', () => {
  424. unsubscribe(accessTokenChannelId, listener);
  425. unsubscribe(systemChannelId, listener);
  426. metrics.connectedChannels.labels({ type: 'eventsource', channel: 'system' }).dec(2);
  427. });
  428. subscribe(accessTokenChannelId, listener);
  429. subscribe(systemChannelId, listener);
  430. metrics.connectedChannels.labels({ type: 'eventsource', channel: 'system' }).inc(2);
  431. };
  432. /**
  433. * @param {any} req
  434. * @param {any} res
  435. * @param {function(Error=): void} next
  436. */
  437. const authenticationMiddleware = (req, res, next) => {
  438. if (req.method === 'OPTIONS') {
  439. next();
  440. return;
  441. }
  442. const channelName = channelNameFromPath(req);
  443. // If no channelName can be found for the request, then we should terminate
  444. // the connection, as there's nothing to stream back
  445. if (!channelName) {
  446. next(new RequestError('Unknown channel requested'));
  447. return;
  448. }
  449. accountFromRequest(req).then(() => checkScopes(req, req.log, channelName)).then(() => {
  450. subscribeHttpToSystemChannel(req, res);
  451. }).then(() => {
  452. next();
  453. }).catch(err => {
  454. next(err);
  455. });
  456. };
  457. /**
  458. * @param {Error} err
  459. * @param {any} req
  460. * @param {any} res
  461. * @param {function(Error=): void} next
  462. */
  463. const errorMiddleware = (err, req, res, next) => {
  464. req.log.error({ err }, err.toString());
  465. if (res.headersSent) {
  466. next(err);
  467. return;
  468. }
  469. const {statusCode, errorMessage } = extractErrorStatusAndMessage(err);
  470. res.writeHead(statusCode, { 'Content-Type': 'application/json' });
  471. res.end(JSON.stringify({ error: errorMessage }));
  472. };
  473. /**
  474. * @param {any[]} arr
  475. * @param {number=} shift
  476. * @returns {string}
  477. */
  478. // @ts-ignore
  479. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  480. /**
  481. * @param {string} listId
  482. * @param {any} req
  483. * @returns {Promise.<void>}
  484. */
  485. const authorizeListAccess = async (listId, req) => {
  486. const { accountId } = req;
  487. const result = await pgPool.query('SELECT id, account_id FROM lists WHERE id = $1 AND account_id = $2 LIMIT 1', [listId, accountId]);
  488. if (result.rows.length === 0) {
  489. throw new AuthenticationError('List not found');
  490. }
  491. };
  492. /**
  493. * @param {string[]} channelIds
  494. * @param {http.IncomingMessage & ResolvedAccount} req
  495. * @param {import('pino').Logger} log
  496. * @param {function(string, string): void} output
  497. * @param {undefined | function(string[], SubscriptionListener): void} attachCloseHandler
  498. * @param {'websocket' | 'eventsource'} destinationType
  499. * @param {boolean=} needsFiltering
  500. * @returns {SubscriptionListener}
  501. */
  502. const streamFrom = (channelIds, req, log, output, attachCloseHandler, destinationType, needsFiltering = false) => {
  503. log.info({ channelIds }, `Starting stream`);
  504. /**
  505. * @param {string} event
  506. * @param {object|string} payload
  507. */
  508. const transmit = (event, payload) => {
  509. // TODO: Replace "string"-based delete payloads with object payloads:
  510. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  511. metrics.messagesSent.labels({ type: destinationType }).inc(1);
  512. log.debug({ event, payload }, `Transmitting ${event} to ${req.accountId}`);
  513. output(event, encodedPayload);
  514. };
  515. // The listener used to process each message off the redis subscription,
  516. // message here is an object with an `event` and `payload` property. Some
  517. // events also include a queued_at value, but this is being removed shortly.
  518. /** @type {SubscriptionListener} */
  519. const listener = message => {
  520. if (!message?.event || !message?.payload) {
  521. return;
  522. }
  523. const { event, payload } = message;
  524. // Streaming only needs to apply filtering to some channels and only to
  525. // some events. This is because majority of the filtering happens on the
  526. // Ruby on Rails side when producing the event for streaming.
  527. //
  528. // The only events that require filtering from the streaming server are
  529. // `update` and `status.update`, all other events are transmitted to the
  530. // client as soon as they're received (pass-through).
  531. //
  532. // The channels that need filtering are determined in the function
  533. // `channelNameToIds` defined below:
  534. if (!needsFiltering || (event !== 'update' && event !== 'status.update')) {
  535. transmit(event, payload);
  536. return;
  537. }
  538. // The rest of the logic from here on in this function is to handle
  539. // filtering of statuses:
  540. // Filter based on language:
  541. if (Array.isArray(req.chosenLanguages) && payload.language !== null && req.chosenLanguages.indexOf(payload.language) === -1) {
  542. log.debug(`Message ${payload.id} filtered by language (${payload.language})`);
  543. return;
  544. }
  545. // When the account is not logged in, it is not necessary to confirm the block or mute
  546. if (!req.accountId) {
  547. transmit(event, payload);
  548. return;
  549. }
  550. // Filter based on domain blocks, blocks, mutes, or custom filters:
  551. // @ts-ignore
  552. const targetAccountIds = [payload.account.id].concat(payload.mentions.map(item => item.id));
  553. const accountDomain = payload.account.acct.split('@')[1];
  554. // TODO: Move this logic out of the message handling loop
  555. pgPool.connect((err, client, releasePgConnection) => {
  556. if (err) {
  557. log.error(err);
  558. return;
  559. }
  560. const queries = [
  561. // @ts-ignore
  562. client.query(`SELECT 1
  563. FROM blocks
  564. WHERE (account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)}))
  565. OR (account_id = $2 AND target_account_id = $1)
  566. UNION
  567. SELECT 1
  568. FROM mutes
  569. WHERE account_id = $1
  570. AND target_account_id IN (${placeholders(targetAccountIds, 2)})`, [req.accountId, payload.account.id].concat(targetAccountIds)),
  571. ];
  572. if (accountDomain) {
  573. // @ts-ignore
  574. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  575. }
  576. // @ts-ignore
  577. if (!payload.filtered && !req.cachedFilters) {
  578. // @ts-ignore
  579. queries.push(client.query('SELECT filter.id AS id, filter.phrase AS title, filter.context AS context, filter.expires_at AS expires_at, filter.action AS filter_action, keyword.keyword AS keyword, keyword.whole_word AS whole_word FROM custom_filter_keywords keyword JOIN custom_filters filter ON keyword.custom_filter_id = filter.id WHERE filter.account_id = $1 AND (filter.expires_at IS NULL OR filter.expires_at > NOW())', [req.accountId]));
  580. }
  581. Promise.all(queries).then(values => {
  582. releasePgConnection();
  583. // Handling blocks & mutes and domain blocks: If one of those applies,
  584. // then we don't transmit the payload of the event to the client
  585. if (values[0].rows.length > 0 || (accountDomain && values[1].rows.length > 0)) {
  586. return;
  587. }
  588. // If the payload already contains the `filtered` property, it means
  589. // that filtering has been applied on the ruby on rails side, as
  590. // such, we don't need to construct or apply the filters in streaming:
  591. if (Object.hasOwn(payload, "filtered")) {
  592. transmit(event, payload);
  593. return;
  594. }
  595. // Handling for constructing the custom filters and caching them on the request
  596. // TODO: Move this logic out of the message handling lifecycle
  597. // @ts-ignore
  598. if (!req.cachedFilters) {
  599. const filterRows = values[accountDomain ? 2 : 1].rows;
  600. // @ts-ignore
  601. req.cachedFilters = filterRows.reduce((cache, filter) => {
  602. if (cache[filter.id]) {
  603. cache[filter.id].keywords.push([filter.keyword, filter.whole_word]);
  604. } else {
  605. cache[filter.id] = {
  606. keywords: [[filter.keyword, filter.whole_word]],
  607. expires_at: filter.expires_at,
  608. filter: {
  609. id: filter.id,
  610. title: filter.title,
  611. context: filter.context,
  612. expires_at: filter.expires_at,
  613. // filter.filter_action is the value from the
  614. // custom_filters.action database column, it is an integer
  615. // representing a value in an enum defined by Ruby on Rails:
  616. //
  617. // enum { warn: 0, hide: 1 }
  618. filter_action: ['warn', 'hide'][filter.filter_action],
  619. },
  620. };
  621. }
  622. return cache;
  623. }, {});
  624. // Construct the regular expressions for the custom filters: This
  625. // needs to be done in a separate loop as the database returns one
  626. // filterRow per keyword, so we need all the keywords before
  627. // constructing the regular expression
  628. // @ts-ignore
  629. Object.keys(req.cachedFilters).forEach((key) => {
  630. // @ts-ignore
  631. req.cachedFilters[key].regexp = new RegExp(req.cachedFilters[key].keywords.map(([keyword, whole_word]) => {
  632. let expr = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  633. if (whole_word) {
  634. if (/^[\w]/.test(expr)) {
  635. expr = `\\b${expr}`;
  636. }
  637. if (/[\w]$/.test(expr)) {
  638. expr = `${expr}\\b`;
  639. }
  640. }
  641. return expr;
  642. }).join('|'), 'i');
  643. });
  644. }
  645. // Apply cachedFilters against the payload, constructing a
  646. // `filter_results` array of FilterResult entities
  647. // @ts-ignore
  648. if (req.cachedFilters) {
  649. const status = payload;
  650. // TODO: Calculate searchableContent in Ruby on Rails:
  651. // @ts-ignore
  652. const searchableContent = ([status.spoiler_text || '', status.content].concat((status.poll && status.poll.options) ? status.poll.options.map(option => option.title) : [])).concat(status.media_attachments.map(att => att.description)).join('\n\n').replace(/<br\s*\/?>/g, '\n').replace(/<\/p><p>/g, '\n\n');
  653. const searchableTextContent = JSDOM.fragment(searchableContent).textContent;
  654. const now = new Date();
  655. // @ts-ignore
  656. const filter_results = Object.values(req.cachedFilters).reduce((results, cachedFilter) => {
  657. // Check the filter hasn't expired before applying:
  658. if (cachedFilter.expires_at !== null && cachedFilter.expires_at < now) {
  659. return results;
  660. }
  661. // Just in-case JSDOM fails to find textContent in searchableContent
  662. if (!searchableTextContent) {
  663. return results;
  664. }
  665. const keyword_matches = searchableTextContent.match(cachedFilter.regexp);
  666. if (keyword_matches) {
  667. // results is an Array of FilterResult; status_matches is always
  668. // null as we only are only applying the keyword-based custom
  669. // filters, not the status-based custom filters.
  670. // https://docs.joinmastodon.org/entities/FilterResult/
  671. results.push({
  672. filter: cachedFilter.filter,
  673. keyword_matches,
  674. status_matches: null
  675. });
  676. }
  677. return results;
  678. }, []);
  679. // Send the payload + the FilterResults as the `filtered` property
  680. // to the streaming connection. To reach this code, the `event` must
  681. // have been either `update` or `status.update`, meaning the
  682. // `payload` is a Status entity, which has a `filtered` property:
  683. //
  684. // filtered: https://docs.joinmastodon.org/entities/Status/#filtered
  685. transmit(event, {
  686. ...payload,
  687. filtered: filter_results
  688. });
  689. } else {
  690. transmit(event, payload);
  691. }
  692. }).catch(err => {
  693. log.error(err);
  694. releasePgConnection();
  695. });
  696. });
  697. };
  698. channelIds.forEach(id => {
  699. subscribe(id, listener);
  700. });
  701. if (typeof attachCloseHandler === 'function') {
  702. attachCloseHandler(channelIds, listener);
  703. }
  704. return listener;
  705. };
  706. /**
  707. * @param {any} req
  708. * @param {any} res
  709. * @returns {function(string, string): void}
  710. */
  711. const streamToHttp = (req, res) => {
  712. const channelName = channelNameFromPath(req);
  713. metrics.connectedClients.labels({ type: 'eventsource' }).inc();
  714. // In theory we'll always have a channel name, but channelNameFromPath can return undefined:
  715. if (typeof channelName === 'string') {
  716. metrics.connectedChannels.labels({ type: 'eventsource', channel: channelName }).inc();
  717. }
  718. res.setHeader('Content-Type', 'text/event-stream');
  719. res.setHeader('Cache-Control', 'private, no-store');
  720. res.setHeader('Transfer-Encoding', 'chunked');
  721. res.write(':)\n');
  722. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  723. req.on('close', () => {
  724. req.log.info({ accountId: req.accountId }, `Ending stream`);
  725. // We decrement these counters here instead of in streamHttpEnd as in that
  726. // method we don't have knowledge of the channel names
  727. metrics.connectedClients.labels({ type: 'eventsource' }).dec();
  728. // In theory we'll always have a channel name, but channelNameFromPath can return undefined:
  729. if (typeof channelName === 'string') {
  730. metrics.connectedChannels.labels({ type: 'eventsource', channel: channelName }).dec();
  731. }
  732. clearInterval(heartbeat);
  733. });
  734. return (event, payload) => {
  735. res.write(`event: ${event}\n`);
  736. res.write(`data: ${payload}\n\n`);
  737. };
  738. };
  739. /**
  740. * @param {any} req
  741. * @param {function(): void} [closeHandler]
  742. * @returns {function(string[], SubscriptionListener): void}
  743. */
  744. const streamHttpEnd = (req, closeHandler = undefined) => (ids, listener) => {
  745. req.on('close', () => {
  746. ids.forEach(id => {
  747. unsubscribe(id, listener);
  748. });
  749. if (closeHandler) {
  750. closeHandler();
  751. }
  752. });
  753. };
  754. /**
  755. * @param {http.IncomingMessage} req
  756. * @param {import('ws').WebSocket} ws
  757. * @param {string[]} streamName
  758. * @returns {function(string, string): void}
  759. */
  760. const streamToWs = (req, ws, streamName) => (event, payload) => {
  761. if (ws.readyState !== ws.OPEN) {
  762. req.log.error('Tried writing to closed socket');
  763. return;
  764. }
  765. const message = JSON.stringify({ stream: streamName, event, payload });
  766. ws.send(message, (/** @type {Error|undefined} */ err) => {
  767. if (err) {
  768. req.log.error({err}, `Failed to send to websocket`);
  769. }
  770. });
  771. };
  772. /**
  773. * @param {http.ServerResponse} res
  774. */
  775. const httpNotFound = res => {
  776. res.writeHead(404, { 'Content-Type': 'application/json' });
  777. res.end(JSON.stringify({ error: 'Not found' }));
  778. };
  779. const api = express.Router();
  780. app.use(api);
  781. api.use(authenticationMiddleware);
  782. api.use(errorMiddleware);
  783. api.get('/api/v1/streaming/*', (req, res) => {
  784. const channelName = channelNameFromPath(req);
  785. // FIXME: In theory we'd never actually reach here due to
  786. // authenticationMiddleware catching this case, however, we need to refactor
  787. // how those middlewares work, so I'm adding the extra check in here.
  788. if (!channelName) {
  789. httpNotFound(res);
  790. return;
  791. }
  792. channelNameToIds(req, channelName, req.query).then(({ channelIds, options }) => {
  793. const onSend = streamToHttp(req, res);
  794. const onEnd = streamHttpEnd(req, subscriptionHeartbeat(channelIds));
  795. // @ts-ignore
  796. streamFrom(channelIds, req, req.log, onSend, onEnd, 'eventsource', options.needsFiltering);
  797. }).catch(err => {
  798. const {statusCode, errorMessage } = extractErrorStatusAndMessage(err);
  799. res.log.info({ err }, 'Eventsource subscription error');
  800. res.writeHead(statusCode, { 'Content-Type': 'application/json' });
  801. res.end(JSON.stringify({ error: errorMessage }));
  802. });
  803. });
  804. /**
  805. * @typedef StreamParams
  806. * @property {string} [tag]
  807. * @property {string} [list]
  808. * @property {string} [only_media]
  809. */
  810. /**
  811. * @param {any} req
  812. * @returns {string[]}
  813. */
  814. const channelsForUserStream = req => {
  815. const arr = [`timeline:${req.accountId}`];
  816. if (isInScope(req, ['read', 'read:notifications'])) {
  817. arr.push(`timeline:${req.accountId}:notifications`);
  818. }
  819. return arr;
  820. };
  821. /**
  822. * @param {any} req
  823. * @param {string} name
  824. * @param {StreamParams} params
  825. * @returns {Promise.<{ channelIds: string[], options: { needsFiltering: boolean } }>}
  826. */
  827. const channelNameToIds = (req, name, params) => new Promise((resolve, reject) => {
  828. switch (name) {
  829. case 'user':
  830. resolve({
  831. channelIds: channelsForUserStream(req),
  832. options: { needsFiltering: false },
  833. });
  834. break;
  835. case 'user:notification':
  836. resolve({
  837. channelIds: [`timeline:${req.accountId}:notifications`],
  838. options: { needsFiltering: false },
  839. });
  840. break;
  841. case 'public':
  842. resolve({
  843. channelIds: ['timeline:public'],
  844. options: { needsFiltering: true },
  845. });
  846. break;
  847. case 'public:local':
  848. resolve({
  849. channelIds: ['timeline:public:local'],
  850. options: { needsFiltering: true },
  851. });
  852. break;
  853. case 'public:remote':
  854. resolve({
  855. channelIds: ['timeline:public:remote'],
  856. options: { needsFiltering: true },
  857. });
  858. break;
  859. case 'public:media':
  860. resolve({
  861. channelIds: ['timeline:public:media'],
  862. options: { needsFiltering: true },
  863. });
  864. break;
  865. case 'public:local:media':
  866. resolve({
  867. channelIds: ['timeline:public:local:media'],
  868. options: { needsFiltering: true },
  869. });
  870. break;
  871. case 'public:remote:media':
  872. resolve({
  873. channelIds: ['timeline:public:remote:media'],
  874. options: { needsFiltering: true },
  875. });
  876. break;
  877. case 'direct':
  878. resolve({
  879. channelIds: [`timeline:direct:${req.accountId}`],
  880. options: { needsFiltering: false },
  881. });
  882. break;
  883. case 'hashtag':
  884. if (!params.tag) {
  885. reject(new RequestError('Missing tag name parameter'));
  886. } else {
  887. resolve({
  888. channelIds: [`timeline:hashtag:${normalizeHashtag(params.tag)}`],
  889. options: { needsFiltering: true },
  890. });
  891. }
  892. break;
  893. case 'hashtag:local':
  894. if (!params.tag) {
  895. reject(new RequestError('Missing tag name parameter'));
  896. } else {
  897. resolve({
  898. channelIds: [`timeline:hashtag:${normalizeHashtag(params.tag)}:local`],
  899. options: { needsFiltering: true },
  900. });
  901. }
  902. break;
  903. case 'list':
  904. if (!params.list) {
  905. reject(new RequestError('Missing list name parameter'));
  906. return;
  907. }
  908. authorizeListAccess(params.list, req).then(() => {
  909. resolve({
  910. channelIds: [`timeline:list:${params.list}`],
  911. options: { needsFiltering: false },
  912. });
  913. }).catch(() => {
  914. reject(new AuthenticationError('Not authorized to stream this list'));
  915. });
  916. break;
  917. default:
  918. reject(new RequestError('Unknown stream type'));
  919. }
  920. });
  921. /**
  922. * @param {string} channelName
  923. * @param {StreamParams} params
  924. * @returns {string[]}
  925. */
  926. const streamNameFromChannelName = (channelName, params) => {
  927. if (channelName === 'list' && params.list) {
  928. return [channelName, params.list];
  929. } else if (['hashtag', 'hashtag:local'].includes(channelName) && params.tag) {
  930. return [channelName, params.tag];
  931. } else {
  932. return [channelName];
  933. }
  934. };
  935. /**
  936. * @typedef WebSocketSession
  937. * @property {import('ws').WebSocket & { isAlive: boolean}} websocket
  938. * @property {http.IncomingMessage & ResolvedAccount} request
  939. * @property {import('pino').Logger} logger
  940. * @property {Object.<string, { channelName: string, listener: SubscriptionListener, stopHeartbeat: function(): void }>} subscriptions
  941. */
  942. /**
  943. * @param {WebSocketSession} session
  944. * @param {string} channelName
  945. * @param {StreamParams} params
  946. * @returns {void}
  947. */
  948. const subscribeWebsocketToChannel = ({ websocket, request, logger, subscriptions }, channelName, params) => {
  949. checkScopes(request, logger, channelName).then(() => channelNameToIds(request, channelName, params)).then(({
  950. channelIds,
  951. options,
  952. }) => {
  953. if (subscriptions[channelIds.join(';')]) {
  954. return;
  955. }
  956. const onSend = streamToWs(request, websocket, streamNameFromChannelName(channelName, params));
  957. const stopHeartbeat = subscriptionHeartbeat(channelIds);
  958. const listener = streamFrom(channelIds, request, logger, onSend, undefined, 'websocket', options.needsFiltering);
  959. metrics.connectedChannels.labels({ type: 'websocket', channel: channelName }).inc();
  960. subscriptions[channelIds.join(';')] = {
  961. channelName,
  962. listener,
  963. stopHeartbeat,
  964. };
  965. }).catch(err => {
  966. const {statusCode, errorMessage } = extractErrorStatusAndMessage(err);
  967. logger.error({ err }, 'Websocket subscription error');
  968. // If we have a socket that is alive and open still, send the error back to the client:
  969. if (websocket.isAlive && websocket.readyState === websocket.OPEN) {
  970. websocket.send(JSON.stringify({
  971. error: errorMessage,
  972. status: statusCode
  973. }));
  974. }
  975. });
  976. };
  977. /**
  978. * @param {WebSocketSession} session
  979. * @param {string[]} channelIds
  980. */
  981. const removeSubscription = ({ request, logger, subscriptions }, channelIds) => {
  982. logger.info({ channelIds, accountId: request.accountId }, `Ending stream`);
  983. const subscription = subscriptions[channelIds.join(';')];
  984. if (!subscription) {
  985. return;
  986. }
  987. channelIds.forEach(channelId => {
  988. unsubscribe(channelId, subscription.listener);
  989. });
  990. metrics.connectedChannels.labels({ type: 'websocket', channel: subscription.channelName }).dec();
  991. subscription.stopHeartbeat();
  992. delete subscriptions[channelIds.join(';')];
  993. };
  994. /**
  995. * @param {WebSocketSession} session
  996. * @param {string} channelName
  997. * @param {StreamParams} params
  998. * @returns {void}
  999. */
  1000. const unsubscribeWebsocketFromChannel = (session, channelName, params) => {
  1001. const { websocket, request, logger } = session;
  1002. channelNameToIds(request, channelName, params).then(({ channelIds }) => {
  1003. removeSubscription(session, channelIds);
  1004. }).catch(err => {
  1005. logger.error({err}, 'Websocket unsubscribe error');
  1006. // If we have a socket that is alive and open still, send the error back to the client:
  1007. if (websocket.isAlive && websocket.readyState === websocket.OPEN) {
  1008. // TODO: Use a better error response here
  1009. websocket.send(JSON.stringify({ error: "Error unsubscribing from channel" }));
  1010. }
  1011. });
  1012. };
  1013. /**
  1014. * @param {WebSocketSession} session
  1015. */
  1016. const subscribeWebsocketToSystemChannel = ({ websocket, request, subscriptions }) => {
  1017. const accessTokenChannelId = `timeline:access_token:${request.accessTokenId}`;
  1018. const systemChannelId = `timeline:system:${request.accountId}`;
  1019. const listener = createSystemMessageListener(request, {
  1020. onKill() {
  1021. websocket.close();
  1022. },
  1023. });
  1024. subscribe(accessTokenChannelId, listener);
  1025. subscribe(systemChannelId, listener);
  1026. subscriptions[accessTokenChannelId] = {
  1027. channelName: 'system',
  1028. listener,
  1029. stopHeartbeat: () => {
  1030. },
  1031. };
  1032. subscriptions[systemChannelId] = {
  1033. channelName: 'system',
  1034. listener,
  1035. stopHeartbeat: () => {
  1036. },
  1037. };
  1038. metrics.connectedChannels.labels({ type: 'websocket', channel: 'system' }).inc(2);
  1039. };
  1040. /**
  1041. * @param {import('ws').WebSocket & { isAlive: boolean }} ws
  1042. * @param {http.IncomingMessage & ResolvedAccount} req
  1043. * @param {import('pino').Logger} log
  1044. */
  1045. function onConnection(ws, req, log) {
  1046. // Note: url.parse could throw, which would terminate the connection, so we
  1047. // increment the connected clients metric straight away when we establish
  1048. // the connection, without waiting:
  1049. metrics.connectedClients.labels({ type: 'websocket' }).inc();
  1050. // Setup connection keep-alive state:
  1051. ws.isAlive = true;
  1052. ws.on('pong', () => {
  1053. ws.isAlive = true;
  1054. });
  1055. /**
  1056. * @type {WebSocketSession}
  1057. */
  1058. const session = {
  1059. websocket: ws,
  1060. request: req,
  1061. logger: log,
  1062. subscriptions: {},
  1063. };
  1064. ws.on('close', function onWebsocketClose() {
  1065. const subscriptions = Object.keys(session.subscriptions);
  1066. subscriptions.forEach(channelIds => {
  1067. removeSubscription(session, channelIds.split(';'));
  1068. });
  1069. // Decrement the metrics for connected clients:
  1070. metrics.connectedClients.labels({ type: 'websocket' }).dec();
  1071. // We need to unassign the session object as to ensure it correctly gets
  1072. // garbage collected, without doing this we could accidentally hold on to
  1073. // references to the websocket, the request, and the logger, causing
  1074. // memory leaks.
  1075. // This is commented out because `delete` only operated on object properties
  1076. // It needs to be replaced by `session = undefined`, but it requires every calls to
  1077. // `session` to check for it, thus a significant refactor
  1078. // delete session;
  1079. });
  1080. // Note: immediately after the `error` event is emitted, the `close` event
  1081. // is emitted. As such, all we need to do is log the error here.
  1082. ws.on('error', (/** @type {Error} */ err) => {
  1083. log.error(err);
  1084. });
  1085. ws.on('message', (data, isBinary) => {
  1086. if (isBinary) {
  1087. log.warn('Received binary data, closing connection');
  1088. ws.close(1003, 'The mastodon streaming server does not support binary messages');
  1089. return;
  1090. }
  1091. const message = data.toString('utf8');
  1092. const json = parseJSON(message, session.request);
  1093. if (!json) return;
  1094. const { type, stream, ...params } = json;
  1095. if (type === 'subscribe') {
  1096. subscribeWebsocketToChannel(session, firstParam(stream), params);
  1097. } else if (type === 'unsubscribe') {
  1098. unsubscribeWebsocketFromChannel(session, firstParam(stream), params);
  1099. } else {
  1100. // Unknown action type
  1101. }
  1102. });
  1103. subscribeWebsocketToSystemChannel(session);
  1104. // Parse the URL for the connection arguments (if supplied), url.parse can throw:
  1105. const location = req.url && url.parse(req.url, true);
  1106. if (location && location.query.stream) {
  1107. subscribeWebsocketToChannel(session, firstParam(location.query.stream), location.query);
  1108. }
  1109. }
  1110. wss.on('connection', onConnection);
  1111. setInterval(() => {
  1112. wss.clients.forEach(ws => {
  1113. // @ts-ignore
  1114. if (ws.isAlive === false) {
  1115. ws.terminate();
  1116. return;
  1117. }
  1118. // @ts-ignore
  1119. ws.isAlive = false;
  1120. ws.ping('', false);
  1121. });
  1122. }, 30000);
  1123. attachServerWithConfig(server, address => {
  1124. logger.info(`Streaming API now listening on ${address}`);
  1125. });
  1126. const onExit = () => {
  1127. server.close();
  1128. process.exit(0);
  1129. };
  1130. /** @param {Error} err */
  1131. const onError = (err) => {
  1132. logger.error(err);
  1133. server.close();
  1134. process.exit(0);
  1135. };
  1136. process.on('SIGINT', onExit);
  1137. process.on('SIGTERM', onExit);
  1138. process.on('exit', onExit);
  1139. process.on('uncaughtException', onError);
  1140. };
  1141. /**
  1142. * @param {any} server
  1143. * @param {function(string): void} [onSuccess]
  1144. */
  1145. const attachServerWithConfig = (server, onSuccess) => {
  1146. if (process.env.SOCKET) {
  1147. server.listen(process.env.SOCKET, () => {
  1148. if (onSuccess) {
  1149. fs.chmodSync(server.address(), 0o666);
  1150. onSuccess(server.address());
  1151. }
  1152. });
  1153. } else {
  1154. const port = +(process.env.PORT || 4000);
  1155. let bind = process.env.BIND ?? '127.0.0.1';
  1156. // Web uses the URI syntax for BIND, which means IPv6 addresses may
  1157. // be wrapped in square brackets:
  1158. if (bind.startsWith('[') && bind.endsWith(']')) {
  1159. bind = bind.slice(1, -1);
  1160. }
  1161. server.listen(port, bind, () => {
  1162. if (onSuccess) {
  1163. onSuccess(`${server.address().address}:${server.address().port}`);
  1164. }
  1165. });
  1166. }
  1167. };
  1168. startServer();