This commit is contained in:
Mateusz Gruszczyński committed 2026-11-14 21:52:48 +01:00
1 parent f48843e934
commit e2c8099d9c
64 files changed
+5354 -673

No files matched your search

+32 -6
View File
@@ -20,7 +20,7 @@ window.rustProxyCacheRules = (() => {
const ACTIONS = {
request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
deliver: ["set_header", "remove_header"],
deliver: ["set_header", "default_header", "remove_header"],
};
const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
@@ -92,6 +92,7 @@ window.rustProxyCacheRules = (() => {
case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
case "remove_header": return `unset resp.http.${a.name};`;
case "default_header": return `if (!resp.http.${a.name}) { set resp.http.${a.name} = "${esc(a.value ?? "")}"; }`;
default: return `# ${a.type}`;
}
});
@@ -121,7 +122,8 @@ window.rustProxyCacheRules = (() => {
const actions = rule.actions.map(a => {
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
if (a.type === "set_header" || a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
if (a.type === "set_header" || a.type === "default_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
if (a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
return actionLabel(a.type);
});
return actions.join(" · ");
@@ -142,6 +144,9 @@ window.rustProxyCacheRules = (() => {
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }],
nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }],
security: () => [{ name: t("cacheRuleTplSecurity"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "default_header", name: "X-Content-Type-Options", value: "nosniff" }, { type: "default_header", name: "Referrer-Policy", value: "strict-origin-when-cross-origin" }] }],
};
function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
@@ -172,6 +177,19 @@ window.rustProxyCacheRules = (() => {
if (skippedBy.length) notes.push(t("cacheRulesIgnoredIn").replace("{vhosts}", skippedBy.join(", ")));
return notes;
}
let targets = null, targetsLoading = null;
function loadTargets() {
if (targets || targetsLoading || typeof authenticated === "undefined" || !authenticated) return targetsLoading;
targetsLoading = api("/api/cache/rules/targets")
.then(data => { targets = Array.isArray(data.targets) ? data.targets : []; document.dispatchEvent(new Event("rustproxy-cache-targets")); })
.catch(() => { })
.finally(() => { targetsLoading = null; });
return targetsLoading;
}
function targetList() {
return targets || (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, hosts: vhost.frontend?.hosts || [], docker: false }));
}
const targetTitle = target => target.docker ? `${target.hosts?.[0] || target.id} (Docker)` : target.id;
let hits = {};
async function loadHits() {
if (!authenticated) return;
@@ -203,7 +221,7 @@ window.rustProxyCacheRules = (() => {
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
toolbar.append(templates, importButton, exportButton, addButton);
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; ignoreBox.id = "vh-cache-ignore-global-rules";
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; if (options.ignoreId !== "") ignoreBox.id = options.ignoreId || "vh-cache-ignore-global-rules";
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
const notices = el("div", undefined, "cache-rules-notices");
const list = el("div", undefined, "cache-rules-list");
@@ -224,6 +242,8 @@ window.rustProxyCacheRules = (() => {
for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); }
void loadTargets();
document.addEventListener("rustproxy-cache-targets", () => { if (root.isConnected && scope === "global" && open.size) render(); });
function renderNotices() {
notices.replaceChildren();
if (scope !== "vhost") return;
@@ -285,7 +305,7 @@ window.rustProxyCacheRules = (() => {
grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
body.append(grid);
if (scope === "global") {
const vhostItems = (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, title: vhost.name || vhost.id, detail: (vhost.frontend?.hosts || []).slice(0, 3).join(", ") }));
const vhostItems = targetList().map(target => ({ id: target.id, title: targetTitle(target), detail: target.docker ? target.id : (target.hosts || []).slice(0, 3).join(", "), search: (target.hosts || []).join(" "), badge: target.docker ? "Docker" : "", badgeClass: "is-allow" }));
const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
picker.addEventListener("change", changed);
@@ -358,6 +378,7 @@ window.rustProxyCacheRules = (() => {
case "hash_cookie": params.append(nameInput("lang")); break;
case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
case "default_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("Cache-Control"), value); break; }
case "remove_header": params.append(nameInput("X-Powered-By")); break;
default: params.append(el("small", t(`cacheRuleActionHelp${action.type.split("_").map(p => p[0].toUpperCase() + p.slice(1)).join("")}`), "fine"));
}
@@ -370,7 +391,12 @@ window.rustProxyCacheRules = (() => {
const grid = el("div", undefined, "cache-rules-tester-grid");
const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...(envelope?.config?.vhosts || []).map(vhost => [vhost.id, vhost.name || vhost.id])], vhostId, t("cacheRulesTesterVhost"));
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])], vhostId, t("cacheRulesTesterVhost"));
document.addEventListener("rustproxy-cache-targets", () => {
const current = vhostSelect.value;
vhostSelect.replaceChildren(...[["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])].map(([value, text]) => { const option = el("option", text); option.value = value; return option; }));
vhostSelect.value = [...vhostSelect.options].some(option => option.value === current) ? current : "";
});
const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
const clientIp = textInput("", "203.0.113.10", "mono");
const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
@@ -443,7 +469,7 @@ window.rustProxyCacheRules = (() => {
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
}
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
}
return rules.map(rule => clean(rule, scope === "global"));
}