This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 12:52:41 +01:00
1 parent 3b953dcdc6
commit 96eec3b1c6
12 files changed
+440 -44

No files matched your search

+1
View File
@@ -127,6 +127,7 @@ fn admin_vhosts_javascript() -> &'static str {
include_str!("web/vhosts/rates.js"),
include_str!("web/vhosts/balancing.js"),
include_str!("web/vhosts/routing.js"),
include_str!("web/vhosts/headers-tab.js"),
include_str!("web/vhosts/editor.js"),
include_str!("web/vhosts/render.js"),
"})();",
+177
View File
@@ -2452,3 +2452,180 @@ h2+.fine {
padding: 2px 8px;
font: 11px var(--mono);
}
/* Headers tab: live preview, diagnostic cards and compact header rules. */
.hdr-preview {
display: grid;
gap: 10px;
border: 1px solid var(--accent);
background: var(--panel2);
padding: 12px;
}
.hdr-preview-controls {
display: flex;
flex-wrap: wrap;
gap: 10px 16px;
}
.hdr-preview-control {
display: grid;
gap: 3px;
min-width: 150px;
font-size: 11px;
color: var(--muted);
}
.hdr-preview-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.hdr-preview-col {
min-width: 0;
border: 1px solid var(--line);
background: var(--panel);
padding: 10px;
}
.hdr-preview-col h4 {
margin: 0;
font-size: 12px;
}
.hdr-preview-col>p {
margin: 2px 0 8px;
}
.hdr-preview-list {
display: grid;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.hdr-line {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 4px 8px;
border-bottom: 1px solid var(--row-line);
padding: 3px 0;
}
.hdr-line code {
min-width: 0;
font: 11px var(--mono);
overflow-wrap: anywhere;
}
.hdr-line code b {
color: var(--accent);
font-weight: 600;
}
.hdr-line.is-removed code {
opacity: .55;
text-decoration: line-through;
}
.hdr-line.is-system code {
color: var(--muted);
}
.hdr-tags {
display: flex;
gap: 4px;
}
.hdr-tag {
border: 1px solid var(--line);
border-radius: 999px;
padding: 0 6px;
color: var(--muted);
font: 10px var(--mono);
white-space: nowrap;
}
.hdr-tag.is-dynamic {
border-color: var(--pill-live-line);
color: var(--green);
}
.hdr-tag.is-removed {
border-color: var(--notice-line);
color: var(--notice-text);
}
.hdr-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 10px;
}
.hdr-card {
display: grid;
align-content: start;
gap: 6px;
border: 1px solid var(--line);
padding: 10px;
}
.hdr-card.is-on {
border-color: var(--pill-live-line);
background: var(--panel2);
}
.hdr-card>p {
margin: 0;
}
.hdr-card-sample {
font: 11px var(--mono);
color: var(--muted);
overflow-wrap: anywhere;
}
.hdr-card.is-on .hdr-card-sample b {
color: var(--accent);
}
.lb-preset.is-added {
opacity: .5;
}
.hdr-row {
padding: 6px 8px;
}
.vh-header-rule-fields.hdr-row-fields {
display: grid;
grid-template-columns: minmax(90px, 130px) minmax(120px, 1fr) minmax(160px, 2fr) auto;
align-items: end;
gap: 8px;
}
.hdr-row-remove {
align-self: end;
}
.hdr-row.is-dynamic {
border-left: 2px solid var(--green);
}
.hdr-row.is-invalid {
border-left: 2px solid var(--red);
}
.hdr-row-hint {
margin: 4px 0 0;
font: 11px var(--mono);
overflow-wrap: anywhere;
}
.hdr-row.is-invalid .hdr-row-hint {
color: var(--red);
}
+5
View File
@@ -411,6 +411,11 @@
grid-template-columns: 1fr 1fr;
}
.hdr-preview-columns,
.vh-header-rule-fields.hdr-row-fields {
grid-template-columns: 1fr;
}
.lb-bar {
grid-template-columns: minmax(60px, 110px) minmax(0, 1fr) 70px;
}
+22 -14
View File
@@ -1,6 +1,6 @@
"use strict";
let vhostCacheRulesEditor = null;
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null;
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null, headersPreviewControl = null, presetsRefresh = () => { };
const chartHistory = new Map();
const backendTrafficHistory = new Map();
const backendRequestHistory = new Map();
@@ -23,7 +23,7 @@ const field = (parent, name, key, value, type = "text", options = {}) => {
};
const group = (key, advanced = false) => {
const box = el(advanced ? "details" : "fieldset", undefined, "vh-group");
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "backends", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "security", vhHeaders: "security", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key));
const body = el("div", undefined, "vh-grid"); box.append(body); container.append(box); return body;
};
const note = (parent, key) => { const node = text("p", key, "fine vh-wide"); parent.append(node); return node; };
@@ -60,7 +60,7 @@ const defaults = () => ({
});
function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); }
function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); }
function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["headers", "vhTabHeaders"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); }
function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_ignore_vary_cookie: tri("vh-cache-static-vary-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), expose_detailed_status: tri("vh-cache-detailed-status"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; }
function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; }
function collectTransform() {
@@ -96,7 +96,7 @@ const DIAGNOSTIC_PRESETS = [
{ key: "hdrPresetDebug", direction: "response", rule: { op: "set", name: "X-Debug", value: "%[vhost]/%[location] -> %[srv_id] (%[cache_status], %[backend_time])" } },
{ key: "hdrPresetUpstream", direction: "request", rule: { op: "set", name: "X-Shard", value: "%[srv_id]" } }
];
function headerEditors(parent, initial, target = read("headers"), onChange = changed) {
function headerEditors(parent, initial, target = read("headers"), onChange = changed, exampleContext = () => ({})) {
const holders = {}, adders = {}, emptyStates = {};
const renumber = direction => {
const rows = holders[direction];
@@ -123,16 +123,24 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
const rows = el("div", undefined, "vh-header-rows"); holders[direction] = rows; block.append(rows); parent.append(block);
const add = (value = { op: "set", name: "", value: "" }) => {
if (rows.children.length >= 32) { toast(t("headerLimit"), true); return; }
const row = el("article", undefined, "vh-header-row");
const rowHead = el("div", undefined, "vh-header-rule-head"), rowTitle = el("strong", "", "vh-header-rule-title");
rowHead.append(rowTitle, button("remove", () => { row.remove(); renumber(direction); sync(); })); row.append(rowHead);
const fields = el("div", undefined, "vh-header-rule-fields");
// Compact one-line rule: operation · name · value · remove, with a live check of
// %[variables] (example value or error) underneath.
const row = el("article", undefined, "vh-header-row hdr-row");
const fields = el("div", undefined, "vh-header-rule-fields hdr-row-fields");
field(fields, "rule-op", "headerOperation", value.op, "select", { values: [["set", "header_set"], ["append", "header_append"], ["remove", "header_remove"]] });
const name = field(fields, "rule-name", "headerName", value.name, "text", { maxLength: 128 }); name.placeholder = "X-App-Header";
const ruleValue = field(fields, "rule-value", "headerValue", value.value ?? "", "text", { maxLength: 8192 }); ruleValue.placeholder = "value";
row.append(fields);
const enabled = () => { ruleValue.disabled = str("rule-op", row) === "remove"; row.classList.toggle("is-remove", ruleValue.disabled); };
row.addEventListener("change", () => { enabled(); sync(); }); row.addEventListener("input", sync); rows.append(row); enabled(); renumber(direction);
const ruleValue = field(fields, "rule-value", "headerValue", value.value ?? "", "text", { maxLength: 8192 }); ruleValue.placeholder = direction === "response" ? "%[srv_id]" : "value";
const removeButton = button("remove", () => { row.remove(); renumber(direction); sync(); }, "quiet hdr-row-remove");
fields.append(removeButton); row.append(fields);
const hint = el("p", "", "fine hdr-row-hint"); row.append(hint);
const check = () => {
const remove = str("rule-op", row) === "remove"; ruleValue.disabled = remove; row.classList.toggle("is-remove", remove);
const result = remove ? { dynamic: false } : headerValueCheck(ruleValue.value, direction, headerExampleVars({ ...headerExampleContext, ...exampleContext() }));
ruleValue.setCustomValidity(result.error || ""); row.classList.toggle("is-invalid", Boolean(result.error)); row.classList.toggle("is-dynamic", Boolean(result.dynamic));
hint.hidden = !result.error && !result.dynamic;
hint.textContent = result.error ? result.error : result.dynamic ? `${t("hdrExample")}: ${name.value || "X-…"}: ${result.rendered}` : "";
};
row.addEventListener("change", () => { check(); sync(); }); row.addEventListener("input", () => { check(); sync(); }); rows.append(row); check(); renumber(direction);
};
adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction);
block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header"));
@@ -145,7 +153,7 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
let target = lastValue?.isConnected && !lastValue.disabled ? lastValue : [...rows.querySelectorAll('[name="rule-value"]:not(:disabled)')].pop();
if (!target) { add({ op: "set", name: "", value: "" }); target = [...rows.querySelectorAll('[name="rule-value"]')].pop(); }
const token = `%[${name}]`, at = target.selectionStart ?? target.value.length;
target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; sync();
target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; target.dispatchEvent(new Event("input", { bubbles: true }));
}, "quiet hdr-var");
delete chip.dataset.i18n; chip.textContent = `%[${name}]`; chip.title = t(`hdrVar_${name}`); chips.append(chip);
}
@@ -495,7 +503,7 @@ function locationsEditor(parent, values) {
const visualButton = button("headersVisualBuilder", () => { visualPane.hidden = false; jsonPane.hidden = true; }), jsonButton = button("headersAdvancedJson", () => { visualPane.hidden = true; jsonPane.hidden = false; }), docsButton = button("documentation", () => openLocationHelp("headers"));
headerToolbar.append(visualButton, jsonButton, docsButton); headerBody.append(headerToolbar, visualPane, jsonPane);
const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 });
const editor = headerEditors(visualPane, value.headers || {}, raw, sync); row.readHeaders = () => editor.read();
const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read();
const preview = el("section", undefined, "vh-wide location-preview");
preview.append(text("h4", "locationPreviewTitle"));
+22 -12
View File
@@ -204,21 +204,30 @@ function load(value = defaults(), migrationIds = [], show = true) {
syncFrontendTransports();
g = group("vhBackendPool"); const members = el("div", undefined, "vh-wide vh-members"); g.append(members);
(value.backends || []).forEach(m => memberRow(members, m)); g.append(button("vhAddBackend", () => { memberRow(members); changed(); }));
g = group("vhHeadersPreview"); headersPreviewControl = headersPreview(g);
g = group("vhBackendDiagnostics");
field(g, "timing-headers", "vhTimingHeaders", value.timing_headers === true, "checkbox", { switch: true });
field(g, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] });
field(g, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com";
field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox", { switch: true });
field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true });
const diagnosticCards = el("div", undefined, "vh-wide hdr-cards"); g.append(diagnosticCards);
diagnosticCard(diagnosticCards, { name: "timing-headers", key: "vhTimingHeaders", checked: value.timing_headers === true, header: "Server-Timing", example: "proxy;dur=1.8, upstream;dur=12.4", help: "hdrCardTimingHelp", extra: body => {
field(body, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] });
field(body, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com";
} });
diagnosticCard(diagnosticCards, { name: "backend-header", key: "vhBackendHeader", checked: value.backend_header === true, header: "X-Rust-Proxy-Backend", example: `${value.id || "vhost"}/${(value.backends || [])[0]?.id || "origin-1"}`, help: "hdrCardBackendHelp" });
diagnosticCard(diagnosticCards, { name: "backend-timing-header", key: "vhBackendTimingHeader", checked: value.backend_timing_header === true, header: "X-RustProxy-Backend-Time", example: "12.40ms", help: "hdrCardBackendTimeHelp" });
note(g, "vhBackendDiagnosticsHelp");
const diagnosticPresets = el("div", undefined, "vh-wide hdr-presets"); diagnosticPresets.append(text("span", "hdrPresets", "hdr-vars-label"));
for (const preset of DIAGNOSTIC_PRESETS) diagnosticPresets.append(button(preset.key, () => {
if (!vhostHeadersControl) return;
const current = vhostHeadersControl.read()[preset.direction] || [];
if (current.some(rule => rule.name.toLowerCase() === preset.rule.name.toLowerCase())) { toast(t("hdrPresetExists").replace("{name}", preset.rule.name)); return; }
vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name));
}, "quiet lb-preset"));
const presetButtons = [];
const syncPresets = () => { const current = safeHeaders(); for (const [preset, node] of presetButtons) { const exists = (current[preset.direction] || []).some(rule => rule.name?.toLowerCase() === preset.rule.name.toLowerCase()); node.disabled = exists; node.classList.toggle("is-added", exists); node.title = exists ? t("hdrPresetExists").replace("{name}", preset.rule.name) : `${preset.direction === "request" ? "→" : "←"} ${preset.rule.name}: ${preset.rule.value}`; } };
const safeHeaders = () => { try { return vhostHeadersControl?.read() || {}; } catch { return {}; } };
for (const preset of DIAGNOSTIC_PRESETS) {
const node = button(preset.key, () => {
if (!vhostHeadersControl) return;
vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name)); syncPresets();
container.querySelector(".hdr-rules-anchor")?.scrollIntoView({ behavior: "smooth", block: "start" });
}, "quiet lb-preset");
presetButtons.push([preset, node]); diagnosticPresets.append(node);
}
g.append(diagnosticPresets); note(g, "hdrPresetsHelp");
presetsRefresh = syncPresets;
const proxyTimeouts = { ...defaultProxyTimeouts(), ...(value.proxy_timeouts || {}) };
g = group("vhProxyTimeouts");
field(g, "proxy-connect-timeout", "vhProxyConnectTimeout", proxyTimeouts.connect_timeout_seconds ?? 10, "number", { required: true, min: 1, max: 300 });
@@ -569,9 +578,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
};
transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
note(transformOptions, "vhTransformHelp");
g = group("vhHeaders"); vhostHeadersControl = headerEditors(g, value.headers || {});
g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor"); vhostHeadersControl = headerEditors(g, value.headers || {});
g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {});
initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal();
headersPreviewControl?.refresh(); presetsRefresh();
}
function collect() {
+136
View File
@@ -0,0 +1,136 @@
// Headers tab of the vhost editor: live preview of the headers RustProxy sends to the
// backend and to the client, example values for %[variables] and diagnostic cards.
const HEADER_VARIABLE_NAMES = new Set(HEADER_VARIABLES.map(([name]) => name));
const HEADER_RESPONSE_ONLY = new Set(HEADER_VARIABLES.filter(([, only]) => only).map(([name]) => name));
let headerExampleContext = { member: "", location: "main", cache: "MISS" };
// Example values for header variables, based on the draft (first eligible backend…).
function headerExampleVars(context = headerExampleContext) {
const members = (typeof balancingMembers === "function" ? balancingMembers() : []).filter(m => m.id);
const member = members.find(m => m.id === context.member) || members.find(m => m.enabled && m.pool_eligible) || members[0];
const hits = context.cache === "HIT";
let algorithm = "least_connections";
try { algorithm = str("algorithm") || algorithm; } catch { }
return {
srv_id: hits ? "-" : member?.id || "-", srv_url: hits ? "-" : member?.url || "-", location: context.location || "main",
vhost: (() => { try { return str("id") || "vhost"; } catch { return "vhost"; } })(), lb_algorithm: algorithm,
hash_key: algorithm === "hash" || algorithm === "ip_hash" ? "/media/a.mp3" : "-", client_ip: "203.0.113.10", country: "PL",
req_id: "7f3a9c1e2b4d", method: "GET", host: (() => { try { return lines(read("hosts")?.value || "")[0] || "example.com"; } catch { return "example.com"; } })(),
path: "/media/a.mp3", cache_status: context.cache, backend_time: hits ? "-" : "12.40ms"
};
}
// Checks a header value and renders it with example variables.
function headerValueCheck(value, direction, vars = headerExampleVars()) {
const text = String(value ?? "");
if (!text.includes("%[")) return { dynamic: false, rendered: text };
let rendered = "", rest = text;
while (rest.includes("%[")) {
const start = rest.indexOf("%["), end = rest.indexOf("]", start);
if (end < 0) return { error: t("hdrErrUnterminated") };
const name = rest.slice(start + 2, end);
if (!HEADER_VARIABLE_NAMES.has(name)) return { error: t("hdrErrUnknown").replace("{name}", name) };
if (direction === "request" && HEADER_RESPONSE_ONLY.has(name)) return { error: t("hdrErrResponseOnly").replace("{name}", name) };
rendered += rest.slice(0, start) + (vars[name] || "-"); rest = rest.slice(end + 1);
}
return { dynamic: true, rendered: rendered + rest };
}
// Applies header rules to an ordered header list [{name, value, source, dynamic}].
function headerApplyRules(list, rules, source, direction, vars, stage) {
for (const rule of rules || []) {
if (!rule?.name) continue;
const check = rule.op === "remove" ? { dynamic: false } : headerValueCheck(rule.value, direction, vars);
if (check.error) continue;
if (stage === "static" && check.dynamic) continue;
if (stage === "dynamic" && !check.dynamic) continue;
const lower = rule.name.toLowerCase();
if (rule.op === "remove") { for (const item of list) if (item.name.toLowerCase() === lower && !item.removed) item.removed = source; continue; }
if (rule.op === "set") for (const item of list) if (item.name.toLowerCase() === lower && !item.removed) item.removed = source;
list.push({ name: rule.name, value: check.rendered, source, dynamic: check.dynamic });
}
}
function headersPreview(parent) {
const box = el("div", undefined, "vh-wide hdr-preview"); parent.append(box);
const controls = el("div", undefined, "hdr-preview-controls"); box.append(controls);
const select = (key, onChange) => { const label = el("label", undefined, "hdr-preview-control"), input = document.createElement("select"); label.append(text("span", key), input); controls.append(label); input.addEventListener("change", () => { onChange(input.value); render(); }); return input; };
const memberSelect = select("hdrExampleBackend", value => { headerExampleContext.member = value; });
const locationSelect = select("hdrExampleLocation", value => { headerExampleContext.location = value; });
const cacheSelect = select("hdrExampleCache", value => { headerExampleContext.cache = value; });
for (const value of ["MISS", "HIT", "BYPASS"]) { const o = el("option", value); o.value = value; cacheSelect.append(o); }
const columns = el("div", undefined, "hdr-preview-columns"); box.append(columns);
const column = (key, hint) => { const col = el("section", undefined, "hdr-preview-col"); col.append(text("h4", key), text("p", hint, "fine")); const listNode = el("ul", undefined, "hdr-preview-list"); col.append(listNode); columns.append(col); return listNode; };
const requestList = column("hdrPreviewRequest", "hdrPreviewRequestHint"), responseList = column("hdrPreviewResponse", "hdrPreviewResponseHint");
box.append(text("p", "hdrPreviewHelp", "fine"));
const fillSelect = (node, options, current) => { node.replaceChildren(...options.map(([value, label]) => { const o = el("option", label); o.value = value; return o; })); node.value = options.some(([v]) => v === current) ? current : options[0]?.[0] ?? ""; return node.value; };
const readRoutes = () => { try { return JSON.parse(read("paths")?.value || "[]"); } catch { return []; } };
const safe = fn => { try { return fn(); } catch { return undefined; } };
const renderList = (node, items, empty) => {
node.replaceChildren();
if (!items.length) { node.append(el("li", t(empty), "fine")); return; }
for (const item of items) {
const li = el("li", undefined, `hdr-line${item.removed ? " is-removed" : ""}${item.system ? " is-system" : ""}`);
const code = el("code"); code.append(el("b", item.name), document.createTextNode(item.value === undefined ? "" : `: ${item.value}`)); li.append(code);
const tags = el("span", undefined, "hdr-tags");
tags.append(el("span", t(`hdrSource_${item.source}`), `hdr-tag is-${item.source}`));
if (item.dynamic) tags.append(el("span", t("hdrTagDynamic"), "hdr-tag is-dynamic"));
if (item.removed) tags.append(el("span", `${t("hdrTagRemoved")} (${t(`hdrSource_${item.removed}`)})`, "hdr-tag is-removed"));
li.append(tags); node.append(li);
}
};
const render = () => {
const members = safe(() => balancingMembers()) || [];
headerExampleContext.member = fillSelect(memberSelect, members.filter(m => m.id).map(m => [m.id, m.id]), headerExampleContext.member);
const routes = readRoutes();
headerExampleContext.location = fillSelect(locationSelect, [["main", t("rtMainSource")], ...routes.filter(r => r.id && !r.internal).map(r => [r.id, r.id])], headerExampleContext.location);
cacheSelect.value = headerExampleContext.cache;
const vars = headerExampleVars(), route = routes.find(r => r.id === headerExampleContext.location);
const global = envelope?.config?.headers || {}, vhost = safe(() => vhostHeadersControl?.read()) || {}, location = route?.headers || {};
// Request: static rules (global → vhost → location), then forwarding, then rules with variables.
const request = [], requestVars = headerExampleVars({ ...headerExampleContext, cache: "MISS" });
if (headerExampleContext.cache === "HIT") request.push({ name: t("hdrPreviewHitNoRequest"), value: undefined, source: "system", system: true });
else for (const stage of ["static", "dynamic"]) {
if (stage === "dynamic" && safe(() => yes("forward-client-ip"))) request.push({ name: "X-Forwarded-For / X-Real-IP", value: t("hdrForwardingValue"), source: "system", system: true });
headerApplyRules(request, global.request, "global", "request", requestVars, stage);
headerApplyRules(request, vhost.request, "vhost", "request", requestVars, stage);
headerApplyRules(request, location.request, "location", "request", requestVars, stage);
}
// Response: static rules, diagnostics and identity, then rules with variables.
const response = [];
headerApplyRules(response, global.response, "global", "response", vars, "static");
headerApplyRules(response, vhost.response, "vhost", "response", vars, "static");
headerApplyRules(response, location.response, "location", "response", vars, "static");
if (safe(() => yes("timing-headers"))) response.push({ name: "Server-Timing", value: "proxy;dur=1.8, upstream;dur=12.4", source: "diagnostics" });
if (safe(() => yes("backend-header")) && vars.srv_id !== "-") response.push({ name: "X-Rust-Proxy-Backend", value: `${vars.vhost}/${vars.srv_id}`, source: "diagnostics" });
if (safe(() => yes("backend-timing-header")) && vars.backend_time !== "-") response.push({ name: "X-RustProxy-Backend-Time", value: vars.backend_time, source: "diagnostics" });
const serverMode = safe(() => str("server-mode")) || "inherit";
const globalServer = envelope?.config?.server_header || { mode: "custom", value: "RustProxy" };
const effectiveServer = serverMode === "inherit" ? globalServer : { mode: serverMode, value: safe(() => str("server-value")) };
if (effectiveServer.mode === "custom") response.push({ name: "Server", value: effectiveServer.value || "RustProxy", source: serverMode === "inherit" ? "global" : "vhost" });
else if (effectiveServer.mode === "preserve") response.push({ name: "Server", value: t("hdrServerPreserved"), source: "system", system: true });
const requestId = safe(() => yes("diag-inherit")) ? envelope?.config?.diagnostic_headers?.request_id : safe(() => yes("diag-request_id"));
if (requestId) response.push({ name: "X-Request-ID", value: vars.req_id, source: "diagnostics" });
headerApplyRules(response, global.response, "global", "response", vars, "dynamic");
headerApplyRules(response, vhost.response, "vhost", "response", vars, "dynamic");
headerApplyRules(response, location.response, "location", "response", vars, "dynamic");
renderList(requestList, request, "hdrPreviewNoneRequest");
renderList(responseList, response, "hdrPreviewNoneResponse");
};
let pending = 0;
const refresh = () => { cancelAnimationFrame(pending); pending = requestAnimationFrame(() => { if (box.isConnected) render(); }); };
return { refresh };
}
// One switch as a card that shows the header it produces.
function diagnosticCard(parent, { name, key, checked, header, example, help, extra }) {
const card = el("div", undefined, "hdr-card"), head = el("div", undefined, "hdr-card-head"); card.append(head);
const input = field(head, name, key, checked, "checkbox", { switch: true });
const sample = el("code", undefined, "hdr-card-sample"); sample.append(el("b", header), document.createTextNode(`: ${example}`)); card.append(sample);
if (help) card.append(text("p", help, "fine"));
let body = null; if (extra) { body = el("div", undefined, "vh-grid hdr-card-extra"); card.append(body); extra(body); }
const sync = () => { card.classList.toggle("is-on", input.checked); if (body) body.hidden = !input.checked; };
input.addEventListener("change", sync); sync(); parent.append(card); return input;
}
// The preview follows every edit in the editor and the Headers tab button.
for (const type of ["input", "change", "click"]) container.addEventListener(type, () => { headersPreviewControl?.refresh(); presetsRefresh(); });
$("vhost-tabs").addEventListener("click", () => headersPreviewControl?.refresh());