This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 00:46:49 +01:00
1 parent 51631810e1
commit e6176cfce3
28 files changed
+959 -506

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.42.4",
"version": "0.43.0",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
@@ -1,283 +0,0 @@
window.rustProxyDashboardLayout = (() => {
const dialog = $("overview-layout-dialog");
const visibleRoot = $("overview-layout-visible");
const hiddenRoot = $("overview-layout-hidden");
const saveButton = $("overview-layout-save");
const cancelButton = $("overview-layout-cancel");
const search = $("overview-layout-search");
const typeFilter = $("overview-layout-type-filter");
const message = $("overview-layout-message");
const defaultButton = $("overview-layout-default");
const resetButton = $("overview-layout-reset");
const resetConfirm = $("overview-reset-confirm");
const resetCancel = $("overview-reset-cancel");
const resetApply = $("overview-reset-apply");
let draft = null;
let dragging = null;
let saving = false;
let opening = false;
function initialDraft() {
const prefs = window.rustProxyPreferences?.current?.() || ADMIN_APPEARANCE_DEFAULTS;
const order = normalizeDashboardWidgets(prefs.dashboard_widgets);
return {
order, hidden: new Set(normalizeHiddenDashboardWidgets(prefs.dashboard_hidden_widgets, prefs.dashboard_widgets)),
sizes: normalizeDashboardWidgetSizes(prefs.dashboard_widget_sizes)
};
}
function defaultDraft() {
return {
order: [...ADMIN_DASHBOARD_WIDGETS],
hidden: new Set(ADMIN_DEFAULT_HIDDEN_WIDGETS),
sizes: null,
};
}
function label(id) {
const widget = ADMIN_DASHBOARD_BY_ID.get(id);
return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id;
}
function visibleIds() {
return dashboardVisualOrder(draft.order, draft.sizes)
.filter(id => !draft.hidden.has(id));
}
function enterFreeLayout() {
if (draft.sizes === null) {
draft.order = dashboardVisualOrder(draft.order, null);
draft.sizes = {};
}
}
function reorderVisible(nextVisible) {
enterFreeLayout();
const iter = nextVisible.values();
draft.order = draft.order.map(id => draft.hidden.has(id) ? id : iter.next().value);
render();
}
function move(id, target, after = false) {
const next = visibleIds();
if (id === target || !next.includes(id) || !next.includes(target)) return;
next.splice(next.indexOf(id), 1);
next.splice(next.indexOf(target) + (after ? 1 : 0), 0, id);
reorderVisible(next);
}
function nudge(id, direction) {
const next = visibleIds(), index = next.indexOf(id), other = index + direction;
if (index < 0 || other < 0 || other >= next.length) return;
[next[index], next[other]] = [next[other], next[index]];
reorderVisible(next);
visibleRoot.querySelector(`[data-preview-widget="${id}"] .overview-layout-up`)?.focus();
}
function resize(id, delta) {
if (!draft) return;
const widths = dashboardAllowedWidths(id);
const next = widths[widths.indexOf(dashboardWidgetWidth(id, draft.sizes)) + delta];
if (next === undefined) return;
enterFreeLayout();
if (next === dashboardDefaultWidth(id)) delete draft.sizes[id];
else draft.sizes[id] = next;
render();
visibleRoot.querySelector(`[data-preview-widget="${id}"] .${delta < 0 ? "overview-layout-narrow" : "overview-layout-widen"}`)?.focus();
}
function preview(id) {
const original = document.querySelector(`#panel-overview [data-dashboard-widget="${id}"]`);
if (!original) return el("article", label(id), "stat");
if (ADMIN_DASHBOARD_BY_ID.get(id)?.category === "panels") {
const card = el("article", undefined, "overview-layout-panel-preview");
card.append(el("strong", label(id)));
const chart = id === "backend_tiny" || id === "backend_table" ? null : original.querySelector?.("svg");
if (chart) {
const graphic = chart.cloneNode(true);
for (const node of [graphic, ...graphic.querySelectorAll("[id]")]) node.removeAttribute("id");
graphic.removeAttribute("data-i18n-aria");
graphic.setAttribute("aria-hidden", "true");
card.append(graphic);
}
const detailKey = ADMIN_DASHBOARD_BY_ID.get(id)?.description_key;
if (detailKey) card.append(el("small", t(detailKey)));
card.setAttribute("aria-hidden", "true");
return card;
}
const copy = original.cloneNode(true);
copy.hidden = false;
copy.removeAttribute("data-dashboard-widget");
for (const node of [copy, ...copy.querySelectorAll("[id]")]) node.removeAttribute("id");
for (const node of copy.querySelectorAll("[aria-labelledby], [aria-describedby]")) {
node.removeAttribute("aria-labelledby"); node.removeAttribute("aria-describedby");
}
copy.classList.add("overview-layout-card-preview");
copy.setAttribute("aria-hidden", "true");
return copy;
}
function render() {
if (!draft || !dialog) return;
const visible = visibleIds();
const tiles = visible.map((id, index) => {
const tile = el("div", undefined, "overview-layout-tile");
tile.dataset.previewWidget = id;
tile.dataset.dashboardSpan = String(dashboardWidgetWidth(id, draft.sizes));
if (ADMIN_DASHBOARD_BY_ID.get(id)?.category === "panels") tile.classList.add("is-panel");
tile.draggable = true;
tile.setAttribute("role", "listitem");
tile.setAttribute("aria-label", label(id));
const toolbar = el("div", undefined, "overview-layout-tile-toolbar");
const grip = el("span", "⠿", "overview-layout-grip");
grip.setAttribute("aria-hidden", "true");
const up = el("button", "←", "quiet overview-layout-up");
up.type = "button"; up.disabled = index === 0;
up.setAttribute("aria-label", `${t("moveUp")}: ${label(id)}`);
up.addEventListener("click", () => nudge(id, -1));
const down = el("button", "→", "quiet overview-layout-down");
down.type = "button"; down.disabled = index === visible.length - 1;
down.setAttribute("aria-label", `${t("moveDown")}: ${label(id)}`);
down.addEventListener("click", () => nudge(id, 1));
const hide = el("button", t("overviewLayoutEditorHide"), "quiet overview-layout-hide");
hide.type = "button";
hide.setAttribute("aria-label", `${t("overviewLayoutEditorHide")}: ${label(id)}`);
hide.addEventListener("click", () => { draft.hidden.add(id); render(); });
const widths = dashboardAllowedWidths(id);
const width = dashboardWidgetWidth(id, draft.sizes);
const at = widths.indexOf(width);
const narrow = el("button", "−", "quiet overview-layout-narrow");
narrow.type = "button"; narrow.disabled = at <= 0;
narrow.setAttribute("aria-label", `${t("overviewLayoutNarrow")}: ${label(id)}`);
narrow.addEventListener("click", () => resize(id, -1));
const widen = el("button", "+", "quiet overview-layout-widen");
widen.type = "button"; widen.disabled = at === widths.length - 1;
widen.setAttribute("aria-label", `${t("overviewLayoutWiden")}: ${label(id)}`);
widen.addEventListener("click", () => resize(id, 1));
const widthValue = el("span", `${width}/12`, "overview-layout-width-value");
widthValue.title = t("overviewLayoutWidth");
const sizeActions = el("span", undefined, "overview-layout-size-actions");
sizeActions.append(narrow, widthValue, widen);
const orderActions = el("span", undefined, "overview-layout-order-actions");
orderActions.append(up, down, hide);
const controls = el("span", undefined, "overview-layout-controls");
controls.append(sizeActions, orderActions);
toolbar.append(grip, dashboardWidgetTypeBadge(id), controls);
tile.append(toolbar, preview(id));
tile.addEventListener("dragstart", event => {
if (event.target !== tile) return;
dragging = id;
event.dataTransfer?.setData("text/plain", id);
if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
tile.classList.add("is-dragging");
});
tile.addEventListener("dragover", event => {
if (!dragging || dragging === id) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
tile.classList.add("is-drop-target");
});
tile.addEventListener("dragleave", () => tile.classList.remove("is-drop-target"));
tile.addEventListener("drop", event => {
event.preventDefault();
tile.classList.remove("is-drop-target");
if (dragging && dragging !== id) {
const startIndex = visibleIds().indexOf(dragging);
const targetIndex = visibleIds().indexOf(id);
move(dragging, id, startIndex < targetIndex);
}
dragging = null;
});
tile.addEventListener("dragend", () => { dragging = null; tile.classList.remove("is-dragging", "is-drop-target"); });
return tile;
});
visibleRoot.replaceChildren(...(tiles.length ? tiles : [el("p", t("overviewLayoutEditorEmpty"), "fine")]));
const query = (search?.value || "").trim().toLocaleLowerCase();
const docker = window.rustProxyDockerDashboard;
const hiddenLabel = id => docker?.isDocker?.(id) ? dashboardWidgetBaseLabel(id) : label(id);
const collapsed = docker?.collapseHidden?.(draft.order.filter(id => draft.hidden.has(id))) || draft.order.filter(id => draft.hidden.has(id));
const hidden = collapsed.filter(id => (typeFilter?.value === "all" || !typeFilter?.value || dashboardWidgetType(id) === typeFilter.value)
&& (`${hiddenLabel(id)} ${dashboardWidgetTypeLabel(id)}`).toLocaleLowerCase().includes(query));
const hiddenItems = hidden.map(id => {
const item = el("div", undefined, "overview-layout-hidden-item");
item.setAttribute("role", "listitem");
const name = el("span", hiddenLabel(id));
const meta = ADMIN_DASHBOARD_BY_ID.get(id)?.description_key;
if (meta) name.title = t(meta);
const picker = docker?.agentPicker?.(id);
const add = el("button", t("overviewLayoutEditorShow"), "outline");
add.type = "button";
add.setAttribute("aria-label", `${t("overviewLayoutEditorShow")}: ${hiddenLabel(id)}`);
add.addEventListener("click", async () => { const slot = docker?.slotFor?.(id, draft.hidden) || id; add.disabled = true; try { await docker?.addWithScope?.(slot, picker); } finally { add.disabled = false; } draft.hidden.delete(slot); render(); });
item.append(name, dashboardWidgetTypeBadge(id));
if (picker) item.append(picker);
item.append(add);
return item;
});
hiddenRoot.replaceChildren(...(hiddenItems.length || query ? hiddenItems : [el("p", t("overviewLayoutEditorHiddenEmpty"), "fine")]));
}
async function open() {
if (dialog?.open || opening || window.rustProxyInlineLayout?.isEditing?.()) return;
opening = true;
try { await window.rustProxyPreferences?.load?.(); }
catch (error) { if (error?.status === 401) { opening = false; return; } }
opening = false;
draft = initialDraft();
dragging = null;
search.value = "";
if (typeFilter) typeFilter.value = "all";
message.textContent = "";
render();
dialog.showModal();
cancelButton.focus();
}
function setSaving(value) {
saving = value;
for (const control of [saveButton, cancelButton, defaultButton, resetButton, resetCancel, resetApply])
if (control) control.disabled = value;
}
function restoreDefaultPreview() {
if (saving || !draft) return;
draft = defaultDraft();
dragging = null;
if (search) search.value = "";
if (typeFilter) typeFilter.value = "all";
message.textContent = t("overviewLayoutDefaultLoaded");
render();
}
async function resetToDefault() {
if (saving || !draft) return;
setSaving(true);
message.textContent = t("overviewLayoutEditorSaving");
const defaults = defaultDraft();
try {
await window.rustProxyPreferences.update({
dashboard_widgets: [...defaults.order], dashboard_hidden_widgets: [...defaults.hidden],
dashboard_widget_sizes: null, dashboard_widget_heights: null,
});
resetConfirm.close();
dialog.close();
toast(t("overviewLayoutResetSaved"));
} catch (error) { message.textContent = error.message; }
finally { setSaving(false); }
}
async function save() {
if (saving || !draft) return;
setSaving(true);
message.textContent = t("overviewLayoutEditorSaving");
try {
await window.rustProxyPreferences.update({
dashboard_widgets: [...draft.order], dashboard_hidden_widgets: [...draft.hidden],
dashboard_widget_sizes: draft.sizes === null ? null : { ...draft.sizes },
});
dialog.close();
toast(t("overviewLayoutEditorSaved"));
} catch (error) { message.textContent = error.message; }
finally { setSaving(false); }
}
for (const id of ["overview-layout-open", "overview-layout-open-settings"]) $(id)?.addEventListener("click", () => { void open(); });
cancelButton.addEventListener("click", () => { if (!saving) dialog.close(); });
saveButton.addEventListener("click", () => { void save(); });
defaultButton?.addEventListener("click", restoreDefaultPreview);
resetButton?.addEventListener("click", () => {
if (!saving && draft && !resetConfirm.open) resetConfirm.showModal();
});
resetCancel?.addEventListener("click", () => { if (!saving) resetConfirm.close(); });
resetApply?.addEventListener("click", () => { void resetToDefault(); });
resetConfirm?.addEventListener("cancel", event => { if (saving) event.preventDefault(); });
search.addEventListener("input", render);
typeFilter?.addEventListener("change", render);
dialog.addEventListener("cancel", event => { if (saving || resetConfirm.open) event.preventDefault(); });
dialog.addEventListener("close", () => { draft = null; dragging = null; message.textContent = ""; });
return { open, refresh: () => { if (dialog.open) render(); } };
})();
+49
View File
@@ -302,3 +302,52 @@ const uiIconObserver = new MutationObserver(records => {
targets.forEach(uiDecorateIconTarget);
});
window.rustProxyIcons = { refresh: refreshUiIcons, setEnabled: setUiIconsEnabled, iconFor: uiIconForTarget };
// Shared information popovers (<details class="metric-info">): one is open at a time, Escape or
// a click elsewhere closes it, and its bubble is kept inside the visible (clipping) area.
(() => {
const MARGIN = 8;
const visibleArea = node => {
const root = document.documentElement;
const area = { left: 0, top: 0, right: root.clientWidth, bottom: root.clientHeight };
for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
const style = getComputedStyle(parent);
if (style.overflowX === "visible" && style.overflowY === "visible") continue;
const rect = parent.getBoundingClientRect();
area.left = Math.max(area.left, rect.left); area.right = Math.min(area.right, rect.right);
area.top = Math.max(area.top, rect.top); area.bottom = Math.min(area.bottom, rect.bottom);
}
return area;
};
const reset = details => { details.style.removeProperty("--rp-info-shift-x"); details.classList.remove("is-above"); };
const place = details => {
const popover = details.querySelector(":scope > .metric-info-popover"), summary = details.querySelector(":scope > summary");
if (!popover || !summary) return;
reset(details);
const zoom = Number.parseFloat(getComputedStyle(document.body).zoom) || 1, area = visibleArea(details), rect = popover.getBoundingClientRect();
let shift = 0;
if (rect.right > area.right - MARGIN) shift = area.right - MARGIN - rect.right;
if (rect.left + shift < area.left + MARGIN) shift = area.left + MARGIN - rect.left;
if (Math.abs(shift) >= 1) details.style.setProperty("--rp-info-shift-x", `${Math.round(shift / zoom)}px`);
const anchor = summary.getBoundingClientRect(), viewportBottom = document.documentElement.clientHeight;
if (rect.bottom > Math.min(area.bottom, viewportBottom) - MARGIN && anchor.top - rect.height - MARGIN > Math.max(area.top, 0)) details.classList.add("is-above");
};
const openInfo = () => document.querySelectorAll("details.metric-info[open]");
document.addEventListener("toggle", event => {
const details = event.target;
if (!(details instanceof HTMLDetailsElement) || !details.classList.contains("metric-info")) return;
if (!details.open) { reset(details); return; }
openInfo().forEach(other => { if (other !== details && !other.contains(details)) other.open = false; });
place(details);
}, true);
document.addEventListener("pointerdown", event => {
openInfo().forEach(details => { if (!details.contains(event.target)) details.open = false; });
}, true);
document.addEventListener("keydown", event => {
if (event.key !== "Escape") return;
const open = [...openInfo()]; if (!open.length) return;
event.preventDefault(); event.stopPropagation();
for (const details of open) { const focused = details.contains(document.activeElement); details.open = false; if (focused) details.querySelector(":scope > summary")?.focus(); }
}, true);
window.addEventListener("resize", () => openInfo().forEach(place));
})();
+32 -8
View File
@@ -1367,9 +1367,19 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
position: relative;
}
.metric-info>summary {
/* One information affordance for the whole panel: <details class="metric-info">
with a summary popover, or a .rp-info-icon button that opens a help dialog.
Shape follows the Appearance corner style; colors follow the theme. */
.metric-info>summary,
.rp-info-icon {
box-sizing: border-box;
flex: 0 0 auto;
width: 18px;
height: 18px;
min-width: 18px;
min-height: 0;
margin: 0;
padding: 0;
display: inline-grid;
place-items: center;
list-style: none;
@@ -1377,9 +1387,10 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
border: 1px solid var(--line);
color: var(--muted);
background: var(--panel2);
font: 700 10px var(--mono);
font: 700 10px/1 var(--mono);
user-select: none;
border-radius: var(--rp-radius-control, 50%);
transition: color .12s ease, border-color .12s ease, background-color .12s ease;
}
.metric-info>summary::-webkit-details-marker,
@@ -1391,14 +1402,18 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
}
.metric-info>summary:hover,
.metric-info[open]>summary {
color: var(--text);
border-color: var(--border-hover);
.metric-info[open]>summary,
.rp-info-icon:hover,
.rp-info-icon[aria-expanded=true] {
color: var(--accent);
border-color: var(--accent);
background: var(--panel2);
}
.metric-info>summary:focus-visible {
color: var(--text);
border-color: var(--border-hover);
.metric-info>summary:focus-visible,
.rp-info-icon:focus-visible {
color: var(--accent);
border-color: var(--accent);
outline: 2px solid var(--accent);
outline-offset: 2px;
}
@@ -1414,9 +1429,18 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
border-radius: var(--rp-radius-surface, 6px);
background: var(--panel2);
box-shadow: 0 12px 30px var(--shadow-mid);
color: var(--text);
font-size: 12px;
line-height: 1.5;
white-space: normal;
text-align: left;
overflow-wrap: break-word;
translate: var(--rp-info-shift-x, 0px) 0;
}
.metric-info.is-above>.metric-info-popover {
top: auto;
bottom: calc(100% + 7px);
}
.metric-info-popover .fine {
+1 -18
View File
@@ -1012,23 +1012,6 @@ html[data-dashboard-density=ultra] #panel-overview .stat-cache-outcomes .cache-m
font-weight: 600;
}
.runtime-information-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
.runtime-information-grid>div {
min-width: 0;
display: grid;
gap: 5px;
}
.runtime-information-grid code {
overflow-wrap: anywhere;
white-space: normal;
}
.connection-card h2 {
display: flex;
align-items: baseline;
@@ -2073,7 +2056,7 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
border-radius: var(--rp-radius-surface) !important;
}
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(button:not(.nav):not(.file-log-tab):not(.vhost-backend-trigger), input:not([type=checkbox]):not([type=radio]):not([type=range]), select, textarea, .pill, .vhost-backend-protocol-badge, .overview-widget-type, .quiet, .outline, .primary, .code, .command, .dashboard-widget-toggle, .settings-tabs button, .overview-inline-restore),
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(button:not(.nav):not(.file-log-tab):not(.vhost-backend-trigger):not(.location-tab), input:not([type=checkbox]):not([type=radio]):not([type=range]), select, textarea, .pill, .vhost-backend-protocol-badge, .overview-widget-type, .quiet, .outline, .primary, .code, .command, .dashboard-widget-toggle, .settings-tabs button, .overview-inline-restore),
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(.nav, .file-log-tab, .vhost-backend-trigger, .backend-column-options, .docker-service-quick-actions a, .docker-service-quick-actions button, .docker-view-toggle, .provider-picker, .renewal-meta-item) {
border-radius: var(--rp-radius-control) !important;
}
+270 -13
View File
@@ -368,12 +368,227 @@
border-bottom: 1px solid var(--row-line);
}
/* Collapsed Custom Location = one routing-table row. */
.location-summary {
display: grid;
grid-template-columns: 26px 12px minmax(0, 120px) 120px minmax(0, 1fr) minmax(0, 1.3fr) minmax(0, 1.3fr);
align-items: center;
gap: 4px 10px;
overflow-wrap: anywhere;
cursor: pointer;
padding: 10px 12px;
font: 600 11px/1.45 var(--mono);
padding: 9px 12px;
font: 400 12px/1.45 var(--sans);
color: var(--text);
list-style: none;
}
.location-summary::-webkit-details-marker {
display: none;
}
.location-summary:hover {
background: var(--panel2);
}
.loc-order {
color: var(--muted);
font: 600 11px var(--mono);
}
.loc-state {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--green);
}
.vh-location.is-disabled .loc-state {
background: var(--line);
}
.vh-location.is-disabled .location-summary {
color: var(--muted);
}
.loc-id,
.loc-path {
font: 600 11px var(--mono);
}
.loc-match {
justify-self: start;
padding: 2px 7px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 4px);
background: var(--panel2);
color: var(--muted);
font: 600 10px var(--mono);
white-space: nowrap;
}
.loc-match.is-internal {
border-color: var(--accent);
color: var(--accent);
}
.loc-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
min-width: 0;
}
.loc-chip {
padding: 1px 7px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 999px);
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.loc-chip.is-fallback {
border-color: var(--accent);
color: var(--accent);
}
.vh-location[open]>.location-summary {
background: var(--panel2);
}
.location-headline {
margin: 0;
font: 600 12px/1.5 var(--mono);
overflow-wrap: anywhere;
}
.location-cards {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.location-card,
.location-options {
min-width: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel);
}
.location-card {
padding: 10px 12px 12px;
}
.location-card-title {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 8px;
font-size: 12px;
}
.location-card-grid {
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
}
.location-step {
color: var(--accent);
font: 600 12px var(--mono);
}
.location-options-head {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 4px 14px;
padding: 10px 12px 0;
border-bottom: 1px solid var(--line);
}
.location-options-head>.location-card-title {
margin-bottom: 9px;
}
.location-tabs {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.location-tab {
min-height: 0;
padding: 7px 10px;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: transparent;
color: var(--muted);
font-size: 12px;
}
.location-tab:hover,
.location-tab.is-set {
color: var(--text);
}
.location-tab.active {
border-bottom-color: var(--accent);
color: var(--text);
font-weight: 600;
}
.location-tab-state {
color: var(--muted);
font-weight: 400;
}
.location-tab-panel {
padding: 12px;
}
.location-add-menu {
position: relative;
}
.location-templates {
position: absolute;
z-index: 30;
top: calc(100% + 6px);
left: 0;
width: calc(min(560px, calc(100 * var(--rp-vw)) - 48px));
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
padding: 8px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 6px);
background: var(--panel2);
box-shadow: 0 12px 30px var(--shadow-mid);
}
.location-templates[hidden] {
display: none;
}
.location-template {
display: grid;
gap: 3px;
min-height: 0;
padding: 8px 10px;
border: 1px solid var(--line);
background: var(--panel);
color: var(--text);
text-align: left;
}
.location-template:hover,
.location-template:focus-visible {
border-color: var(--accent);
}
.location-template>b {
font-size: 12px;
}
.vh-health-summary {
@@ -447,15 +662,10 @@
display: flex;
flex-direction: row;
margin-inline-start: 0;
gap: 3px;
position: sticky;
top: 29px;
z-index: 2;
background: var(--panel);
padding: 5px 0 8px;
border-bottom: 1px solid var(--line);
margin-bottom: 9px;
flex-wrap: nowrap;
overflow-x: auto;
overscroll-behavior-x: contain;
scrollbar-width: thin;
@@ -464,14 +674,10 @@
.vh-tabs button {
width: auto;
flex: 0 1 auto;
font-size: 10px;
padding: 6px 9px;
white-space: nowrap;
}
.vh-tabs button.active {
color: var(--text);
background: var(--nav-selected-bg);
border-color: var(--green);
}
@@ -2101,7 +2307,7 @@ html.app-loading,
min-width: 0;
}
.fine+:is(.switch-grid, .settings-tabs, .table-scroll, .soft-card, .appearance-settings-grid, .runtime-information-grid, details),
.fine+:is(.switch-grid, .settings-tabs, .table-scroll, .soft-card, .appearance-settings-grid, details),
.form-actions+.fine,
.table-scroll+:is(.empty, .fine),
.empty+.file-logs-pager {
@@ -2707,4 +2913,55 @@ h2+.fine {
.hdr-row.is-invalid .hdr-row-hint {
color: var(--red);
}
}
/* Error fallback status picker (vhost and Custom Location). */
.vh-error-fallback-statuses {
display: grid;
gap: 5px;
min-width: 0;
}
.vh-status-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.vh-status-chip {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
margin: 0;
padding: 3px 8px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 999px);
background: var(--panel2);
font: 600 11px var(--mono);
cursor: pointer;
}
.vh-status-chip>input {
position: absolute;
width: 1px;
height: 1px;
margin: 0;
opacity: 0;
pointer-events: none;
}
.vh-status-chip:has(input:checked) {
border-color: var(--accent);
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, var(--panel2));
}
.vh-status-chip:has(input:focus-visible) {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.vh-error-fallback-statuses.is-inactive .vh-status-chip {
opacity: .55;
cursor: default;
}
+11 -30
View File
@@ -304,6 +304,7 @@
.docker-protocol-editor,
.docker-security-editor,
.docker-diagnostics-editor,
.docker-policy-editor,
.docker-timeout-editor {
border-top: 1px solid var(--line);
padding-top: 9px;
@@ -315,11 +316,11 @@
.docker-protocol-editor>summary,
.docker-security-editor>summary,
.docker-diagnostics-editor>summary,
.docker-policy-editor>summary,
.docker-timeout-editor>summary {
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
user-select: none;
}
@@ -641,7 +642,6 @@ html:not([data-switch-controls="false"]) .docker-publish-field input.docker-publ
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
user-select: none;
}
@@ -1684,8 +1684,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
color: var(--accent);
}
.overview-inline-hidden-item .docker-widget-scope,
.overview-layout-hidden-item .docker-widget-scope {
.overview-inline-hidden-item .docker-widget-scope {
max-width: 160px;
min-height: 26px;
padding: 2px 6px;
@@ -1707,7 +1706,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
}
.docker-spark-primary {
stroke: var(--chart-primary, var(--accent));
stroke: var(--accent);
}
.docker-spark-secondary {
@@ -1965,26 +1964,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
min-width: 0;
}
.docker-label-info {
flex: 0 0 auto;
width: 20px;
height: 20px;
min-height: 0;
padding: 0;
border-radius: var(--rp-radius-control, 0px);
border: 1px solid var(--line);
background: var(--panel);
color: var(--accent);
font-size: 12px;
font-weight: 700;
line-height: 1;
cursor: pointer;
}
.docker-label-info:hover {
border-color: var(--accent);
}
#location-help-body .docker-label-table {
width: 100%;
table-layout: auto;
@@ -2724,7 +2703,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px 14px;
align-items: end;
}
.cache-rule-field {
@@ -3554,7 +3532,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.docker-service-group-rows {
display: grid;
gap: var(--ui-gap-sm, 8px);
gap: 8px;
padding: 0 8px 8px;
}
@@ -3574,11 +3552,13 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
min-width: 0;
}
.docker-security-grid .docker-wide-field {
.docker-security-grid .docker-wide-field,
.docker-diagnostics-grid .docker-wide-field {
grid-column: 1 / -1;
}
.docker-security-grid .docker-subheading {
.docker-security-grid .docker-subheading,
.docker-diagnostics-grid .docker-subheading {
grid-column: 1 / -1;
margin: 8px 0 0;
padding-top: 8px;
@@ -3590,7 +3570,8 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
text-transform: uppercase;
}
.docker-security-grid .docker-subheading:first-child {
.docker-security-grid .docker-subheading:first-child,
.docker-diagnostics-grid .docker-subheading:first-child {
margin-top: 0;
padding-top: 0;
border-top: 0;
+6 -7
View File
@@ -457,15 +457,14 @@
min-width: 520px;
}
.docker-policy-editor {
margin: 12px 0;
border: 1px solid var(--line);
padding: 12px;
/* HTTP policies are nested in the Docker service "Headers" section and use the
same disclosure row as the other Docker service sections. */
.docker-headers-editor .docker-policy-editor {
margin-top: 12px;
}
.docker-policy-editor>summary {
cursor: pointer;
font-weight: 600;
.docker-policy-editor>.http-policy-editor {
margin-top: 10px;
}
@media (max-width: 760px) {
-22
View File
@@ -219,15 +219,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
min-width: 190px;
}
.cache-reason {
display: inline-block;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 4px);
padding: 2px 5px;
margin: 1px 4px 2px 0;
font-size: 10px;
}
#panel-cache thead th {
position: sticky;
top: 0;
@@ -237,8 +228,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
#panel-cache .cache-table .cache-reasons {
white-space: normal;
min-width: 210px;
max-width: 300px;
}
#panel-cache .cache-copy-cell {
@@ -429,7 +418,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
.transform-reason-list {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.cache-transform-badge {
@@ -991,7 +979,6 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
.cache-varnish-info,
.cache-maintenance-info {
position: static;
flex-shrink: 0;
}
@@ -1232,12 +1219,6 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
background: var(--chart-accent);
}
#cache-domain-scroll .cache-reason {
border-color: transparent;
background: var(--panel2);
color: var(--muted);
}
#panel-cache .cache-table .cache-reasons {
min-width: 200px;
max-width: 320px;
@@ -1320,13 +1301,10 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
align-items: center;
gap: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 6px);
overflow: hidden;
}
.cache-pager button {
border: 0;
border-radius: 0;
min-width: 88px;
margin: 0;
}
+24 -5
View File
@@ -762,6 +762,21 @@
grid-template-columns: 1fr 1fr;
}
.location-summary {
grid-template-columns: 22px 10px minmax(0, 1fr) auto;
}
.location-summary>.loc-path,
.location-summary>.loc-action,
.location-summary>.loc-chips {
grid-column: 3 / -1;
}
.location-cards,
.location-templates {
grid-template-columns: minmax(0, 1fr);
}
.location-actions,
.location-toolbar {
align-items: stretch;
@@ -1804,6 +1819,7 @@
.docker-protocol-editor>summary,
.docker-security-editor>summary,
.docker-diagnostics-editor>summary,
.docker-policy-editor>summary,
.docker-timeout-editor>summary,
.docker-passive-health-editor>summary {
list-style: none;
@@ -1816,6 +1832,7 @@
.docker-protocol-editor>summary::-webkit-details-marker,
.docker-security-editor>summary::-webkit-details-marker,
.docker-diagnostics-editor>summary::-webkit-details-marker,
.docker-policy-editor>summary::-webkit-details-marker,
.docker-timeout-editor>summary::-webkit-details-marker,
.docker-passive-health-editor>summary::-webkit-details-marker {
display: none;
@@ -1828,6 +1845,7 @@
.docker-protocol-editor>summary::before,
.docker-security-editor>summary::before,
.docker-diagnostics-editor>summary::before,
.docker-policy-editor>summary::before,
.docker-timeout-editor>summary::before,
.docker-passive-health-editor>summary::before {
content: "›";
@@ -1847,6 +1865,7 @@
.docker-protocol-editor[open]>summary::before,
.docker-security-editor[open]>summary::before,
.docker-diagnostics-editor[open]>summary::before,
.docker-policy-editor[open]>summary::before,
.docker-timeout-editor[open]>summary::before,
.docker-passive-health-editor[open]>summary::before {
transform: rotate(90deg);
@@ -1857,11 +1876,6 @@
flex: 0 0 auto;
}
.docker-service-editor>summary .docker-config-hint {
flex: 1;
min-width: 0;
}
.docker-service-editor:not(.docker-service-metrics)>summary:hover>span {
color: var(--green);
}
@@ -1889,6 +1903,7 @@
.docker-protocol-editor>summary:focus-visible,
.docker-security-editor>summary:focus-visible,
.docker-diagnostics-editor>summary:focus-visible,
.docker-policy-editor>summary:focus-visible,
.docker-timeout-editor>summary:focus-visible,
.docker-health-editor>summary:focus-visible {
outline: 2px solid var(--green);
@@ -2055,6 +2070,7 @@
.docker-protocol-editor>summary,
.docker-security-editor>summary,
.docker-diagnostics-editor>summary,
.docker-policy-editor>summary,
.docker-timeout-editor>summary,
.docker-passive-health-editor>summary {
justify-content: flex-start;
@@ -2068,6 +2084,7 @@
.docker-protocol-editor>summary>span,
.docker-security-editor>summary>span,
.docker-diagnostics-editor>summary>span,
.docker-policy-editor>summary>span,
.docker-timeout-editor>summary>span,
.docker-passive-health-editor>summary>span {
text-align: left;
@@ -2080,6 +2097,7 @@
.docker-protocol-editor>summary>small,
.docker-security-editor>summary>small,
.docker-diagnostics-editor>summary>small,
.docker-policy-editor>summary>small,
.docker-timeout-editor>summary>small,
.docker-passive-health-editor>summary>small {
flex: 1 1 auto;
@@ -2096,6 +2114,7 @@
.docker-protocol-editor>summary>span,
.docker-security-editor>summary>span,
.docker-diagnostics-editor>summary>span,
.docker-policy-editor>summary>span,
.docker-timeout-editor>summary>span,
.docker-passive-health-editor>summary>span {
flex: 0 0 190px;
+27 -11
View File
@@ -485,7 +485,7 @@
provisionInput.addEventListener("keydown", event => { if (event.key === "Enter") { event.preventDefault(); void applyProvision(); } });
row.focusProvision = () => { provision.open = true; provisionInput.focus(); };
const labelPublish = input("", "checkbox", "docker-agent-label-publish switch"); labelPublish.checked = value.label_publish === true;
const labelField = checkboxField("dockerLabelPublish", labelPublish), labelHelp = el("small", undefined, "fine docker-label-help"), labelInfo = el("button", "?", "docker-label-info"); labelInfo.type = "button"; labelInfo.dataset.uiIconName = "none"; labelInfo.title = t("dockerLabelHelpTitle"); labelInfo.setAttribute("aria-label", t("dockerLabelHelpTitle")); labelInfo.addEventListener("click", openLabelHelp);
const labelField = checkboxField("dockerLabelPublish", labelPublish), labelHelp = el("small", undefined, "fine docker-label-help"), labelInfo = el("button", "?", "docker-label-info rp-info-icon"); labelInfo.type = "button"; labelInfo.setAttribute("aria-haspopup", "dialog"); labelInfo.dataset.uiIconName = "none"; labelInfo.title = t("dockerLabelHelpTitle"); labelInfo.setAttribute("aria-label", t("dockerLabelHelpTitle")); labelInfo.addEventListener("click", openLabelHelp);
labelHelp.append(el("span", t("dockerLabelPublishHelp")), labelInfo); labelField.append(labelHelp);
let closeBubble = null;
const showBubble = (text, kind) => {
@@ -875,17 +875,33 @@
basic_auth: collectBasicAuth(row),
};
}
function diagnosticsEditor(assignment) {
const details = el("details", undefined, "docker-diagnostics-editor"), summary = el("summary"); summary.append(el("span", t("dockerDiagnostics")), el("small", t("dockerDiagnosticsHelp"), "fine")); details.append(summary);
// "Headers": diagnostic response headers and the vhost's HTTP policy rules.
// The policy editor stays collapsed inside this section until it is needed.
function headersEditor(assignment, row) {
const details = el("details", undefined, "docker-diagnostics-editor docker-headers-editor"), summary = el("summary"), state = el("small", "", "fine");
summary.append(el("span", t("dockerHeaders")), state); details.append(summary);
const grid = el("div", undefined, "field-grid docker-diagnostics-grid");
const box = (cls, value) => { const node = input("", "checkbox", `${cls} switch`); node.checked = value === true; return node; };
grid.append(checkboxField("vhTimingHeaders", box("docker-timing-headers", assignment?.timing_headers)), checkboxField("vhBackendHeader", box("docker-backend-header", assignment?.backend_header)), checkboxField("vhBackendTimingHeader", box("docker-backend-timing-header", assignment?.backend_timing_header)));
details.append(grid); return details;
}
function policyEditor(assignment, row) {
const details = el("details", undefined, "docker-policy-editor"); details.append(el("summary", t("policyTitle")));
const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => row.classList.add("is-dirty") });
details.append(policy.node); row._readPolicy = () => policy.read(); return details;
const timing = box("docker-timing-headers", assignment?.timing_headers), backend = box("docker-backend-header", assignment?.backend_header), backendTiming = box("docker-backend-timing-header", assignment?.backend_timing_header);
grid.append(el("h4", t("dockerDiagnostics"), "docker-subheading docker-wide-field"), el("p", t("dockerDiagnosticsHelp"), "fine docker-wide-field"),
checkboxField("vhTimingHeaders", timing), checkboxField("vhBackendHeader", backend), checkboxField("vhBackendTimingHeader", backendTiming));
const policyBox = el("details", undefined, "docker-policy-editor"), policySummary = el("summary"), policyState = el("small", "", "fine");
policySummary.append(el("span", t("policyTitle")), policyState); policyBox.append(policySummary);
let sync = () => { };
const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => { row.classList.add("is-dirty"); sync(); } });
policyBox.append(policy.node); row._readPolicy = () => policy.read();
details.append(grid, policyBox);
let ruleCount = (assignment?.policy?.rules || []).length;
sync = () => {
const rules = policy.node.querySelector(".policy-visual:not([hidden]) .policy-rules");
if (rules) ruleCount = rules.querySelectorAll(":scope > .policy-rule").length;
const rulesText = ruleCount ? t("dockerPolicyRuleCount").replace("{count}", ruleCount) : t("dockerPolicyNone");
policyState.textContent = rulesText;
const enabled = [[timing, "Server-Timing"], [backend, "X-RustProxy-Backend"], [backendTiming, "X-RustProxy-Backend-Time"]].filter(([control]) => control.checked).map(([, label]) => label);
state.textContent = enabled.length || ruleCount ? [...enabled, ...(ruleCount ? [rulesText] : [])].join(" · ") : t("dockerHeadersHelp");
};
details.addEventListener("input", sync); details.addEventListener("change", sync); sync();
return details;
}
function collectDiagnostics(row) {
const on = cls => row.querySelector(cls)?.checked === true;
@@ -1068,7 +1084,7 @@
protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled));
protocolBox.append(protocolSummary, protocolOptions);
route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp();
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), policyEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), headersEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions);
function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint();
for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); }
+1 -1
View File
@@ -348,7 +348,7 @@
const restart = t("restartFieldBadge");
panel.querySelectorAll("[data-restart]").forEach(node => { const span = node.querySelector(":scope > span"); if (span && span.dataset.restartBadge !== restart) span.dataset.restartBadge = restart; node.title = t("restartFieldHelp"); });
panel.querySelectorAll(".settings-page .fine:not([role=status]):not(.help-clamp)").forEach(node => {
if (node.id?.endsWith("-status") || node.closest(".certificate-api-credential-item, .acl-picker, .docker-container-state, dialog")) return;
if (node.id?.endsWith("-status") || node.closest(".certificate-api-credential-item, .acl-picker, .docker-container-state, .metric-info-popover, dialog")) return;
if ((node.textContent || "").trim().length < HELP_CLAMP_LENGTH) return;
node.classList.add("help-clamp"); node.tabIndex = 0; node.setAttribute("aria-expanded", "false");
const toggle = () => { const open = !node.classList.contains("is-open"); node.classList.toggle("is-open", open); node.setAttribute("aria-expanded", String(open)); };
+146 -38
View File
@@ -426,12 +426,63 @@ function openLocationHelp(topic = "locations") {
}
dialog.showModal();
}
// Error fallback = target internal location + the upstream statuses it handles.
// The status chips write the legacy comma-separated "<prefix>-statuses" field,
// so readers, JSON drawers and saved configuration keep their exact format.
const ERROR_FALLBACK_STATUSES = [403, 404, 500, 502, 503, 504];
let errorFallbackListId = 0;
const internalLocationIds = () => [...form.querySelectorAll('.vh-location [name="location-internal"]')].filter(box => box.checked)
.map(box => read("location-id", box.closest(".vh-location"))?.value.trim()).filter(Boolean);
function errorFallbackFields(parent, prefix, value, keys) {
const target = field(parent, `${prefix}-target`, keys.target, value?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
target.placeholder = t("errorFallbackTargetPlaceholder"); target.autocomplete = "off";
const list = el("datalist"); list.id = `vh-error-fallback-targets-${++errorFallbackListId}`; target.setAttribute("list", list.id); target.closest("label").append(list);
const fillTargets = () => list.replaceChildren(...internalLocationIds().map(id => { const option = el("option"); option.value = id; return option; }));
target.addEventListener("focus", fillTargets);
const box = el("div", undefined, "vh-field vh-error-fallback-statuses"), caption = text("span", keys.statuses);
const hidden = document.createElement("input"); hidden.type = "hidden"; hidden.name = `${prefix}-statuses`;
const chips = el("div", undefined, "vh-status-chips"); chips.setAttribute("role", "group"); chips.setAttribute("aria-label", t(keys.statuses));
const initial = [...new Set((value?.statuses?.length ? value.statuses : [404]).map(Number))];
const choices = [...ERROR_FALLBACK_STATUSES, ...initial.filter(code => !ERROR_FALLBACK_STATUSES.includes(code))];
const boxes = choices.map(code => {
const label = el("label", undefined, "vh-status-chip"), input = document.createElement("input");
input.type = "checkbox"; input.value = String(code); input.checked = initial.includes(code);
label.append(input, el("span", String(code))); chips.append(label); return input;
});
const write = () => { hidden.value = boxes.filter(input => input.checked).map(input => input.value).join(", "); };
const sync = () => { const off = !target.value.trim(); box.classList.toggle("is-inactive", off); for (const input of boxes) input.disabled = off; };
chips.addEventListener("change", event => {
// At least one status stays selected; an empty list would silently mean 404.
if (!boxes.some(input => input.checked)) event.target.checked = true;
write(); hidden.dispatchEvent(new Event("input", { bubbles: true }));
});
target.addEventListener("input", sync);
box.append(caption, chips, hidden); parent.append(box); write(); sync();
return { target, statuses: hidden };
}
const LOCATION_GROUP = "__group__";
function locationsEditor(parent, values, onChange = changed) {
const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations");
const addTop = button("locationAdd", () => { add(); sync(); }, "primary");
const addHostRule = button("rtAddHostRule", () => { add({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }, true); sync(); });
toolbar.append(addTop, addHostRule, button("documentation", () => openLocationHelp("locations")));
// "Add location" opens starting points; each one only pre-fills ordinary fields.
const addMenu = el("div", undefined, "location-add-menu"), templates = el("div", undefined, "location-templates"); templates.hidden = true;
const showTemplates = open => { templates.hidden = !open; addTop.setAttribute("aria-expanded", String(open)); };
const addTop = button("locationAdd", () => showTemplates(templates.hidden), "primary"); addTop.setAttribute("aria-haspopup", "true"); addTop.setAttribute("aria-expanded", "false");
const template = (key, helpKey, make, openConditions = false) => {
const choice = el("button", undefined, "location-template"); choice.type = "button"; choice.append(text("b", key), text("span", helpKey, "fine"));
choice.addEventListener("click", () => { showTemplates(false); add(make(), openConditions); sync(); rows.lastElementChild?.scrollIntoView({ block: "nearest" }); rows.lastElementChild?.querySelector('[name="location-id"]')?.focus(); });
templates.append(choice);
};
template("locationTplProxy", "locationTplProxyHelp", () => ({ id: nextId("api"), path_prefix: "/api/", rewrite: { mode: "strip_prefix" } }));
template("locationTplWeb", "locationTplWebHelp", () => ({ id: nextId("files"), path_prefix: "/static/", source: { type: "web_server", web_service_id: "" } }));
template("locationTplRedirect", "locationTplRedirectHelp", () => ({ id: nextId("redirect"), path_prefix: "/old/", redirect: { status: 301, target: "", preserve_query: true } }));
template("locationTplReturn", "locationTplReturnHelp", () => ({ id: nextId("health"), match_type: "exact", path_prefix: "/healthz", response: { status: 200, content_type: "text/plain; charset=utf-8", body: "ok" } }));
template("locationTplInternal", "locationTplInternalHelp", () => ({ id: nextId("error"), internal: true }));
template("rtAddHostRule", "locationTplHostHelp", () => ({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }), true);
template("locationTplBlank", "locationTplBlankHelp", () => ({}));
addMenu.addEventListener("keydown", event => { if (event.key === "Escape" && !templates.hidden) { event.preventDefault(); event.stopPropagation(); showTemplates(false); addTop.focus(); } });
addMenu.addEventListener("focusout", event => { if (!addMenu.contains(event.relatedTarget)) showTemplates(false); });
addMenu.append(addTop, templates);
toolbar.append(addMenu, button("documentation", () => openLocationHelp("locations")));
parent.append(toolbar); note(parent, "locationHelp"); note(parent, "rtOrderHelp");
const tester = routingTester(parent, () => readRows());
parent.append(rows); let reloading = false;
@@ -464,32 +515,64 @@ function locationsEditor(parent, values, onChange = changed) {
};
});
}
function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); }
function renumber() { [...rows.children].forEach((row, index) => { if (row._order) row._order.textContent = String(index + 1); }); }
function sync() { renumber(); if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); }
function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; const groupOption = text("option", "locationBackendGroup"); groupOption.value = LOCATION_GROUP; select.replaceChildren(base, groupOption, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; }
function add(value = {}, openConditions = false) {
function add(value = {}, openConditions = false, open = true) {
if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; }
const row = el("details", undefined, "vh-location"); row.open = true;
const row = el("details", undefined, "vh-location"); row.open = open;
const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body);
// Collapsed row = one line of the routing table; expanded = When / What / Options.
const sumOrder = el("span", String(rows.children.length + 1), "loc-order"), sumState = el("span", undefined, "loc-state"), sumId = el("span", "", "loc-id");
const sumMatch = el("span", "", "loc-match"), sumPath = el("span", "", "loc-path"), sumAction = el("span", "", "loc-action"), sumChips = el("span", undefined, "loc-chips");
sumState.setAttribute("role", "img"); summary.append(sumOrder, sumState, sumId, sumMatch, sumPath, sumAction, sumChips); row._order = sumOrder;
const headline = el("p", "", "vh-wide location-headline"); body.append(headline);
const card = (cls, number, key) => {
const box = el("section", undefined, `location-card ${cls}`), head = el("h4", undefined, "location-card-title"), grid = el("div", undefined, "vh-grid location-card-grid");
head.append(el("span", number, "location-step"), text("span", key)); box.append(head, grid); return [box, grid];
};
const [whenCard, whenGrid] = card("location-when", "1", "locationStepWhen"), [whatCard, whatGrid] = card("location-what", "2", "locationStepWhat");
const cards = el("div", undefined, "vh-wide location-cards"); cards.append(whenCard, whatCard); body.append(cards);
const options = el("section", undefined, "vh-wide location-options"), optionsHead = el("div", undefined, "location-options-head"), tabList = el("div", undefined, "location-tabs"), panels = el("div", undefined, "location-tab-panels");
const optionsTitle = el("h4", undefined, "location-card-title"); optionsTitle.append(el("span", "3", "location-step"), text("span", "locationStepOptions"));
tabList.setAttribute("role", "tablist"); optionsHead.append(optionsTitle, tabList); options.append(optionsHead, panels); body.append(options);
const tabs = new Map(); let activeTab = "access";
const optionTab = (name, key) => {
const tab = el("button", undefined, "location-tab"), state = el("small", "", "location-tab-state"), panel = el("div", undefined, "vh-grid location-tab-panel");
tab.type = "button"; tab.setAttribute("role", "tab"); tab.append(text("span", key), state); panel.setAttribute("role", "tabpanel"); panel.hidden = true;
tab.addEventListener("click", () => selectTab(name)); tabList.append(tab); panels.append(panel); tabs.set(name, { tab, state, panel }); return panel;
};
const selectTab = name => {
const available = item => !item.tab.hidden;
let target = tabs.get(name); if (!target || !available(target)) target = [...tabs.values()].find(available);
for (const [key, item] of tabs) { const on = item === target; if (on) activeTab = key; item.tab.setAttribute("aria-selected", String(on)); item.tab.classList.toggle("active", on); item.panel.hidden = !on; }
};
const setTabAvailable = (name, available) => { const item = tabs.get(name); item.tab.hidden = !available; if (!available && activeTab === name) selectTab("access"); else if (activeTab === name) selectTab(name); };
const accessPanel = optionTab("access", "locationTabAccess"), headersPanel = optionTab("headers", "locationTabHeaders"), cachePanel = optionTab("cache", "locationTabCache");
const errorsPanel = optionTab("errors", "locationTabErrors"), backendPanel = optionTab("backend", "locationBalancing"), policyPanel = optionTab("policy", "policyTitle");
row.addEventListener("invalid", event => {
const panel = event.target.closest?.(".location-tab-panel"), entry = panel && [...tabs].find(([, item]) => item.panel === panel);
if (entry) selectTab(entry[0]); row.open = true;
}, true);
const used = new Set([...rows.children].map(r => str("location-id", r))); let suffix = 1; while (used.has(`location-${suffix}`)) suffix++;
field(body, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 });
const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] });
const path = field(body, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/";
const internal = field(body, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true });
field(whenGrid, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 });
const match = field(whenGrid, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] });
const path = field(whenGrid, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/";
const internal = field(whenGrid, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true });
const initialAction = value.response ? "return" : value.redirect ? "redirect" : value.source?.type === "web_server" ? "web_server" : "proxy";
const action = field(body, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] });
const action = field(whatGrid, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] });
const initialTarget = value.backend_ids?.length ? LOCATION_GROUP : value.backend_id || "";
const backend = field(body, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget);
const webService = field(body, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || "");
field(body, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true });
const cache = field(body, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] });
const backend = field(whatGrid, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget);
const webService = field(whatGrid, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || "");
field(whatGrid, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true });
const cache = field(cachePanel, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] });
const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); body.append(conditionBox);
const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); whenGrid.append(conditionBox);
conditionBox.open = openConditions || Boolean(value.conditions?.length);
note(conditionBody, "rtConditionsHelp");
const conditions = conditionsEditor(conditionBody, value.conditions || [], () => { syncUi(); sync(); }); row.readConditions = conditions.read;
const conditionCacheNote = text("p", "rtNotCachedHelp", "fine vh-wide"); conditionBody.append(conditionCacheNote);
const balancing = el("details", undefined, "vh-wide location-section location-balancing"), balancingBody = el("div", undefined, "vh-grid"); balancing.append(text("summary", "locationBalancing"), balancingBody); body.append(balancing);
balancing.open = Boolean(value.backend_ids?.length || value.load_balancing);
const balancingBody = backendPanel; balancingBody.classList.add("location-balancing");
const groupBox = el("div", undefined, "vh-wide location-group"); groupBox.append(text("span", "locationGroupMembers", "location-group-title"));
const groupList = el("div", undefined, "location-group-list"); groupBox.append(groupList, text("p", "locationGroupHelp", "fine")); balancingBody.append(groupBox);
const groupSelected = new Set(value.backend_ids || []);
@@ -503,7 +586,7 @@ function locationsEditor(parent, values, onChange = changed) {
}));
};
row.groupIds = () => { const ids = balancingMembers().map(m => m.id).filter(id => groupSelected.has(id)); if (!ids.length) throw new Error(t("locationGroupEmpty").replace("{location}", str("location-id", row))); return ids; };
backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) balancing.open = true; });
backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) selectTab("backend"); });
const ownBalancing = field(balancingBody, "location-lb-custom", "lbLocationOwn", Boolean(value.load_balancing), "checkbox", { switch: true });
const balancingSlot = el("div", undefined, "vh-wide vh-grid"); balancingBody.append(balancingSlot);
const balancingControl = balancingEditor(balancingSlot, {
@@ -515,10 +598,9 @@ function locationsEditor(parent, values, onChange = changed) {
row.readBalancing = () => { if (!ownBalancing.checked) return null; balancingControl.validate(); const hash = balancingControl.hash(); return { algorithm: balancingControl.algorithm(), ...(hash ? { hash } : {}), sticky: balancingControl.sticky() }; };
row.refreshBalancing = () => { renderGroup(); balancingControl.refresh(); };
renderGroup();
const handling = el("details", undefined, "vh-wide location-section"), handlingBody = el("div", undefined, "vh-grid"); handling.append(text("summary", "locationHandling"), handlingBody); body.append(handling);
field(handlingBody, "location-error-target", "locationErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
field(handlingBody, "location-error-statuses", "locationErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 });
note(handlingBody, "locationErrorFallbackHelp");
const handlingBody = whatGrid;
errorFallbackFields(errorsPanel, "location-error", value.error_fallback, { target: "locationErrorFallbackTarget", statuses: "locationErrorFallbackStatuses" });
note(errorsPanel, "locationErrorFallbackHelp");
const rewriteMode = field(handlingBody, "location-rewrite-mode", "locationRewriteMode", value.rewrite?.mode || "preserve", "select", { values: [["preserve", "locationRewritePreserve"], ["strip_prefix", "locationRewriteStrip"], ["replace_prefix", "locationRewriteReplace"], ["regex", "locationRewriteRegex"]] });
const rewriteValue = field(handlingBody, "location-rewrite-value", "locationRewriteValue", value.rewrite?.value || "", "text", { maxLength: 2048 });
const returnBox = el("div", undefined, "vh-wide vh-grid location-return-box"); handlingBody.append(returnBox);
@@ -531,9 +613,9 @@ function locationsEditor(parent, values, onChange = changed) {
field(redirectBox, "location-redirect-pattern", "locationRedirectPattern", value.redirect?.rewrite_pattern || "", "text", { maxLength: 1024 });
field(redirectBox, "location-redirect-query", "locationRedirectQuery", value.redirect?.preserve_query !== false, "checkbox", { switch: true });
note(redirectBox, "locationRedirectHelp");
note(handlingBody, "locationRewriteHelp");
const rewriteHelp = note(handlingBody, "locationRewriteHelp");
const extra = el("details", undefined, "vh-wide location-section"), accessBody = el("div", undefined, "vh-grid"); extra.append(text("summary", "locationAccess"), accessBody); body.append(extra);
const accessBody = accessPanel;
const locationProfiles = subsection(accessBody, "vhAclProfile");
const locationProfile = field(locationProfiles, "location-acl-profile", "locationAclProfile", value.acl_profile_id || "", "select");
const locationNoProfile = text("option", "vhAclProfileNone"); locationNoProfile.value = "";
@@ -549,15 +631,14 @@ function locationsEditor(parent, values, onChange = changed) {
note(locationCountries, "locationCountryHelp");
const locationAcl = subsection(accessBody, "vhLocationIpAclSection");
const acl = aclEditor(locationAcl, value.acl, sync); row.readAcl = () => acl.read();
const headerBox = el("details", undefined, "vh-wide location-section location-header-editor"), headerBody = el("div", undefined, "vh-grid"); headerBox.append(text("summary", "locationHeaders"), headerBody); body.append(headerBox);
const headerBody = headersPanel; headerBody.classList.add("location-header-editor");
const headerToolbar = el("div", undefined, "vh-wide location-header-toolbar"), visualPane = el("div", undefined, "vh-wide vh-grid"), jsonPane = el("div", undefined, "vh-wide vh-grid"); jsonPane.hidden = true;
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, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read();
const policyBox = el("details", undefined, "vh-wide location-section"), policyBody = el("div", undefined, "policy-detail-body");
policyBox.append(text("summary", "policyTitle"), policyBody); body.append(policyBox);
const policyBody = policyPanel; policyBody.classList.add("policy-detail-body");
const policyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "location", onChange: sync });
policyBody.append(policyEditor.node); row.readPolicy = () => policyEditor.read();
@@ -576,46 +657,54 @@ function locationsEditor(parent, values, onChange = changed) {
const moveDown = button("rtMoveDown", () => { if (row.nextElementSibling) { rows.insertBefore(row.nextElementSibling, row); sync(); } });
actions.append(moveUp, moveDown, dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions);
let policyCount = (value.policy?.rules || []).length;
const syncUi = () => {
const isReturn = action.value === "return", isRedirect = action.value === "redirect", isWeb = action.value === "web_server", isProxy = action.value === "proxy", isRegex = match.value === "regex" || match.value === "regex_insensitive";
match.disabled = internal.checked; path.disabled = internal.checked || match.value === "any";
match.closest("label").hidden = internal.checked; path.closest("label").hidden = internal.checked || match.value === "any";
const conditional = !internal.checked && conditions.count() > 0;
conditionBox.hidden = internal.checked; conditionCacheNote.hidden = !conditional;
if (conditional) cache.value = "";
backend.disabled = !isProxy; cache.disabled = !isProxy || conditional; dedicated.disabled = !isProxy;
const isGroup = isProxy && backend.value === LOCATION_GROUP, pinned = isProxy && !["", LOCATION_GROUP].includes(backend.value);
balancing.hidden = !isProxy || pinned; groupBox.hidden = !isGroup;
const balancingAvailable = isProxy && !pinned; setTabAvailable("backend", balancingAvailable); groupBox.hidden = !isGroup;
ownBalancing.disabled = !isProxy || pinned; balancingSlot.hidden = !ownBalancing.checked; inheritNote.hidden = ownBalancing.checked;
webService.disabled = !isWeb; webService.required = isWeb;
backend.closest("label").hidden = !isProxy; webService.closest("label").hidden = !isWeb;
rewriteMode.closest("label").hidden = isReturn || isRedirect; rewriteValue.closest("label").hidden = isReturn || isRedirect; rewriteHelp.hidden = isReturn || isRedirect;
returnBox.hidden = !isReturn; redirectBox.hidden = !isRedirect; rewriteMode.disabled = isReturn || isRedirect; rewriteValue.disabled = isReturn || isRedirect || rewriteMode.value === "preserve" || rewriteMode.value === "strip_prefix";
for (const option of rewriteMode.options) if (option.value === "regex") option.disabled = !isRegex;
if (!isRegex && rewriteMode.value === "regex") rewriteMode.value = "preserve";
path.placeholder = isRegex ? "^/api/v[0-9]+/" : "/api/";
const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : match.value === "any" ? "*" : (str("location-path", row) || "/");
const conditionNote = conditional ? ` · ${t("rtConditionCount").replace("{count}", String(conditions.count()))}` : "";
summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}${conditionNote}`;
const enabledNow = yes("location-enabled", row); let actionText;
row.classList.toggle("is-disabled", !enabledNow); sumState.title = t(enabledNow ? "enabled" : "notEnabled"); sumState.setAttribute("aria-label", sumState.title);
sumId.textContent = id; sumMatch.textContent = internal.checked ? t("locationInternalShort") : t(`locationMatch_${match.value}`); sumMatch.classList.toggle("is-internal", internal.checked);
sumPath.textContent = `${pattern}${conditionNote}`;
previewStatus.hidden = yes("location-enabled", row);
previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}${conditionNote}`;
if (isReturn) {
const status = str("location-response-status", row) || "200", type = str("location-response-type", row) || "text/plain";
previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`;
previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationReturnAction")} ${status}`;
previewValues.rewrite.textContent = "-";
previewValues.cache.textContent = t("notEnabled");
} else if (isRedirect) {
const status = str("location-redirect-status", row) || "302", target = str("location-redirect-target", row) || "-", capture = str("location-redirect-pattern", row);
previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`;
previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationRedirectAction")} ${status} → ${target}`;
previewValues.rewrite.textContent = capture || "-";
previewValues.cache.textContent = t("notEnabled");
} else {
if (isWeb) {
const selected = webService.selectedOptions?.[0]?.textContent || t("webServiceSelect");
previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`;
previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`; actionText = `${t("locationWebServerShort")} → ${selected}`;
previewValues.cache.textContent = t("notEnabled");
} else {
const selected = backend.value === LOCATION_GROUP ? `${t("locationBackendGroup")} (${[...groupSelected].join(", ") || "-"})` : backend.selectedOptions?.[0]?.textContent || t("locationPool");
const algorithmLabel = ownBalancing.checked && !balancing.hidden ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : "";
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`;
const shortTarget = backend.value === LOCATION_GROUP ? [...groupSelected].join(", ") || "-" : selected;
const algorithmLabel = ownBalancing.checked && balancingAvailable ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : "";
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`; actionText = `${t("locationProxyShort")} → ${shortTarget}`;
previewValues.cache.textContent = t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit");
}
const rewriteLabels = { preserve: "locationRewritePreserve", strip_prefix: "locationRewriteStrip", replace_prefix: "locationRewriteReplace", regex: "locationRewriteRegex" };
@@ -628,21 +717,40 @@ function locationsEditor(parent, values, onChange = changed) {
const countryMode = str("location-country-mode", row); if (countryMode !== "off") accessParts.push(`${t("locationCountryMode")}: ${t(countryMode === "allow" ? "vhCountryAllow" : "vhCountryBlock")} ${lines(str("location-country-list", row)).join(", ")}`);
if (yes("acl-use", row)) accessParts.push(t("locationPreviewCustomAcl"));
previewValues.access.textContent = accessParts.length ? accessParts.join(" · ") : t("locationPreviewVhostAcl");
let headerCount = 0;
try {
const headerValue = editor.read(), requestRules = headerValue.request?.length || 0, responseRules = headerValue.response?.length || 0;
previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`;
previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`; headerCount = requestRules + responseRules;
} catch { previewValues.headers.textContent = t("headersInvalid"); }
// Row summary, headline and option tab states.
sumAction.textContent = actionText || "";
const fallbackTarget = str("location-error-target", row), fallbackStatuses = str("location-error-statuses", row).replace(/\s+/g, "");
const visualRules = policyBody.querySelector(".policy-visual:not([hidden]) .policy-rules"); if (visualRules) policyCount = visualRules.querySelectorAll(":scope > .policy-rule").length;
const cacheLabel = isProxy && !conditional ? t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit") : "-";
const ownLb = isProxy && balancingAvailable && (ownBalancing.checked || isGroup);
const states = { access: accessParts.length ? String(accessParts.length) : "", headers: headerCount ? String(headerCount) : "", cache: isProxy && cache.value ? cacheLabel : "", errors: fallbackTarget ? `@${fallbackTarget}` : "", backend: isGroup ? t("locationChipGroup").replace("{count}", String(groupSelected.size)) : ownLb ? t("locationChipBalancing") : "", policy: policyCount ? String(policyCount) : "" };
for (const [name, item] of tabs) { item.state.textContent = states[name] ? ` · ${states[name]}` : ""; item.tab.classList.toggle("is-set", Boolean(states[name])); }
const chips = [];
if (accessParts.length) chips.push(t("locationTabAccess"));
if (headerCount) chips.push(`${t("locationTabHeaders")} ${headerCount}`);
if (isProxy && !conditional && cache.value) chips.push(`Cache: ${cacheLabel}`);
if (states.backend) chips.push(states.backend);
if (policyCount) chips.push(`${t("policyTitle")} ${policyCount}`);
sumChips.replaceChildren(...chips.map(label => el("span", label, "loc-chip")));
if (fallbackTarget) { const chip = el("span", `${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}`, "loc-chip is-fallback"); sumChips.append(chip); }
headline.textContent = `${internal.checked ? `@${id} (${t("locationInternalShort")})` : pattern}${conditionNote} → ${actionText || "-"}${fallbackTarget ? ` · ${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}` : ""}${enabledNow ? "" : ` · ${t("notEnabled")}`}`;
};
row.addEventListener("input", () => { syncUi(); sync(); }); row.addEventListener("change", () => { syncUi(); sync(); });
selectTab(value.backend_ids?.length || value.load_balancing ? "backend" : "access");
rows.append(row); syncUi();
}
for (const value of values) add(value);
for (const value of values) add(value, false, false);
const bottom = el("div", undefined, "vh-wide location-toolbar location-toolbar-bottom"); bottom.append(button("locationAdd", () => { add(); sync(); }, "primary")); parent.append(bottom);
const refreshMembers = () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); for (const row of rows.children) row.refreshBalancing?.(); };
form.querySelector(".vh-members").addEventListener("input", refreshMembers); form.querySelector(".vh-members").addEventListener("change", refreshMembers);
readRows.set = data => {
validateLocations(data); const previous = [...rows.childNodes]; reloading = true;
try { rows.replaceChildren(); for (const value of data) add(value); readRows(); tester?.run(); }
try { rows.replaceChildren(); for (const value of data) add(value, false, false); renumber(); readRows(); tester?.run(); }
catch (error) { rows.replaceChildren(...previous); throw error; }
finally { reloading = false; }
};
+3 -3
View File
@@ -365,9 +365,9 @@ function load(value = defaults(), migrationIds = [], show = true) {
field(uaBlockingFields, "ua-block-patterns", "vhUaBlockPatterns", (uaBlock.patterns || []).join("\n"), "textarea", { rows: 4, maxLength: 32768 });
note(uaBlockingFields, "vhUaBlockHelp");
g = group("vhLocations");
field(g, "main-error-target", "vhErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
field(g, "main-error-statuses", "vhErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 });
note(g, "vhErrorFallbackHelp");
const fallbackFields = subsection(g, "vhErrorFallbackSection");
errorFallbackFields(fallbackFields, "main-error", value.error_fallback, { target: "vhErrorFallbackTarget", statuses: "vhErrorFallbackStatuses" });
note(fallbackFields, "vhErrorFallbackHelp");
const pathsJson = jsonDrawer(g, { name: "paths", titleKey: "vhLocationsJson", helpKey: "vhLocationsJsonHelp", value: value.routes || [], maxLength: 131072, validate: validateLocations, apply: data => locationsReader.set(data) });
locationsReader = locationsEditor(g, value.routes || [], () => { changed(); pathsJson.refresh(); });
g.append(pathsJson.node);
+52 -12
View File
@@ -17,7 +17,7 @@ use http::{
use http_body_util::BodyExt;
use std::{collections::BTreeMap, io, path::Path, str::FromStr};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter},
sync::{mpsc, OwnedSemaphorePermit},
time::Instant,
};
@@ -31,6 +31,13 @@ pub(super) const FCGI_STDOUT: u8 = 6;
const FCGI_STDERR: u8 = 7;
const FCGI_RESPONDER: u16 = 1;
const FCGI_REQUEST_ID: u16 = 1;
const FCGI_HEADER_LEN: usize = 8;
/// Request records (BEGIN, PARAMS, STDIN) are coalesced into a few socket writes.
const FASTCGI_WRITE_BUFFER_BYTES: usize = 16 * 1024;
/// Response records are read through one buffer instead of 2-3 reads per record.
const FASTCGI_READ_BUFFER_BYTES: usize = 32 * 1024;
/// Already-received STDOUT records are merged into one body chunk up to this size.
const FASTCGI_BODY_CHUNK_BYTES: usize = 64 * 1024;
pub(super) trait FastCgiIo: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T> FastCgiIo for T where T: AsyncRead + AsyncWrite + Unpin + Send {}
@@ -40,11 +47,27 @@ async fn connect_fastcgi(endpoint: &FastCgiEndpoint) -> io::Result<Box<dyn FastC
#[cfg(unix)]
FastCgiEndpoint::Unix(path) => Ok(Box::new(tokio::net::UnixStream::connect(path).await?)),
FastCgiEndpoint::Tcp(address) => {
Ok(Box::new(tokio::net::TcpStream::connect(address).await?))
let stream = tokio::net::TcpStream::connect(address).await?;
// FastCGI is a request/response exchange of small records; Nagle's
// algorithm would only delay the final record of a request.
stream.set_nodelay(true)?;
Ok(Box::new(stream))
}
}
}
/// Type of the next FastCGI record when it is already complete in the read
/// buffer, so it can be consumed without waiting for the socket.
fn buffered_fcgi_record(io: &BufReader<Box<dyn FastCgiIo>>) -> Option<u8> {
let buffer = io.buffer();
if buffer.len() < FCGI_HEADER_LEN {
return None;
}
let length = u16::from_be_bytes([buffer[4], buffer[5]]) as usize;
let padding = buffer[6] as usize;
(buffer.len() >= FCGI_HEADER_LEN + length + padding).then_some(buffer[1])
}
pub(super) async fn write_fcgi_record(
io: &mut dyn FastCgiIo,
record_type: u8,
@@ -338,7 +361,7 @@ pub(super) fn parse_cgi_headers(value: &[u8]) -> Result<(StatusCode, HeaderMap)>
}
async fn drain_fastcgi_body(
mut io: Box<dyn FastCgiIo>,
mut io: BufReader<Box<dyn FastCgiIo>>,
deadline: Instant,
tx: mpsc::Sender<io::Result<Bytes>>,
initial: Vec<u8>,
@@ -347,18 +370,29 @@ async fn drain_fastcgi_body(
metrics: std::sync::Arc<crate::web_server::metrics::PhpMetrics>,
_permit: OwnedSemaphorePermit,
) {
if send_body && !initial.is_empty() && tx.send(Ok(Bytes::from(initial))).await.is_err() {
return;
}
// Body bytes waiting to be sent. Records that have already arrived are
// merged into one chunk; nothing is held back while waiting for the socket,
// so flush() from the application still reaches the client immediately.
let mut pending = if send_body { initial } else { Vec::new() };
let mut stderr = Vec::new();
loop {
match read_fcgi_record(io.as_mut(), deadline).await {
if !pending.is_empty()
&& (pending.len() >= FASTCGI_BODY_CHUNK_BYTES || buffered_fcgi_record(&io).is_none())
&& tx
.send(Ok(Bytes::from(std::mem::take(&mut pending))))
.await
.is_err()
{
return;
}
match read_fcgi_record(&mut io, deadline).await {
Ok((FCGI_STDOUT, content)) => {
if send_body
&& !content.is_empty()
&& tx.send(Ok(Bytes::from(content))).await.is_err()
{
return;
if send_body && !content.is_empty() {
if pending.is_empty() {
pending = content;
} else {
pending.extend_from_slice(&content);
}
}
}
Ok((FCGI_STDERR, content)) => {
@@ -370,12 +404,18 @@ async fn drain_fastcgi_body(
Err(error) => {
metrics.failure(8);
if send_body {
if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() {
return;
}
let _ = tx.send(Err(error)).await;
}
return;
}
}
}
if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() {
return;
}
if !stderr.is_empty() {
tracing::warn!(
stderr = %String::from_utf8_lossy(&stderr),
+16 -8
View File
@@ -68,7 +68,7 @@ async fn php_response_inner(
return response;
}
};
let mut io =
let io =
match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await {
Ok(Ok(io)) => io,
Ok(Err(error)) => {
@@ -100,16 +100,22 @@ async fn php_response_inner(
}
};
let deadline = Instant::now() + php.request_timeout;
let mut writer = BufWriter::with_capacity(FASTCGI_WRITE_BUFFER_BYTES, io);
let exchange = async {
let mut begin = [0u8; 8];
begin[..2].copy_from_slice(&FCGI_RESPONDER.to_be_bytes());
write_fcgi_record(io.as_mut(), FCGI_BEGIN_REQUEST, &begin).await?;
write_fcgi_record(&mut writer, FCGI_BEGIN_REQUEST, &begin).await?;
for chunk in params.chunks(u16::MAX as usize) {
write_fcgi_record(io.as_mut(), FCGI_PARAMS, chunk).await?;
write_fcgi_record(&mut writer, FCGI_PARAMS, chunk).await?;
}
write_fcgi_record(io.as_mut(), FCGI_PARAMS, &[]).await?;
write_fcgi_record(&mut writer, FCGI_PARAMS, &[]).await?;
let mut body = body;
// Requests without a body go out in one write. With a body, deliver the
// parameters first so the responder can start while the client uploads.
if !http_body::Body::is_end_stream(&body) {
writer.flush().await?;
}
let mut body_bytes = 0u64;
while let Some(frame) = body.frame().await {
let frame = frame.map_err(|error| {
@@ -121,12 +127,12 @@ async fn php_response_inner(
return Err(FastCgiRequestWriteError::BodyTooLarge);
}
for chunk in data.chunks(u16::MAX as usize) {
write_fcgi_record(io.as_mut(), FCGI_STDIN, chunk).await?;
write_fcgi_record(&mut writer, FCGI_STDIN, chunk).await?;
}
}
}
write_fcgi_record(io.as_mut(), FCGI_STDIN, &[]).await?;
io.flush().await?;
write_fcgi_record(&mut writer, FCGI_STDIN, &[]).await?;
writer.flush().await?;
Ok::<(), FastCgiRequestWriteError>(())
};
match tokio::time::timeout_at(deadline, exchange).await {
@@ -145,10 +151,12 @@ async fn php_response_inner(
}
}
// The request is fully flushed; from here on the connection is only read.
let mut io = BufReader::with_capacity(FASTCGI_READ_BUFFER_BYTES, writer.into_inner());
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let (status, response_headers, initial_body) = loop {
let record = read_fcgi_record(io.as_mut(), deadline).await;
let record = read_fcgi_record(&mut io, deadline).await;
let (record_type, content) = match record {
Ok(value) => value,
Err(error) if error.kind() == io::ErrorKind::TimedOut => {
+185
View File
@@ -3250,3 +3250,188 @@ async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query()
assert_eq!(params["QUERY_STRING"], "404");
assert_eq!(params["REQUEST_URI"], "/error.php?404");
}
/// One encoded FastCGI record (request id 1), as a responder writes it.
fn fcgi_record_bytes(kind: u8, content: &[u8]) -> Vec<u8> {
let padding = (8 - content.len() % 8) % 8;
let mut record = vec![1, kind, 0, 1];
record.extend_from_slice(&(content.len() as u16).to_be_bytes());
record.extend_from_slice(&[padding as u8, 0]);
record.extend_from_slice(content);
record.resize(record.len() + padding, 0);
record
}
fn php_fixture_service(root: &Path, address: std::net::SocketAddr) -> CompiledService {
std::fs::write(root.join("index.php"), b"<?php echo 'SOURCE';").unwrap();
let mut configured = Service {
id: "php-buffered".into(),
name: "PHP buffered".into(),
document_root: root.to_path_buf(),
index: vec!["index.php".into()],
php: Php {
enabled: true,
endpoint: format!("tcp:{address}"),
connect_timeout_ms: 500,
request_timeout_ms: 5_000,
max_concurrent_requests: 2,
..Default::default()
},
..Default::default()
};
configured.validate().unwrap();
configured.compile().unwrap()
}
/// Reads one complete FastCGI request and returns (params, stdin).
async fn read_fastcgi_request(stream: &mut tokio::net::TcpStream) -> (Vec<u8>, Vec<u8>) {
let deadline = Instant::now() + Duration::from_secs(5);
let (mut params, mut stdin) = (Vec::new(), Vec::new());
loop {
let (kind, content) = read_fcgi_record(stream, deadline).await.unwrap();
match kind {
FCGI_PARAMS => params.extend_from_slice(&content),
FCGI_STDIN if content.is_empty() => return (params, stdin),
FCGI_STDIN => stdin.extend_from_slice(&content),
_ => {}
}
}
}
#[tokio::test]
async fn fastcgi_buffered_exchange_keeps_many_records_stderr_and_body_intact() {
const FCGI_STDERR: u8 = 7;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let upload: Vec<u8> = (0..200_000u32).map(|value| (value % 251) as u8).collect();
let expected_upload = upload.clone();
let (seen_tx, seen_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let (params, stdin) = read_fastcgi_request(&mut stream).await;
let _ = seen_tx.send((decode_fastcgi_params(&params), stdin));
// Headers split across records, interleaved STDERR, then many small
// body records written in one burst (as PHP output buffers do).
let mut burst = Vec::new();
for record in [
&b"Status: 200 OK\r\nContent-"[..],
&b"Type: text/plain\r\n\r\nA"[..],
] {
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, record));
}
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDERR, b"notice"));
for index in 0..3000u32 {
burst.extend_from_slice(&fcgi_record_bytes(
FCGI_STDOUT,
format!("{index:05}|").as_bytes(),
));
}
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, &[]));
burst.extend_from_slice(&fcgi_record_bytes(FCGI_END_REQUEST, &[0u8; 8]));
stream.write_all(&burst).await.unwrap();
stream.flush().await.unwrap();
});
let tmp = TempDir::new().unwrap();
let service = php_fixture_service(tmp.path(), address);
let mut post = request(Method::POST, "/index.php?x=1");
post.headers_mut()
.insert(CONTENT_LENGTH, upload.len().to_string().parse().unwrap());
let response = serve_body_request(&service, &post, "/index.php", Body::from(upload)).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()[CONTENT_TYPE], "text/plain");
let body = response.into_body().collect().await.unwrap().to_bytes();
let mut expected = b"A".to_vec();
for index in 0..3000u32 {
expected.extend_from_slice(format!("{index:05}|").as_bytes());
}
assert_eq!(body.as_ref(), expected.as_slice());
let (params, stdin) = seen_rx.await.unwrap();
assert_eq!(params["REQUEST_METHOD"], "POST");
assert_eq!(params["QUERY_STRING"], "x=1");
assert_eq!(stdin, expected_upload);
}
#[tokio::test]
async fn fastcgi_streamed_output_is_not_held_back_for_coalescing() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
read_fastcgi_request(&mut stream).await;
write_fcgi_record(
&mut stream,
FCGI_STDOUT,
b"Content-Type: text/plain\r\n\r\nfirst",
)
.await
.unwrap();
stream.flush().await.unwrap();
// The rest is produced only after the client has seen the first chunk,
// like an application calling flush() between slow steps.
release_rx.await.unwrap();
write_fcgi_record(&mut stream, FCGI_STDOUT, b"-second")
.await
.unwrap();
write_fcgi_record(&mut stream, FCGI_STDOUT, &[])
.await
.unwrap();
write_fcgi_record(&mut stream, FCGI_END_REQUEST, &[0u8; 8])
.await
.unwrap();
stream.flush().await.unwrap();
});
let tmp = TempDir::new().unwrap();
let service = php_fixture_service(tmp.path(), address);
let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await;
assert_eq!(response.status(), StatusCode::OK);
let mut body = response.into_body();
let first = tokio::time::timeout(Duration::from_secs(2), body.frame())
.await
.expect("first chunk must be delivered before more output exists")
.unwrap()
.unwrap()
.into_data()
.unwrap();
assert_eq!(first.as_ref(), b"first");
release_tx.send(()).unwrap();
let rest = body.collect().await.unwrap().to_bytes();
assert_eq!(rest.as_ref(), b"-second");
}
#[tokio::test]
async fn fastcgi_truncated_stream_delivers_received_bytes_then_errors() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
read_fastcgi_request(&mut stream).await;
let mut burst = fcgi_record_bytes(FCGI_STDOUT, b"Content-Type: text/plain\r\n\r\nkept");
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, b"-also"));
stream.write_all(&burst).await.unwrap();
// Half a record header, then the responder disappears.
stream.write_all(&[1, FCGI_STDOUT, 0]).await.unwrap();
stream.flush().await.unwrap();
});
let tmp = TempDir::new().unwrap();
let service = php_fixture_service(tmp.path(), address);
let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await;
assert_eq!(response.status(), StatusCode::OK);
let mut body = response.into_body();
let mut received = Vec::new();
let mut failed = false;
while let Some(frame) = body.frame().await {
match frame {
Ok(frame) => received.extend_from_slice(&frame.into_data().unwrap()),
Err(_) => {
failed = true;
break;
}
}
}
assert_eq!(received, b"kept-also");
assert!(
failed,
"a truncated FastCGI stream must not look like a complete body"
);
}