'use strict'; const http = require('node:http'); module.exports = function proxy({ statePort, rednotePort }) { return http.createServer((req, res) => { const mode = /^\/(state|rednote)(?:\/|\?|$)/.exec(req.url)?.[1]; if (!mode) { res.writeHead(404); return res.end('Not Found'); } if (req.url === '/' + mode) { res.writeHead(301, { Location: '/' + mode + '/' }); return res.end(); } const upstream = http.request({ host: '127.0.0.1', port: mode === 'state' ? statePort : rednotePort, method: req.method, path: req.url.slice(mode.length + 1) || '/', headers: { ...req.headers, 'x-real-ip': '127.0.0.1', 'x-forwarded-proto': 'http' } }, reply => { res.writeHead(reply.statusCode, reply.headers); reply.pipe(res); }); upstream.setTimeout(150000, () => upstream.destroy()); upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); }); req.pipe(upstream); }); };