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
c06c76a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
781eb05
c06c76a
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/**
 * Cloudflare Worker Reverse Proxy for PanelThTuanIT & Custom Zone Domains
 *
 * Deploy lên Cloudflare Workers rồi gắn Custom Domain (ví dụ: panel.yourdomain.com)
 * hoặc Wildcard Route (*yourdomain.com/*) để trỏ về Hugging Face Space.
 *
 * Biến môi trường tùy chọn trong Cloudflare Worker (Settings -> Variables):
 *   TARGET_HOST = "shadowfilebot-vscode.hf.space"
 */

const DEFAULT_TARGET_HOST = "shadowfilebot-vscode.hf.space";
const DEFAULT_PANEL_HOST = "panel.thtuanit.com";
const GATEWAY_ERROR_STATUSES = new Set([502, 503, 504, 520, 521, 522, 523, 524, 525, 526]);

const STATIC_META_PATHS = new Set([
  "/favicon.svg",
  "/favicon.ico",
  "/og-image.png",
  "/og-image.svg",
  "/manifest.json",
  "/robots.txt",
  "/sitemap.xml",
  "/llms.txt",
  "/.well-known/ard.json",
  "/.well-known/security.txt",
  "/googlecae40e84854ca067.html",
]);

const PANEL_BASE_CSP =
  "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests";

const PANEL_SECURITY_HEADERS = [
  ["Content-Security-Policy", PANEL_BASE_CSP],
  ["Strict-Transport-Security", "max-age=31536000; includeSubDomains"],
  ["X-Content-Type-Options", "nosniff"],
  ["X-Frame-Options", "SAMEORIGIN"],
  ["Cross-Origin-Opener-Policy", "same-origin-allow-popups"],
  ["Referrer-Policy", "strict-origin-when-cross-origin"],
];

function applyPanelSecurityHeaders(respHeaders) {
  for (const [name, value] of PANEL_SECURITY_HEADERS) {
    if (!respHeaders.has(name)) {
      respHeaders.set(name, value);
    }
  }
}

function generateCspNonce() {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  let bin = "";
  for (let i = 0; i < bytes.length; i++) {
    bin += String.fromCharCode(bytes[i]);
  }
  return btoa(bin);
}

function buildPanelCsp(nonce) {
  if (!nonce) return PANEL_BASE_CSP;
  return PANEL_BASE_CSP.replace("script-src 'self'", `script-src 'self' 'nonce-${nonce}'`);
}

function applyPanelHtmlNonceCsp(resp) {
  const ct = (resp.headers.get("content-type") || "").toLowerCase();
  if (!ct.includes("text/html") || typeof HTMLRewriter === "undefined") {
    return resp;
  }
  const nonce = generateCspNonce();
  const headers = new Headers(resp.headers);
  headers.set("Content-Security-Policy", buildPanelCsp(nonce));
  const rewritten = new HTMLRewriter()
    .on("script", {
      element(el) {
        el.setAttribute("nonce", nonce);
      },
    })
    .transform(resp);
  return new Response(rewritten.body, {
    status: rewritten.status,
    statusText: rewritten.statusText,
    headers,
  });
}

const PUBLIC_SEO_PATHS = new Set([
  "/",
  "/home",
  "/home/",
  "/about",
  "/about/",
  "/services",
  "/services/",
  "/guide",
  "/guide/",
  "/contact",
  "/contact/",
]);

