File size: 4,736 Bytes
6e18e02
928c07f
96b5930
6e18e02
 
 
 
 
 
 
 
96b5930
 
 
 
 
 
8c8a0c5
 
2f78318
96b5930
7f99b73
44ea4f8
cbd3c77
96b5930
 
 
 
cbd3c77
6e18e02
 
 
 
 
 
 
2f78318
6e18e02
 
 
2f78318
6e18e02
2f78318
6e18e02
 
 
 
 
 
 
2f78318
6e18e02
96b5930
 
 
6e18e02
2f78318
6e18e02
 
2f78318
96b5930
 
 
 
 
 
cbd3c77
 
 
 
 
96b5930
 
 
cbd3c77
 
96b5930
 
2f78318
cbd3c77
96b5930
 
 
 
6e18e02
2f78318
96b5930
 
 
 
6e18e02
2f78318
96b5930
 
2f78318
 
 
 
 
96b5930
b50b822
2f78318
96b5930
b50b822
2f78318
 
 
b50b822
96b5930
 
2f78318
 
7f99b73
 
 
 
2f78318
6e18e02
 
 
 
 
 
 
2f78318
 
6e18e02
44ea4f8
 
96b5930
 
 
44ea4f8
96b5930
 
 
44ea4f8
928c07f
cbd3c77
6e18e02
96b5930
 
6e18e02
 
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
/**
 * Cloudflare Proxy: Transparent Fix for Blocked Domains
 *
 * Patches https.request to redirect traffic for Telegram/Discord
 * through a Cloudflare Worker proxy.
 */
"use strict";

const https = require("https");
const http = require("http");

let PROXY_URL = process.env.CLOUDFLARE_PROXY_URL;
if (
  PROXY_URL &&
  !PROXY_URL.startsWith("http://") &&
  !PROXY_URL.startsWith("https://")
) {
  PROXY_URL = `https://${PROXY_URL}`;
}

const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";
const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();

// Allow user to define what to proxy. Use "*" to proxy everything except internal HF traffic.
const PROXY_DOMAINS =
  process.env.CLOUDFLARE_PROXY_DOMAINS ||
  "api.telegram.org,discord.com,discordapp.com,gateway.discord.gg,status.discord.com";
const BLOCKED_DOMAINS = PROXY_DOMAINS.split(",").map((d) => d.trim());
const PROXY_ALL = PROXY_DOMAINS === "*";

if (PROXY_URL) {
  try {
    const proxy = new URL(PROXY_URL);
    const originalHttpsRequest = https.request;
    const originalHttpRequest = http.request;

    const patch = (original, isHttps) => {
      return function (options, callback) {
        let hostname = "";
        let path = "";
        let headers = {};

        // 1. Extract hostname and path from various possible input types
        if (typeof options === "string") {
          const u = new URL(options);
          hostname = u.hostname;
          path = u.pathname + u.search;
        } else if (options instanceof URL) {
          hostname = options.hostname;
          path = options.pathname + options.search;
          headers = options.headers || {};
        } else {
          hostname =
            options.hostname ||
            (options.host ? options.host.split(":")[0] : "");
          path = options.path || "/";
          headers = options.headers || {};
        }

        // 2. Check if we should intercept (and prevent recursion)
        const isInternal =
          hostname === "localhost" ||
          hostname === "127.0.0.1" ||
          hostname.endsWith(".hf.space") ||
          hostname.endsWith(".huggingface.co") ||
          hostname === "huggingface.co";

        let shouldProxy = false;
        if (PROXY_ALL) {
          shouldProxy = !isInternal;
        } else {
          shouldProxy = BLOCKED_DOMAINS.some(
            (domain) => hostname === domain || hostname.endsWith("." + domain),
          );
        }

        const alreadyProxied =
          options._proxied || (headers && headers["x-target-host"]);

        if (shouldProxy && !alreadyProxied) {
          if (DEBUG)
            console.log(
              `[cloudflare-proxy] Redirecting ${hostname}${path} -> ${proxy.hostname}`,
            );

          // 3. Create fresh options for the proxied request
          const newOptions =
            typeof options === "string" || options instanceof URL
              ? { protocol: "https:", path: path }
              : { ...options };

          // Ensure it's an object we can modify
          if (typeof newOptions !== "object")
            return original.apply(this, arguments);

          newOptions._proxied = true;
          newOptions.protocol = "https:";
          newOptions.hostname = proxy.hostname;
          newOptions.port = proxy.port || 443;

          // CRITICAL: Force fresh TLS handshake for the new domain
          newOptions.servername = proxy.hostname;
          delete newOptions.host; // Prefer hostname
          delete newOptions.agent; // Force a new agent to prevent connection reuse issues

          // Merge and update headers
          newOptions.headers = {
            ...(newOptions.headers || {}),
            host: proxy.host,
            "x-target-host": hostname,
          };

          if (PROXY_SHARED_SECRET) {
            newOptions.headers["x-proxy-key"] = PROXY_SHARED_SECRET;
          }

          // Always use HTTPS for the proxy connection
          return originalHttpsRequest.call(https, newOptions, callback);
        }

        return original.apply(this, arguments);
      };
    };

    https.request = patch(originalHttpsRequest, true);
    http.request = patch(originalHttpRequest, false);

    if (DEBUG) {
      if (PROXY_ALL) {
        console.log(
          `[cloudflare-proxy] Transparent proxy active in WILDCARD mode (Proxying ALL except HF internal)`,
        );
      } else {
        console.log(
          `[cloudflare-proxy] Transparent proxy active for: ${BLOCKED_DOMAINS.join(", ")}`,
        );
      }
      console.log(`[cloudflare-proxy] Target proxy: ${proxy.hostname}`);
    }
  } catch (e) {
    if (DEBUG)
      console.error(`[cloudflare-proxy] Failed to initialize: ${e.message}`);
  }
}