import express from "express"; import httpProxy from "http-proxy"; const TARGET = process.env.TARGET_URL; const TOKEN = process.env.HF_TOKEN_PRIVATE_SPACE; if (!TARGET || !TOKEN) { console.error("❌ Missing TARGET_URL or HF_TOKEN_PRIVATE_SPACE"); process.exit(1); } const app = express(); // Parse the target URL const targetUrl = new URL(TARGET); // Create proxy with WebSocket + headers const proxy = httpProxy.createProxyServer({ target: TARGET, changeOrigin: true, ws: true, secure: true, xfwd: true, autoRewrite: true, // Important: automatically rewrite Location header protocolRewrite: 'https' // Ensure HTTPS in redirects }); // --- DEBUG LOGGING ----------------------------------------------------------- app.use((req, res, next) => { console.log(`âžĄī¸ ${req.method} ${req.originalUrl}`); console.log(" Host:", req.headers.host); console.log(" Referer:", req.headers.referer); next(); }); // --- CRITICAL: Prevent redirect loops --- proxy.on("proxyReq", (proxyReq, req) => { // Add authorization proxyReq.setHeader("Authorization", `Bearer ${TOKEN}`); // Preserve important headers const publicHost = req.headers["x-forwarded-host"] || req.headers.host; const publicProto = req.headers["x-forwarded-proto"] || "https"; // Set forwarding headers so LibreChat knows the original request context proxyReq.setHeader("X-Forwarded-Host", publicHost); proxyReq.setHeader("X-Forwarded-Proto", publicProto); proxyReq.setHeader("X-Forwarded-For", req.connection.remoteAddress); proxyReq.setHeader("X-Real-IP", req.connection.remoteAddress); // IMPORTANT: Rewrite Referer header if it points to our public URL if (req.headers.referer) { const referer = req.headers.referer; if (referer.includes(publicHost)) { const newReferer = referer.replace(`https://${publicHost}`, TARGET).replace(`http://${publicHost}`, TARGET); proxyReq.setHeader("Referer", newReferer); console.log(" 🔄 Rewriting Referer:", referer, "->", newReferer); } } // IMPORTANT: Rewrite Origin header if present if (req.headers.origin) { const origin = req.headers.origin; if (origin.includes(publicHost)) { proxyReq.setHeader("Origin", TARGET); console.log(" 🔄 Rewriting Origin:", origin, "->", TARGET); } } console.log(`🔐 Forwarding -> ${TARGET}${req.url}`); }); proxy.on("proxyRes", (proxyRes, req, res) => { console.log(`âŦ…ī¸ Response ${proxyRes.statusCode} from ${TARGET}${req.url}`); // Get the public URL base const publicHost = (req.headers["x-forwarded-host"] || req.headers.host || "").toString(); const publicProto = req.headers["x-forwarded-proto"] || "https"; const publicBase = publicHost ? `${publicProto}://${publicHost}` : null; // --- FIX 1: Handle Location redirects --- if (proxyRes.headers["location"]) { const location = proxyRes.headers["location"]; console.log(" 🧭 Original Location:", location); // Rewrite absolute URLs pointing to target if (location.startsWith(TARGET)) { proxyRes.headers["location"] = location.replace(TARGET, publicBase); console.log(" ✅ Rewritten to:", proxyRes.headers["location"]); } // Handle protocol-relative or absolute paths else if (location.startsWith("/")) { proxyRes.headers["location"] = `${publicBase}${location}`; console.log(" ✅ Rewritten to:", proxyRes.headers["location"]); } // If it already points to our public URL, leave it alone else if (location.startsWith(publicBase)) { console.log(" â„šī¸ Already points to public URL, keeping as-is"); } } // --- FIX 2: Fix cookies --- const setCookies = proxyRes.headers["set-cookie"]; if (Array.isArray(setCookies) && publicHost) { console.log(" đŸĒ Processing", setCookies.length, "cookies"); proxyRes.headers["set-cookie"] = setCookies.map((cookie) => { let newCookie = cookie; // Remove or replace Domain attribute to match public host if (/;\s*Domain=/i.test(newCookie)) { // Remove the target domain newCookie = newCookie.replace(/;\s*Domain=[^;]*/i, ""); } // Add our public domain (without leading dot for exact match) newCookie = `${newCookie}; Domain=${publicHost}`; // Ensure Secure flag (required for SameSite=None) if (!/;\s*Secure/i.test(newCookie)) { newCookie = `${newCookie}; Secure`; } // Set SameSite=None for cross-site cookies (required for iframe/embed contexts) if (!/SameSite=/i.test(newCookie)) { newCookie = `${newCookie}; SameSite=None`; } else { newCookie = newCookie.replace(/SameSite=[^;]*/i, "SameSite=None"); } return newCookie; }); } // --- FIX 3: Add CORS headers if needed --- // This helps if LibreChat makes client-side requests if (!proxyRes.headers["access-control-allow-credentials"]) { proxyRes.headers["access-control-allow-credentials"] = "true"; } }); proxy.on("error", (err, req, res) => { console.error("❌ Proxy error:", err.message); console.error(" Stack:", err.stack); if (res && !res.headersSent) { res.status(502).json({ error: "Proxy Error", message: "Unable to reach the upstream server", details: err.message }); } }); // Health check endpoint (optional but useful) app.get("/health", (req, res) => { res.json({ status: "ok", target: TARGET, timestamp: new Date().toISOString() }); }); // Forward everything else app.use((req, res) => proxy.web(req, res)); const server = app.listen(process.env.PORT || 7860, () => { console.log("✅ Proxy listening on port", process.env.PORT || 7860); console.log("đŸŽ¯ Target:", TARGET); console.log("🔐 Using HF token:", TOKEN ? "***" + TOKEN.slice(-4) : "MISSING"); }); server.on("upgrade", (req, socket, head) => { console.log("â†•ī¸ WebSocket upgrade:", req.url); proxy.ws(req, socket, head); });