function getStaticCacheControl(pathname) {
  if (pathname.startsWith("/_next/static/")) {
    return "public, max-age=31536000, immutable";
  }
  if (STATIC_META_PATHS.has(pathname)) {
    return "public, max-age=3600, stale-while-revalidate=86400";
  }
  if (PUBLIC_SEO_PATHS.has(pathname)) {
    return "public, max-age=300, s-maxage=1800, stale-while-revalidate=86400";
  }
  return null;
}

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function normalizeHost(raw) {
  return String(raw || "")
    .trim()
    .replace(/^https?:\/\//i, "")
    .split("/")[0]
    .trim();
}

function stripUpstreamHfLink(respHeaders) {
  const linkHeader = respHeaders.get("Link");
  if (!linkHeader) return;

  const kept = linkHeader
    .split(/,\s*(?=<)/)
    .map((entry) => entry.trim())
    .filter(
      (entry) =>
        entry &&
        !/^<https?:\/\/([^/>]*\.)?(huggingface\.co|hf\.space)(?:[/:>]|$)/i.test(entry)
    );

  if (kept.length > 0) {
    respHeaders.set("Link", kept.join(", "));
  } else {
    respHeaders.delete("Link");
  }
}

function escapeHtml(str) {
  return String(str || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function buildGatewayFallbackResponse(request, incomingUrl, originalHost) {
  const accept = (request.headers.get("Accept") || "").toLowerCase();
  const isApiOrJson =
    incomingUrl.pathname.startsWith("/api/") ||
    (accept.includes("application/json") && !accept.includes("text/html"));

  if (isApiOrJson) {
    return new Response(
      JSON.stringify({
        detail: "Hệ thống đang khởi động lại, vui lòng thử lại sau vài giây.",
      }),
      {
        status: 503,
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          "Cache-Control": "no-store",
          "Retry-After": "5",
        },
      }
    );
  }

  const safeHost = escapeHtml(normalizeHost(originalHost) || DEFAULT_PANEL_HOST);
  const html = `<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta http-equiv="refresh" content="5" />
  <meta name="robots" content="noindex, nofollow" />
  <title>Panel ThTuanIT — Đang khởi động lại</title>
  <style>
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 24px;
      background: #030712;
      color: #f3f4f6;
      font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
    }
    .card {
      width: 100%;
      max-width: 440px;
      background: #111827;
      border: 1px solid #1f2937;
      border-radius: 16px;
      padding: 28px;
      text-align: center;
      box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
    }
    .badge {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 9999px;
      background: rgba(124, 58, 237, 0.16);
      border: 1px solid rgba(139, 92, 246, 0.35);
      color: #c4b5fd;
      font-size: 12px;
      font-weight: 600;
      margin-bottom: 14px;
    }
    h1 { margin: 0 0 10px; font-size: 20px; font-weight: 700; color: #ffffff; }
    p { margin: 0 0 18px; font-size: 14px; line-height: 1.6; color: #9ca3af; }
    .host { color: #d1d5db; font-family: ui-monospace, monospace; font-size: 12px; }
    button {
      cursor: pointer;
      border: 0;
      border-radius: 10px;
      padding: 10px 18px;
      background: #7c3aed;
      color: #ffffff;
      font-size: 13px;
      font-weight: 600;
    }
    button:hover { background: #6d28d9; }
  </style>
</head>
<body>
  <main class="card">
    <div class="badge">Panel ThTuanIT</div>
    <h1>Máy chủ đang khởi động lại</h1>
    <p>Hệ thống đang cập nhật hoặc đánh thức container. Trang sẽ tự động tải lại sau vài giây.</p>
    <p class="host">${safeHost}</p>
    <button type="button" onclick="location.reload()">Tải lại ngay</button>
  </main>
</body>
</html>`;

  return new Response(html, {
    status: 503,
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-store",
      "Retry-After": "5",
      "X-Robots-Tag": "noindex, nofollow",
    },
  });
}

function safeCloseWs(ws, code, reason) {
  try {
    if (code === 1000 || (typeof code === "number" && code >= 3000 && code <= 4999)) {
      ws.close(code, typeof reason === "string" ? reason.slice(0, 123) : "");
    } else {
      ws.close();
    }
  } catch {}
}

function bridgeWebSocketResponse(upstreamResp) {
  if (typeof WebSocketPair === "undefined" || !upstreamResp.webSocket) {
    return upstreamResp;
  }

  const pair = new WebSocketPair();
  const [clientWs, serverWs] = Object.values(pair);
  const upstreamWs = upstreamResp.webSocket;

  serverWs.accept();
  upstreamWs.accept();

  serverWs.addEventListener("message", (event) => {
    try {
      upstreamWs.send(event.data);
    } catch {
      safeCloseWs(upstreamWs);
      safeCloseWs(serverWs);
    }
  });
  upstreamWs.addEventListener("message", (event) => {
    try {
      serverWs.send(event.data);
    } catch {
      safeCloseWs(serverWs);
      safeCloseWs(upstreamWs);
    }
  });

  serverWs.addEventListener("close", (event) => {
    safeCloseWs(upstreamWs, event.code, event.reason);
  });
  upstreamWs.addEventListener("close", (event) => {
    safeCloseWs(serverWs, event.code, event.reason);
  });

  serverWs.addEventListener("error", () => {
    safeCloseWs(upstreamWs);
    safeCloseWs(serverWs);
  });
  upstreamWs.addEventListener("error", () => {
    safeCloseWs(serverWs);
    safeCloseWs(upstreamWs);
  });

  const wsHeaders = new Headers();
  const wsProto = upstreamResp.headers.get("Sec-WebSocket-Protocol");
  if (wsProto) {
    wsHeaders.set("Sec-WebSocket-Protocol", wsProto);
  }

  return new Response(null, {
    status: 101,
    webSocket: clientWs,
    headers: wsHeaders,
  });
}

export default {
  async fetch(request, env, ctx) {
    const targetHost = normalizeHost(env?.TARGET_HOST) || DEFAULT_TARGET_HOST;
    const panelHost = normalizeHost(env?.PANEL_HOST) || DEFAULT_PANEL_HOST;
    const incomingUrl = new URL(request.url);
    if (incomingUrl.protocol === "http:") {
      const httpsUrl = new URL(incomingUrl.toString());
      httpsUrl.protocol = "https:";
      return Response.redirect(httpsUrl.toString(), 301);
    }
    const originalHost = request.headers.get("Host") || incomingUrl.host;
    const normalizedOriginalHost = normalizeHost(originalHost).split(":")[0].toLowerCase();
    const isPanelHost = normalizedOriginalHost === panelHost.split(":")[0].toLowerCase();

    const upstreamUrl = new URL(request.url);
    upstreamUrl.protocol = "https:";
    upstreamUrl.host = targetHost;

    // Chuẩn bị headers: giữ domain gốc trong X-Forwarded-Host cho DomainProxyMiddleware
    const headers = new Headers(request.headers);
    headers.set("Host", targetHost);
    headers.set("X-Forwarded-Host", originalHost);
    headers.set("X-Forwarded-Proto", incomingUrl.protocol.replace(":", "") || "https");

    const clientIp = request.headers.get("CF-Connecting-IP");
    if (clientIp) {
      headers.set("X-Forwarded-For", clientIp);
    }

    const origin = headers.get("Origin");
    if (origin) {
      try {
        const originUrl = new URL(origin);
        if (originUrl.host === originalHost) {
          originUrl.protocol = "https:";
          originUrl.host = targetHost;
          headers.set("Origin", originUrl.origin);
        }
      } catch {}
    }

    const method = request.method.toUpperCase();
    const hasBody = method !== "GET" && method !== "HEAD";
    const isWebSocket = headers.get("Upgrade")?.toLowerCase() === "websocket";
    const hasAuth = Boolean(request.headers.get("Authorization"));
    const cacheControlRule = isPanelHost ? getStaticCacheControl(incomingUrl.pathname) : null;
    const shouldUseEdgeCache = Boolean(
      method === "GET" && !isWebSocket && !hasAuth && cacheControlRule
    );

    const edgeCache =
      shouldUseEdgeCache && typeof caches !== "undefined" && caches?.default
        ? caches.default
        : null;
    const cacheKey = edgeCache
      ? new Request(`${incomingUrl.origin}${incomingUrl.pathname}`, { method: "GET" })
      : null;

    if (edgeCache && cacheKey) {
      const cachedResp = await edgeCache.match(cacheKey);
      if (cachedResp) {
        return isPanelHost && !incomingUrl.pathname.startsWith("/port/")
          ? applyPanelHtmlNonceCsp(cachedResp)
          : cachedResp;
      }
    }

    let upstreamResp;
    try {
      upstreamResp = await fetch(upstreamUrl.toString(), {
        method,
        headers,
        body: hasBody ? request.body : undefined,
        redirect: "manual",
      });
    } catch {
      return buildGatewayFallbackResponse(request, incomingUrl, originalHost);
    }

    // Chuyển tiếp WebSocket qua WebSocketPair để không rò header HF ở response 101
    if (upstreamResp.status === 101) {
      return bridgeWebSocketResponse(upstreamResp);
    }

    // Chặn trang lỗi 502/503/504/52x HTML từ proxy gốc (tránh lộ domain *.hf.space)
    const upstreamContentType = (upstreamResp.headers.get("content-type") || "").toLowerCase();
    if (
      GATEWAY_ERROR_STATUSES.has(upstreamResp.status) &&
      upstreamContentType.includes("text/html")
    ) {
      try {
        await upstreamResp.body?.cancel();
      } catch {}
      return buildGatewayFallbackResponse(request, incomingUrl, originalHost);
    }

    const respHeaders = new Headers(upstreamResp.headers);

    // Gỡ header Link canonical trỏ về huggingface.co / *.hf.space do proxy ngoài của HF tự chèn
    stripUpstreamHfLink(respHeaders);

    // Viết lại Access-Control-Allow-Origin nếu trỏ về *.hf.space và gỡ header proxy nội bộ của HF
    const allowOrigin = respHeaders.get("Access-Control-Allow-Origin");
    if (allowOrigin && /^https?:\/\//i.test(allowOrigin)) {
      try {
        const allowUrl = new URL(allowOrigin);
        if (allowUrl.host === targetHost) {
          respHeaders.set("Access-Control-Allow-Origin", `${incomingUrl.protocol}//${originalHost}`);
        }
      } catch {}
    }
    respHeaders.delete("x-proxied-path");
    respHeaders.delete("x-proxied-replica");
    respHeaders.delete("x-request-id");

    // Viết lại Location nếu Space redirect về domain *.hf.space
    const location = respHeaders.get("Location");
    if (location && (/^https?:\/\//i.test(location) || location.startsWith("//"))) {
      try {
        const locUrl = new URL(
          location.startsWith("//") ? `${incomingUrl.protocol}${location}` : location
        );
        if (locUrl.host === targetHost) {
          locUrl.protocol = incomingUrl.protocol;
          locUrl.host = originalHost;
          respHeaders.set("Location", locUrl.toString());
        }
      } catch {}
    }

    // Gỡ Domain=*.hf.space trong Set-Cookie để cookie hoạt động trên custom domain
    if (typeof respHeaders.getSetCookie === "function") {
      const cookies = respHeaders.getSetCookie();
      if (cookies.length > 0) {
        respHeaders.delete("Set-Cookie");
        const domainRegex = new RegExp(`;\\s*Domain=${escapeRegExp(targetHost)}`, "gi");
        for (const cookie of cookies) {
          respHeaders.append("Set-Cookie", cookie.replace(domainRegex, ""));
        }
      }
    }

    const hasSetCookie =
      typeof respHeaders.getSetCookie === "function"
        ? respHeaders.getSetCookie().length > 0
        : respHeaders.has("Set-Cookie");
    const canCacheResponse = shouldUseEdgeCache && upstreamResp.status === 200 && !hasSetCookie;

    if (canCacheResponse) {
      respHeaders.set("Cache-Control", cacheControlRule);
    }

    const applyPanelSec = isPanelHost && !incomingUrl.pathname.startsWith("/port/");
    if (applyPanelSec) {
      applyPanelSecurityHeaders(respHeaders);
    }

    const finalResp = new Response(upstreamResp.body, {
      status: upstreamResp.status,
      statusText: upstreamResp.statusText,
      headers: respHeaders,
    });

    if (edgeCache && cacheKey && canCacheResponse) {
      const putPromise = edgeCache.put(cacheKey, finalResp.clone());
      if (ctx && typeof ctx.waitUntil === "function") {
        ctx.waitUntil(putPromise);
      } else {
        await putPromise;
      }
    }

    return applyPanelSec ? applyPanelHtmlNonceCsp(finalResp) : finalResp;
  },
};