/** * API proxy for development — forwards /api/* to flights.test.aeroflot.ru * through the system HTTPS proxy (GOST at 127.0.0.1:8888). * * Run: node scripts/api-proxy.mjs * Listens on port 4201. */ import http from "node:http"; import https from "node:https"; import { URL } from "node:url"; const TARGET = "flights.test.aeroflot.ru"; const PORT = 4201; const SYSTEM_PROXY = process.env.https_proxy || process.env.HTTPS_PROXY || ""; function proxyViaConnect(req, res) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "*"); if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; } if (SYSTEM_PROXY) { // Use HTTP CONNECT tunnel through system proxy const proxyUrl = new URL(SYSTEM_PROXY); const connectReq = http.request({ host: proxyUrl.hostname, port: parseInt(proxyUrl.port || "8888"), method: "CONNECT", path: `${TARGET}:443`, }); connectReq.on("connect", (_connectRes, socket) => { const options = { hostname: TARGET, path: req.url, method: req.method, headers: { host: TARGET, accept: "application/json, text/plain, */*", "accept-language": "ru", }, socket, agent: false, }; const targetReq = https.request(options, (targetRes) => { const headers = { ...targetRes.headers, "access-control-allow-origin": "*" }; delete headers["transfer-encoding"]; res.writeHead(targetRes.statusCode ?? 200, headers); targetRes.pipe(res, { end: true }); }); targetReq.on("error", (err) => { res.writeHead(502, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: err.message })); }); req.pipe(targetReq, { end: true }); }); connectReq.on("error", (err) => { res.writeHead(502, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: `Proxy connect error: ${err.message}` })); }); connectReq.end(); } else { // Direct HTTPS without system proxy const options = { hostname: TARGET, port: 443, path: req.url, method: req.method, headers: { host: TARGET, accept: "application/json, text/plain, */*", "accept-language": "ru", }, }; const targetReq = https.request(options, (targetRes) => { res.writeHead(targetRes.statusCode ?? 200, { ...targetRes.headers, "access-control-allow-origin": "*", }); targetRes.pipe(res, { end: true }); }); targetReq.on("error", (err) => { res.writeHead(502, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: err.message })); }); req.pipe(targetReq, { end: true }); } } const server = http.createServer(proxyViaConnect); server.listen(PORT, () => { console.log(`API proxy on http://localhost:${PORT} → https://${TARGET}`); if (SYSTEM_PROXY) console.log(`Using system proxy: ${SYSTEM_PROXY}`); });