Spaces:
Running

Bot / worker.js
ddosvn's picture
Use per-request CSP nonce instead of script-src unsafe-inline (part 2)
781eb05 verified
Raw History Blame Contribute Delete
15.5 kB
/**
* 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;
},
};