File size: 6,005 Bytes
c157047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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);
});