This commit is contained in:
Mateusz Gruszczyński committed 2026-11-14 17:24:12 +01:00
1 parent 78dbb31487
commit f48843e934
83 files changed
+7304 -1203

No files matched your search

+455
View File
@@ -0,0 +1,455 @@
"use strict";
window.rustProxyCacheRules = (() => {
const MAX_RULES = 128;
const STAGES = ["request", "response", "deliver"];
const STAGE_KEYS = { request: "cacheRuleStageRequest", response: "cacheRuleStageResponse", deliver: "cacheRuleStageDeliver" };
const FIELDS = {
host: { ops: ["equals", "suffix", "prefix", "regex", "glob"], stages: STAGES },
url: { ops: ["prefix", "regex", "glob", "equals", "contains"], stages: STAGES },
path: { ops: ["prefix", "equals", "glob", "regex", "suffix", "contains"], stages: STAGES },
extension: { ops: ["equals"], stages: STAGES },
method: { ops: ["equals"], stages: STAGES },
query: { ops: ["exists", "equals", "prefix", "regex"], name: true, stages: STAGES },
header: { ops: ["exists", "equals", "contains", "prefix", "regex"], name: true, stages: STAGES },
cookie: { ops: ["exists", "equals", "regex"], name: true, stages: STAGES },
client_ip: { ops: ["cidr"], stages: STAGES },
status: { ops: ["equals"], stages: ["response", "deliver"] },
content_type: { ops: ["prefix", "equals", "regex"], stages: ["response", "deliver"] },
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
};
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"],
};
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("")}`);
const fieldLabel = field => tk("cacheRuleField", field);
const opLabel = op => tk("cacheRuleOp", op);
const actionLabel = type => tk("cacheRuleAction", type);
const splitList = value => String(value || "").split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
const durationUnits = [["s", 1], ["m", 60], ["h", 3600], ["d", 86400]];
function slug(value, taken) {
let base = String(value || "").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/ł/g, "l").replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56) || "rule";
let candidate = base, n = 2;
while (taken.has(candidate)) candidate = `${base}-${n++}`;
return candidate;
}
function blankRule(taken, stage = "request") {
const id = slug(t("cacheRuleNewName"), taken);
return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
}
function normalize(rule) {
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, vhosts: [...(rule.vhosts || [])] };
}
function clean(rule, global) {
const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
return out;
}
const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const globRe = value => String(value).split("*").map(reEsc).join(".*");
function vclVar(field, name, stage) {
const resp = stage === "deliver" ? "resp" : "beresp";
return { host: "req.http.host", url: "req.url", path: "req.url", extension: "req.url", method: "req.method", query: "req.url", header: `req.http.${name}`, cookie: "req.http.Cookie", client_ip: "client.ip", status: `${resp}.status`, content_type: `${resp}.http.Content-Type`, response_header: `${resp}.http.${name}` }[field];
}
function vclCondition(c, stage) {
const variable = vclVar(c.field, c.name, stage), values = c.values || [];
const one = value => {
if (c.field === "status") { const m = String(value).match(/^(\d)xx$/i); if (m) return `(${variable} >= ${m[1]}00 && ${variable} <= ${m[1]}99)`; const r = String(value).split("-"); if (r.length === 2) return `(${variable} >= ${r[0]} && ${variable} <= ${r[1]})`; return `${variable} == ${value}`; }
if (c.field === "client_ip") return `client.ip ~ ${c.ruleAcl || "rule_acl"} /* ${value} */`;
if (c.field === "extension") return `req.url ~ "\\.${reEsc(value)}(\\?|$)"`;
if (c.field === "query") return c.operator === "exists" ? `req.url ~ "[?&]${reEsc(c.name)}="` : `req.url ~ "[?&]${reEsc(c.name)}=${c.operator === "regex" ? value : reEsc(value)}${c.operator === "equals" ? "(&|$)" : ""}"`;
if (c.field === "cookie") return c.operator === "exists" ? `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}="` : `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}=${c.operator === "regex" ? value : `${reEsc(value)}(;|$)`}"`;
if (c.field === "path" && c.operator === "equals") return `req.url ~ "^${reEsc(value)}(\\?|$)"`;
switch (c.operator) {
case "equals": return `${variable} == "${esc(value)}"`;
case "prefix": return `${variable} ~ "^${esc(reEsc(value))}"`;
case "suffix": return `${variable} ~ "${esc(reEsc(value))}$"`;
case "contains": return `${variable} ~ "${esc(reEsc(value))}"`;
case "glob": return `${variable} ~ "^${esc(globRe(value))}$"`;
case "regex": return `${variable} ~ "${esc(value)}"`;
default: return variable;
}
};
let expr = c.operator === "exists" && !["query", "cookie"].includes(c.field) ? variable : values.length > 1 ? `(${values.map(one).join(" || ")})` : one(values[0] ?? "");
if (c.negate) expr = `!(${expr})`;
return expr;
}
function vclActions(rule) {
return rule.actions.map(a => {
switch (a.type) {
case "pass": return "return (pass);";
case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
case "hash_header": return `hash_data(req.http.${a.name});`;
case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
case "ttl": return `set beresp.ttl = ${a.seconds ?? 0}s;`;
case "grace": return `set beresp.grace = ${a.seconds ?? 0}s;`;
case "no_store": return "set beresp.uncacheable = true;";
case "ignore_cache_control": return "unset beresp.http.Cache-Control;";
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};`;
default: return `# ${a.type}`;
}
});
}
function ruleVcl(rule) {
const lines = vclActions(rule).flatMap(line => line.split("\n"));
const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
const joined = conditions.join(rule.match === "any" ? " ||\n " : " &&\n ");
const body = lines.map(line => ` ${line}`).join("\n");
const head = `# ${rule.name || rule.id}${rule.enabled === false ? " (disabled)" : ""}${rule.vhosts?.length ? ` · vhosts: ${rule.vhosts.join(", ")}` : ""}`;
return conditions.length ? `${head}\nif (${joined}) {\n${body}\n}` : `${head}\n${body.replace(/^ {4}/gm, "")}`;
}
function exportVcl(rules) {
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
const blocks = ["vcl 4.1;", "# Generated by RustProxy cache rules (read-only preview)"];
const indent = text => text.replace(/^/gm, " ");
for (const stage of STAGES) {
const items = rules.filter(rule => rule.stage === stage);
const main = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
const hash = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
if (main.length) blocks.push(`\nsub ${subs[stage]} {\n${main.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
if (hash.length) blocks.push(`\nsub vcl_hash {\n${hash.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
}
return blocks.join("\n");
}
function summary(rule) {
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 || "-"}`;
return actionLabel(a.type);
});
return actions.join(" · ");
}
function fmtDuration(seconds) {
seconds = Number(seconds) || 0;
for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
return `${seconds}s`;
}
const TEMPLATES = {
wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }],
static: () => [
{ name: t("cacheRuleTplStaticCookies"), stage: "request", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }], actions: [{ type: "strip_cookies", keep: [] }] },
{ name: t("cacheRuleTplStaticTtl"), stage: "response", 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: "ttl", seconds: 2592000 }, { type: "strip_set_cookie" }] },
],
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
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" }] }],
};
function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
}
function aspects(rule) { return new Set(rule.actions.map(a => ASPECTS[a.type]).filter(Boolean)); }
function conflictsFor(vhostRules, globals) {
const notes = [];
for (const local of vhostRules.filter(rule => rule.enabled !== false)) {
const mine = aspects(local);
if (!mine.size) continue;
for (const global of globals) {
if (global.stage !== local.stage) continue;
const shared = [...aspects(normalize(global))].filter(aspect => mine.has(aspect));
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
}
}
return notes;
}
function globalOverrideNotes(rule) {
const vhosts = envelope?.config?.vhosts || [], mine = aspects(rule), overriddenBy = [], skippedBy = [];
for (const vhost of vhosts) {
if (rule.vhosts?.length && !rule.vhosts.includes(vhost.id)) continue;
if (vhost.cache?.ignore_global_rules) { skippedBy.push(vhost.id); continue; }
if ((vhost.cache?.rules || []).some(local => local.enabled !== false && local.stage === rule.stage && [...aspects(normalize(local))].some(aspect => mine.has(aspect)))) overriddenBy.push(vhost.id);
}
const notes = [];
if (overriddenBy.length) notes.push(t("cacheRulesOverriddenIn").replace("{vhosts}", overriddenBy.join(", ")));
if (skippedBy.length) notes.push(t("cacheRulesIgnoredIn").replace("{vhosts}", skippedBy.join(", ")));
return notes;
}
let hits = {};
async function loadHits() {
if (!authenticated) return;
try { hits = (await api("/api/cache/rules/stats")).hits || {}; } catch { hits = {}; }
}
function select(values, current, label) {
const node = el("select"); for (const [value, text] of values) { const option = el("option", text); option.value = value; node.append(option); } node.value = current; if (label) node.setAttribute("aria-label", label); return node;
}
function textInput(value, placeholder = "", cls = "") { const node = el("input", undefined, cls); node.type = "text"; node.value = value ?? ""; node.placeholder = placeholder; node.spellcheck = false; return node; }
function durationInput(seconds, onChange) {
const wrap = el("span", undefined, "cache-rule-duration"), number = el("input"); number.type = "number"; number.min = 0; number.step = 1;
let unit = "s"; for (const [name, size] of [...durationUnits].reverse()) if ((seconds || 0) >= size && (seconds || 0) % size === 0) { unit = name; break; }
number.value = Math.round((seconds || 0) / Object.fromEntries(durationUnits)[unit]);
const units = select(durationUnits.map(([name]) => [name, t(`cacheRuleUnit${name.toUpperCase()}`)]), unit, t("cacheRuleDurationUnit"));
const emit = () => onChange(Math.max(0, Math.round(Number(number.value) || 0) * Object.fromEntries(durationUnits)[units.value]));
number.addEventListener("input", emit); units.addEventListener("change", emit);
wrap.append(number, units); return wrap;
}
function create(options = {}) {
const scope = options.scope === "vhost" ? "vhost" : "global", vhostId = options.vhostId || "";
let rules = (options.rules || []).map(normalize), open = new Set(), ignoreGlobal = !!options.ignoreGlobal;
const root = el("div", undefined, `cache-rules cache-rules-${scope}`);
const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
const toolbar = el("div", undefined, "cache-rules-toolbar");
if (scope === "vhost") { const docs = el("a", t("cacheRulesDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FCACHE.md&section=cache-rules-vcl-style"; docs.target = "_blank"; docs.rel = "noopener noreferrer"; root.append(docs); }
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
templates.classList.add("cache-rules-templates");
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
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";
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
const notices = el("div", undefined, "cache-rules-notices");
const list = el("div", undefined, "cache-rules-list");
const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty");
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
const importText = document.createElement("textarea"); importText.rows = 10; importText.spellcheck = false; importText.placeholder = "sub vcl_recv {\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}";
const importRun = el("button", t("cacheRulesImportRun"), "primary"); importRun.type = "button";
const importCancel = el("button", t("cancel"), "outline"); importCancel.type = "button";
const importResult = el("div", undefined, "cache-rules-import-result");
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importCancel);
importBox.append(el("p", t("cacheRulesImportHelp"), "fine"), importText, importActions, importResult);
const exportBox = el("details", undefined, "cache-rules-export"); const exportSummary = el("summary", t("cacheRulesVclPreview")); const exportPre = el("pre", "", "metrics-example mono cache-rules-vcl");
exportBox.append(exportSummary, exportPre);
const tester = buildTester();
root.append(toolbar);
if (scope === "vhost") root.append(ignoreWrap);
root.append(notices, importBox, list, empty, exportBox, tester.node);
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)); }
function renderNotices() {
notices.replaceChildren();
if (scope !== "vhost") return;
const globals = applicableGlobals(vhostId);
if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; }
if (globals.length) notices.append(el("p", t("cacheRulesGlobalApply").replace("{count}", globals.length).replace("{names}", globals.slice(0, 6).map(rule => rule.name || rule.id).join(", ") + (globals.length > 6 ? "…" : "")), "fine"));
for (const note of conflictsFor(rules, globals)) notices.append(el("p", note, "fine cache-rules-notice"));
}
function render() {
list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index)));
empty.hidden = rules.length > 0;
addButton.disabled = rules.length >= MAX_RULES;
exportPre.textContent = exportVcl(rules);
renderNotices();
}
function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); }
function ruleCard(rule, index) {
const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index;
card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); });
card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
card.addEventListener("dragover", event => { event.preventDefault(); card.classList.add("is-drop"); });
card.addEventListener("dragleave", () => card.classList.remove("is-drop"));
card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); });
const head = el("div", undefined, "cache-rule-head");
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag");
const toggle = el("input"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled"));
toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); });
const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none";
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary"));
title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); });
const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`;
const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits");
const actions = el("span", undefined, "cache-rule-actions");
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1));
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1));
const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); });
const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); });
actions.append(up, down, copy, remove);
head.append(grip, toggle, title, hitCount, actions);
card.append(head);
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
if (open.has(rule.id)) card.append(ruleEditor(rule));
return card;
}
function ruleEditor(rule) {
const body = el("div", undefined, "cache-rule-body");
const grid = el("div", undefined, "cache-rule-grid");
const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96;
name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); });
const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
stage.addEventListener("change", () => { rule.stage = stage.value; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
const stop = el("input"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; };
const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop")));
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 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);
const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine"));
body.append(field);
}
const conditions = el("div", undefined, "cache-rule-section");
conditions.append(el("h4", t("cacheRuleConditions")));
const conditionRows = el("div", undefined, "cache-rule-rows");
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button";
addCondition.disabled = rule.conditions.length >= 16;
addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
conditions.append(conditionRows, addCondition);
const actionsSection = el("div", undefined, "cache-rule-section");
actionsSection.append(el("h4", t("cacheRuleActions")));
const actionRows = el("div", undefined, "cache-rule-rows");
rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index)));
const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button";
addAction.disabled = rule.actions.length >= 16;
addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
actionsSection.append(actionRows, addAction);
const preview = el("pre", "", "metrics-example mono cache-rule-vcl");
const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); };
body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview);
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview);
body.append(conditions, actionsSection, previewWrap);
syncPreview();
return body;
}
function conditionRow(rule, condition, index) {
const row = el("div", undefined, "cache-rule-row");
const fields = Object.keys(FIELDS).filter(field => FIELDS[field].stages.includes(rule.stage));
const field = select(fields.map(value => [value, fieldLabel(value)]), condition.field, t("cacheRuleField"));
const name = textInput(condition.name, t("cacheRuleNamePlaceholderField"), "cache-rule-name"); name.hidden = !FIELDS[condition.field].name;
const ops = FIELDS[condition.field].ops;
if (!ops.includes(condition.operator)) condition.operator = ops[0];
const operator = select(ops.map(value => [value, opLabel(value)]), condition.operator, t("cacheRuleOperator"));
const values = textInput((condition.values || []).join(", "), t(`cacheRuleValuesPlaceholder${condition.field === "status" ? "Status" : condition.field === "client_ip" ? "Cidr" : condition.field === "extension" ? "Extension" : condition.field === "method" ? "Method" : ""}`), "cache-rule-values");
values.hidden = condition.operator === "exists";
const negateLabel = el("label", undefined, "check cache-rule-negate"), negate = el("input"); negate.type = "checkbox"; negate.checked = !!condition.negate; negateLabel.append(negate, el("span", t("cacheRuleNegate")));
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove"));
field.addEventListener("change", () => { condition.field = field.value; condition.operator = FIELDS[field.value].ops[0]; if (!FIELDS[field.value].name) delete condition.name; render(); changed(); });
name.addEventListener("input", () => { condition.name = name.value.trim(); changed(); });
operator.addEventListener("change", () => { condition.operator = operator.value; if (operator.value === "exists") condition.values = []; render(); changed(); });
values.addEventListener("input", () => { condition.values = operator.value === "regex" ? [values.value.trim()].filter(Boolean) : splitList(values.value); changed(); });
negate.addEventListener("change", () => { condition.negate = negate.checked; changed(); });
remove.addEventListener("click", () => { rule.conditions.splice(index, 1); render(); changed(); });
row.append(field, name, operator, values, negateLabel, remove);
return row;
}
function actionRow(rule, action, index) {
const row = el("div", undefined, "cache-rule-row");
const type = select(ACTIONS[rule.stage].map(value => [value, actionLabel(value)]), action.type, t("cacheRuleAction"));
const params = el("span", undefined, "cache-rule-params");
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1;
type.addEventListener("change", () => { rule.actions[index] = { type: type.value }; render(); changed(); });
remove.addEventListener("click", () => { rule.actions.splice(index, 1); render(); changed(); });
const listInput = (key, placeholder) => { const node = textInput((action[key] || []).join(", "), placeholder); node.addEventListener("input", () => { action[key] = splitList(node.value); changed(); }); return node; };
const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; };
switch (action.type) {
case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break;
case "strip_query": {
const keepOnly = el("label", undefined, "check"), box = el("input"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly")));
box.addEventListener("change", () => { action.keep_only = box.checked; changed(); });
params.append(listInput("params", t("cacheRuleQueryParams")), keepOnly); break;
}
case "hash_header": params.append(nameInput("Accept-Language")); break;
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 "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"));
}
row.append(type, params, remove);
return row;
}
function buildTester() {
const node = el("details", undefined, "cache-rules-tester");
node.append(el("summary", t("cacheRulesTester")));
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 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;
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 3; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
const run = el("button", t("cacheRulesTesterRun"), "primary"); run.type = "button";
const result = el("div", undefined, "cache-rules-tester-result");
const field = (key, control) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); return label; };
grid.append(field("cacheRuleFieldMethod", method), field("cacheRulesTesterUrl", url));
if (scope === "global") grid.append(field("cacheRulesTesterVhost", vhostSelect));
grid.append(field("cacheRulesTesterHeaders", headers), field("cacheRuleFieldClientIp", clientIp), field("cacheRuleFieldStatus", status), field("cacheRulesTesterResponseHeaders", responseHeaders));
const pairs = text => String(text || "").split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => { const at = line.indexOf(":"); return at > 0 ? [line.slice(0, at).trim(), line.slice(at + 1).trim()] : [line, ""]; });
run.addEventListener("click", async () => {
run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
try {
const body = { request: { method: method.value, url: url.value.trim(), headers: pairs(headers.value), client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
if (scope === "global") { body.global_rules = read(); body.vhost_id = vhostSelect.value || null; }
else { body.vhost_id = vhostId || null; body.vhost_rules = read(); body.ignore_global_rules = ignoreGlobal; if (!vhostId) body.vhost_id = null; }
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(body) }));
} catch (error) { result.replaceChildren(el("p", error.message, "fine is-error")); }
finally { run.disabled = false; }
});
function renderResult(data) {
const items = [];
const line = (label, value, cls = "") => { const row = el("div", undefined, `cache-rules-result-line ${cls}`.trim()); row.append(el("span", label, "fine"), el("strong", value)); items.push(row); };
const names = matched => (matched || []).map(item => `${item.name || item.id} (${item.origin === "vhost" ? t("cacheRulesOriginVhost") : t("cacheRulesOriginGlobal")})`).join(", ") || "—";
const request = data.request || {};
line(t("cacheRulesResultDecision"), request.cacheable ? (data.response?.stored ? t("cacheRulesResultHit").replace("{ttl}", fmtDuration(data.response.ttl)).replace("{grace}", fmtDuration(data.response.grace)) : t("cacheRulesResultNotStored").replace("{reason}", data.response?.reason || "-")) : t("cacheRulesResultPass").replace("{reason}", request.reason || "-"), request.cacheable && data.response?.stored ? "is-ok" : "is-warn");
line(t("cacheRulesResultRequest"), names(request.matched));
line(t("cacheRulesResultKey"), `${data.host || "-"}${request.target || ""}${request.variant?.length ? ` + ${request.variant.join(", ")}` : ""}`);
if (request.cookie != null) line(t("cacheRulesResultCookie"), request.cookie || "—");
if (data.response) line(t("cacheRulesResultResponse"), names(data.response.matched));
if (data.deliver) line(t("cacheRulesResultDeliver"), [...(data.deliver.set || []).map(([k, v]) => `${k}: ${v}`), ...(data.deliver.remove || []).map(k => `−${k}`)].join(", ") || "—");
for (const item of [...(request.overridden || []), ...(data.response?.overridden || [])]) line(t("cacheRulesResultOverridden"), t("cacheRulesResultOverriddenText").replace("{winner}", item.winner).replace("{ignored}", item.ignored).replace("{aspect}", t(`cacheRuleAspect${item.aspect[0].toUpperCase()}${item.aspect.slice(1)}`)), "is-warn");
result.replaceChildren(...items);
}
const actions = el("div", undefined, "form-actions"); actions.append(run);
node.append(el("p", t("cacheRulesTesterHelp"), "fine"), grid, actions, result);
return { node };
}
function addRules(items) {
const ids = taken(); let added = 0;
for (const item of items) {
if (rules.length >= MAX_RULES) { toast(t("cacheRulesLimit"), true); break; }
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
ids.add(rule.id); rules.push(rule); added++;
}
render(); if (added) changed();
return added;
}
templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); });
addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (!importBox.hidden) importText.focus(); });
importCancel.addEventListener("click", () => { importBox.hidden = true; importResult.replaceChildren(); });
importRun.addEventListener("click", async () => {
importRun.disabled = true; importResult.replaceChildren();
try {
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: importText.value }) });
const added = addRules(data.rules || []);
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
if (data.warnings?.length) { const list = el("ul", undefined, "cache-rules-warnings"); for (const warning of data.warnings) list.append(el("li", warning)); importResult.append(el("p", t("cacheRulesImportWarnings"), "fine"), list); }
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
finally { importRun.disabled = false; }
});
exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
function read() {
for (const rule of rules) {
if (!rule.actions.length) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
for (const c of rule.conditions) {
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));
}
return rules.map(rule => clean(rule, scope === "global"));
}
render();
void loadHits().then(render);
return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits: () => loadHits().then(render) };
}
return { create, exportVcl, TEMPLATES };
})();