This commit is contained in:
Mateusz Gruszczyński committed 2026-11-26 08:50:30 +01:00
1 parent 167861fc16
commit aa0a271a1c
38 files changed
+3642 -1058

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.0",
"version": "0.42.1",
"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
View File
@@ -93,6 +93,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/integrations.js"),
include_str!("web/acl-picker.js"),
include_str!("web/cache-rules.js"),
include_str!("web/policy-presets.js"),
include_str!("web/policy.js"),
admin_vhosts_javascript(),
include_str!("web/web-server-profiles.js"),
+1 -2
View File
@@ -1,4 +1,3 @@
:root {
color-scheme: dark;
--bg: #131615;
@@ -709,4 +708,4 @@ html[data-corner-style=extra] {
--rp-radius-surface: 18px;
--rp-radius-control: 12px;
--rp-progress-radius: 999px;
}
}
+2 -10
View File
@@ -1,4 +1,3 @@
* {
box-sizing: border-box;
scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
@@ -493,9 +492,6 @@ button.is-saving {
font-size: 11px;
}
/* The 13px top margin lines a single toggle up with labelled fields above
it; stacked toggles only need a small step, and toggles laid out in rows
or editor grids use the container gap instead. */
.check+.check {
margin-top: 6px !important;
}
@@ -1152,11 +1148,6 @@ html[data-dashboard-density=compact] #panel-overview .dashboard-overview-grid>.c
transform: translateY(-1px);
}
/* On/off switch: an ordinary checkbox with class "switch". Used for settings
that turn a feature or section on; option lists, row selection and risk
confirmations stay plain checkboxes. The account preference
switch_controls=false (html[data-switch-controls="false"]) keeps the plain
checkbox look. */
html:not([data-switch-controls="false"]) input[type=checkbox].switch {
--rp-switch-h: calc(var(--ui-check-size) + 1px);
--rp-switch-w: calc(var(--rp-switch-h) * 1.875);
@@ -1669,10 +1660,11 @@ html[data-table-density=ultra] :is(table th, table td) {
.path-permissions-actions {
margin-top: 10px;
}
html[data-interface-icons="true"] :is(button, a, summary)>svg.ui-icon {
display: inline-block;
position: static;
flex: 0 0 auto;
max-width: none;
overflow: visible;
}
}
+21 -7
View File
@@ -1,4 +1,3 @@
html.app-loading .shell {
visibility: hidden;
pointer-events: none;
@@ -195,18 +194,31 @@ nav {
}
.app-health-button.is-checking,
.app-health-summary.is-checking { color: var(--muted); }
.app-health-summary.is-checking {
color: var(--muted);
}
.app-health-button.is-ok,
.app-health-summary.is-ok,
.app-health-check.is-ok { color: var(--green); }
.app-health-check.is-ok {
color: var(--green);
}
.app-health-button.is-warning,
.app-health-summary.is-warning,
.app-health-check.is-warning { color: var(--notice-text); }
.app-health-check.is-warning {
color: var(--notice-text);
}
.app-health-button.is-error,
.app-health-summary.is-error,
.app-health-check.is-error { color: var(--red); }
.app-health-check.is-error {
color: var(--red);
}
.app-health-button:hover { opacity: .82; }
.app-health-button:hover {
opacity: .82;
}
.nav {
display: flex;
@@ -840,6 +852,7 @@ main {
visibility: visible;
}
}
.brand-mark .brand-letter {
font: inherit;
color: inherit;
@@ -1035,6 +1048,7 @@ a.brand>.brand-mark[data-logo-effect="wobble"]>span {
}
@media (min-width: 851px) {
html.sidebar-collapsed .shell,
html.sidebar-peek .shell {
grid-template-columns: 58px minmax(0, 1fr);
@@ -1113,4 +1127,4 @@ a.brand>.brand-mark[data-logo-effect="wobble"]>span {
.sidebar-collapse {
display: none;
}
}
}
-3
View File
@@ -3840,9 +3840,6 @@ html[data-table-density=ultra] .bo-traffic-text {
font: 11px var(--mono);
}
/* Keep the ordinary table layout when the option is disabled. In responsive
mode only the three sparkline columns consume surplus table width. Native
table sizing still preserves intrinsic text widths and horizontal scrolling. */
.bo-table.bo-responsive-charts {
min-width: 0;
}
+112 -19
View File
@@ -80,9 +80,6 @@
gap: 7px;
}
/* Switches never share a row with ordinary fields: a field after a switch
and a switch after a field each start a new row. Consecutive switches
still sit side by side (for example TLS 1.2 / TLS 1.3). */
.vh-grid>.check+:not(.check),
.vh-grid>:not(.check)+.check {
grid-column-start: 1;
@@ -97,26 +94,32 @@
margin-top: 6px !important;
}
/* Fields in one row line up: each field spans a caption row and a control
row of the editor grid, and a plain caption + control field uses those
rows as a subgrid, so a caption that wraps to more lines makes the whole
caption row taller and every control in the row still starts on the same
line. Multi-line text areas take the whole row instead of a narrow column. */
:is(.vh-grid>.vh-field, .field-grid>label:not([class])) {
:is(.vh-grid, .field-grid)>:is(.vh-field, label:not([class]), .auto-id-field) {
grid-row: span 2;
}
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child) {
:is(.vh-grid, .field-grid)>:is(.vh-field, label:not([class]), .auto-id-field):is(:has(>:nth-child(2):last-child), .auto-id-field.is-compact) {
display: grid;
grid-template-rows: subgrid;
row-gap: 4px;
align-content: start;
}
:is(.vh-grid>.vh-field, .field-grid>label:not([class])):has(>:nth-child(2):last-child)>:first-child {
:is(.vh-grid, .field-grid)>:is(.vh-field, label:not([class]), .auto-id-field):is(:has(>:nth-child(2):last-child), .auto-id-field.is-compact)>:first-child {
align-self: end;
}
:is(.vh-grid, .field-grid):has(>.auto-id-field:not(.is-compact))>:is(.vh-field, label:not([class]), .auto-id-field) {
grid-template-rows: none;
}
:is(.vh-grid, .field-grid)>.auto-id-field:not(.is-compact) {
display: grid;
align-content: start;
gap: 4px;
}
.vh-grid>.vh-field:has(>textarea) {
grid-column: 1 / -1;
}
@@ -144,6 +147,78 @@
font-family: var(--mono);
}
.vh-json-editor {
min-width: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
background: var(--panel2);
}
.vh-json-editor>summary {
padding: 10px 12px;
cursor: pointer;
font-size: 12px;
font-weight: 600;
}
.vh-json-status {
display: inline-block;
margin-left: 10px;
color: var(--muted);
font-size: 11px;
font-weight: 400;
}
.vh-json-editor.has-json-draft {
border-color: var(--accent);
}
.vh-json-editor.has-json-draft .vh-json-status {
color: var(--accent);
}
.vh-json-body {
padding: 12px;
border-top: 1px solid var(--line);
gap: 12px;
}
.vh-json-body>textarea[hidden] {
display: none !important;
}
.vh-json-body>.vh-field {
grid-column: 1 / -1;
}
.vh-json-source {
min-height: 180px;
line-height: 1.5;
tab-size: 2;
}
.vh-json-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.vh-json-toolbar>button {
width: auto;
margin: 0;
}
.vh-json-message {
margin: 0;
overflow-wrap: anywhere;
color: var(--green);
}
.vh-json-message.is-error {
color: var(--red);
}
.vh-check {
font-size: 11px;
min-height: 28px;
@@ -407,7 +482,7 @@
display: block;
}
.vh-form .form-actions {
.vh-form>.form-actions {
position: sticky;
bottom: -14px;
background: var(--panel);
@@ -437,10 +512,11 @@
}
.listener-choices {
flex-wrap: wrap;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr));
align-items: stretch;
gap: 8px;
min-width: 0;
}
.listener-choices>.fine {
@@ -455,11 +531,21 @@
border-radius: var(--rp-radius-control, 4px);
font-size: 11px;
display: flex;
min-width: 0;
min-height: 44px;
align-items: center;
margin: 0;
}
.listener-choices>.check {
margin: 0 !important;
}
.listener-choices>.check>span {
min-width: 0;
overflow-wrap: anywhere;
}
dialog.vhost-dialog,
dialog.audit-dialog,
dialog.config-history-dialog,
@@ -1083,6 +1169,16 @@ p,
min-width: 0;
}
.redirect-rule-actions {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
padding-top: 8px;
border-top: 1px solid var(--line);
}
.redirect-card .vhost-detail-strip {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
@@ -2170,7 +2266,7 @@ h2+.fine {
justify-self: start;
}
}
/* Load-balancing editor and distribution simulator (vhost and location). */
.lb-editor {
display: grid;
gap: 10px;
@@ -2323,7 +2419,6 @@ h2+.fine {
padding: 8px 10px;
}
/* Location conditions and routing tester. */
.rt-conditions {
display: grid;
gap: 8px;
@@ -2417,7 +2512,6 @@ h2+.fine {
font-size: 11px;
}
/* Header value variables and diagnostic header presets. */
.hdr-vars,
.hdr-presets {
display: flex;
@@ -2439,7 +2533,6 @@ h2+.fine {
font: 11px var(--mono);
}
/* Headers tab: live preview, diagnostic cards and compact header rules. */
.hdr-preview {
display: grid;
gap: 10px;
@@ -2614,4 +2707,4 @@ h2+.fine {
.hdr-row.is-invalid .hdr-row-hint {
color: var(--red);
}
}
+238 -49
View File
@@ -238,8 +238,6 @@
min-width: 0;
gap: 8px;
padding: 10px 12px;
/* Many service cards: skip layout and paint of cards outside the
viewport; the browser remembers each card's last rendered size. */
content-visibility: auto;
contain-intrinsic-size: auto 320px;
}
@@ -2310,6 +2308,28 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
align-items: center;
}
#logging-settings-card .logging-format-actions {
--logging-action-height: max(var(--button-min-height), var(--ui-field-min-height));
margin-block: 12px;
}
#logging-settings-card .logging-format-actions>label {
display: grid;
gap: 6px;
min-width: 0;
margin: 0;
}
#logging-settings-card .logging-builder-action {
gap: 6px;
}
#logging-settings-card .logging-format-actions :is(select, button) {
height: var(--logging-action-height);
min-height: var(--logging-action-height);
padding-block: 0;
}
.global-policy-summary {
display: flex;
flex-wrap: wrap;
@@ -2427,6 +2447,10 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
border-top: 1px solid var(--line);
}
.listener-card-body>.vh-grid>.check {
margin: 0 !important;
}
.listener-card.is-collapsed>.listener-card-body {
display: none;
}
@@ -2450,8 +2474,10 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rules {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 10px;
margin-top: 8px;
min-width: 0;
}
.cache-rules-toolbar {
@@ -2459,20 +2485,19 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
flex-wrap: wrap;
gap: 8px;
align-items: center;
min-width: 0;
}
.cache-rules-toolbar>.cache-rules-templates {
width: auto;
min-width: 220px;
min-width: min(220px, 100%);
max-width: 100%;
}
.cache-rules-toolbar>.primary {
margin-left: auto;
}
/* Searchable, grouped one-click cache/VCL rule library. The native select
above remains for quick keyboard access and existing editor workflows. */
.cache-rule-catalog {
display: grid;
gap: 10px;
@@ -2485,9 +2510,13 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rule-catalog>h4,
.cache-rule-catalog>p,
.cache-rule-catalog-card p { margin: 0; }
.cache-rule-catalog-card p {
margin: 0;
}
.cache-rule-catalog-search { width: min(100%, 480px); }
.cache-rule-catalog-search {
width: min(100%, 480px);
}
.cache-rule-catalog-groups {
max-height: 540px;
@@ -2497,8 +2526,16 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
padding-right: 4px;
}
.cache-rule-catalog-group { display: grid; gap: 7px; min-width: 0; }
.cache-rule-catalog-group>h5 { margin: 0; font-size: 13px; }
.cache-rule-catalog-group {
display: grid;
gap: 7px;
min-width: 0;
}
.cache-rule-catalog-group>h5 {
margin: 0;
font-size: 13px;
}
.cache-rule-catalog-card {
display: flex;
@@ -2519,14 +2556,63 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
overflow-wrap: anywhere;
}
.cache-rule-catalog-card-copy strong { font-size: 13px; line-height: 1.4; }
.cache-rule-catalog-card-copy p { font-size: 12px; }
.cache-rule-catalog-review { color: var(--accent); font-size: 11px; }
.cache-rule-catalog-card>button { flex: 0 0 auto; }
.cache-rule-catalog-card-copy strong {
font-size: 13px;
line-height: 1.4;
}
.cache-rule-catalog-card-copy p {
font-size: 12px;
}
.cache-rule-catalog-review {
color: var(--accent);
font-size: 11px;
}
.cache-rule-catalog-card>button {
flex: 0 0 auto;
}
@media (max-width: 540px) {
.cache-rule-catalog { padding: 9px; }
.cache-rule-catalog-card { align-items: flex-start; }
.cache-rules-toolbar {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: stretch;
}
.cache-rules-toolbar>.cache-rules-templates {
grid-column: 1/-1;
width: 100%;
}
.cache-rules-toolbar>button {
min-width: 0;
width: 100%;
white-space: normal;
}
.cache-rules-toolbar>.primary {
margin-left: 0;
}
.cache-rule-head {
flex-wrap: wrap;
}
.cache-rule-head>.cache-rule-actions {
flex: 1 0 100%;
justify-content: flex-end;
gap: 6px;
}
.cache-rule-catalog {
padding: 9px;
}
.cache-rule-catalog-card {
align-items: flex-start;
}
}
.cache-rules-notices {
@@ -2545,6 +2631,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rules-list {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 6px;
}
@@ -2627,6 +2714,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rule-body {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 12px;
padding: 10px 12px 12px;
border-top: 1px solid var(--line);
@@ -2669,6 +2757,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rule-rows {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 6px;
}
@@ -2681,7 +2770,8 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.cache-rule-row>select {
width: auto;
min-width: 150px;
min-width: min(150px, 100%);
max-width: 100%;
}
.cache-rule-row>.cache-rule-name {
@@ -2759,8 +2849,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
font-size: 13px;
}
/* Shared compact rule tester (global Cache, Vhosts and Docker vhosts).
Keep controls aligned without the vhost editor's two-row subgrid. */
.cache-rules-vhost-links {
display: flex;
align-items: center;
@@ -2912,7 +3000,9 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
min-width: 0;
}
.cache-rules-tester-result:empty { display: none; }
.cache-rules-tester-result:empty {
display: none;
}
.cache-rules-result-line {
display: grid;
@@ -2924,19 +3014,48 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
font-size: 12px;
}
.cache-rules-result-line>strong { min-width: 0; }
.cache-rules-result-line>strong {
min-width: 0;
}
@container (max-width: 550px) {
.cache-rules-tester-body { padding: 9px; }
.cache-rules-tester-pane { padding: 9px; }
.cache-rules-tester-request-grid { grid-template-columns: minmax(105px, 1fr) minmax(0, 1fr); }
.cache-rules-tester-body {
padding: 9px;
}
.cache-rules-tester-pane {
padding: 9px;
}
.cache-rules-tester-request-grid {
grid-template-columns: minmax(105px, 1fr) minmax(0, 1fr);
}
.cache-rules-tester-request-grid>.is-url,
.cache-rules-tester-request-grid>.is-vhost { grid-column: 1 / -1; }
.cache-rules-tester-request-grid>.is-ip { grid-column: span 1; }
.cache-rules-tester-response-grid { grid-template-columns: minmax(0, 1fr); }
.cache-rules-tester-response-grid>.is-status { max-width: 170px; }
.cache-rules-tester-response-grid>.is-response-headers { grid-column: 1 / -1; }
.cache-rules-result-line { grid-template-columns: minmax(0, 1fr); gap: 3px; }
.cache-rules-tester-request-grid>.is-vhost {
grid-column: 1 / -1;
}
.cache-rules-tester-request-grid>.is-ip {
grid-column: span 1;
}
.cache-rules-tester-response-grid {
grid-template-columns: minmax(0, 1fr);
}
.cache-rules-tester-response-grid>.is-status {
max-width: 170px;
}
.cache-rules-tester-response-grid>.is-response-headers {
grid-column: 1 / -1;
}
.cache-rules-result-line {
grid-template-columns: minmax(0, 1fr);
gap: 3px;
}
}
.cache-rules-result-line.is-ok>strong {
@@ -3438,6 +3557,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
gap: var(--ui-gap-sm, 8px);
padding: 0 8px 8px;
}
.docker-security-grid,
.docker-diagnostics-grid {
display: grid;
@@ -3551,6 +3671,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
}
@media (max-width: 900px) {
.docker-security-grid,
.docker-diagnostics-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -3613,7 +3734,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
}
}
/* Contextual cache / VCL help in Settings -> Cache. */
.cache-guide-heading-actions {
display: flex;
flex-wrap: wrap;
@@ -3621,44 +3741,86 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
gap: 8px;
margin-left: auto;
}
#cache-form .cache-guide-trigger { width: auto; }
#cache-form [data-cache-settings-page=rules]>.cache-guide-trigger { margin-left: 10px; }
#cache-form .cache-guide-trigger {
width: auto;
}
#cache-form [data-cache-settings-page=rules]>.cache-guide-trigger {
margin-left: 10px;
}
.cache-vcl-guide-dialog {
width: calc(min(980px, 100vw - 24px) / var(--ui-scale, 1));
max-height: calc((100dvh - 28px) / var(--ui-scale, 1));
overflow: hidden;
}
.cache-guide-dialog-heading { justify-content: space-between; }
.cache-guide-dialog-heading h2 { margin: 3px 0 0; }
.cache-guide-dialog-heading {
justify-content: space-between;
}
.cache-guide-dialog-heading h2 {
margin: 3px 0 0;
}
.cache-guide-content {
overflow-y: auto;
max-height: calc((100dvh - 110px) / var(--ui-scale, 1));
padding: 14px;
}
.cache-guide-content>.fine { margin: 0 0 12px; }
.cache-guide-content>.fine {
margin: 0 0 12px;
}
.cache-guide-current {
border: 1px solid var(--line);
background: var(--panel2);
padding: 12px;
margin-bottom: 12px;
}
.cache-guide-current-pills { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 8px; }
.cache-guide-current p { margin: 5px 0 0; }
.cache-guide-current-pills {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-bottom: 8px;
}
.cache-guide-current p {
margin: 5px 0 0;
}
.cache-guide-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: stretch;
gap: 10px;
}
.cache-guide-card {
min-width: 0;
border: 1px solid var(--line);
background: var(--panel);
padding: 13px;
}
.cache-guide-card h3 { margin: 0 0 8px; font-size: 14px; }
.cache-guide-card p { font-size: 12px; line-height: 1.55; margin: 0; }
.cache-guide-card p+p { margin-top: 9px; }
.cache-guide-card h3 {
margin: 0 0 8px;
font-size: 14px;
}
.cache-guide-card p {
font-size: 12px;
line-height: 1.55;
margin: 0;
}
.cache-guide-card p+p {
margin-top: 9px;
}
.cache-guide-card pre {
margin: 9px 0;
padding: 10px;
@@ -3671,12 +3833,39 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
line-height: 1.5;
tab-size: 2;
}
.cache-guide-card pre code { white-space: pre; }
.cache-guide-import-example { margin-top: 4px; width: auto; }
.cache-guide-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin-top: 13px; }
.cache-guide-footer>.fine { flex: 1 1 100%; margin: 0; }
@media (max-width: 720px) {
.cache-guide-grid { grid-template-columns: minmax(0, 1fr); }
.cache-guide-content { padding: 10px; }
.cache-guide-card { padding: 11px; }
.cache-guide-card pre code {
white-space: pre;
}
.cache-guide-import-example {
margin-top: 4px;
width: auto;
}
.cache-guide-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 14px;
margin-top: 13px;
}
.cache-guide-footer>.fine {
flex: 1 1 100%;
margin: 0;
}
@media (max-width: 720px) {
.cache-guide-grid {
grid-template-columns: minmax(0, 1fr);
}
.cache-guide-content {
padding: 10px;
}
.cache-guide-card {
padding: 11px;
}
}
+465 -43
View File
@@ -9,10 +9,29 @@
gap: 12px;
min-width: 0;
}
.http-policy-editor { width: 100%; margin-top: 10px; }
.http-policy-editor {
width: 100%;
margin-top: 10px;
}
.policy-visual,
.policy-raw {
margin: 0;
padding: 0;
border: 0;
min-inline-size: 0;
}
.http-policy-editor p,
.http-policy-editor h4 { margin: 0; }
.http-policy-editor [hidden] { display: none !important; }
.http-policy-editor h4 {
margin: 0;
}
.http-policy-editor [hidden] {
display: none !important;
}
.policy-toolbar,
.policy-row-controls,
.policy-rule-heading {
@@ -21,17 +40,94 @@
gap: 8px;
align-items: center;
}
.policy-toolbar > button,
.policy-row-controls > button { width: auto; }
.policy-toolbar > [aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.policy-guide { margin-left: auto; }
.policy-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; min-width: 0; }
.policy-wide { grid-column: 1 / -1; }
.policy-field { display: grid; gap: 5px; min-width: 0; color: var(--muted); font-size: 12px; }
.policy-field > :is(input, select, textarea) { min-width: 0; width: 100%; margin: 0; }
.policy-field > textarea { resize: vertical; font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.5; }
.policy-check { display: flex; gap: 8px; align-items: center; }
.policy-check > input { width: auto; flex: 0 0 auto; }
.policy-toolbar>button,
.policy-row-controls>button {
width: auto;
}
.policy-toolbar>[aria-pressed="true"] {
border-color: var(--accent);
color: var(--accent);
}
.policy-add-toolbar {
padding-top: 12px;
border-top: 1px solid var(--line);
}
.policy-add-toolbar>[aria-expanded="true"] {
border-color: var(--accent);
color: var(--accent);
background: var(--panel2);
}
.policy-guide {
margin-left: auto;
}
.policy-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
min-width: 0;
}
.policy-rule-meta {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.policy-wide {
grid-column: 1 / -1;
}
.policy-field {
display: grid;
gap: 5px;
min-width: 0;
color: var(--muted);
font-size: 12px;
}
.policy-field> :is(input, select, textarea) {
min-width: 0;
width: 100%;
margin: 0;
}
.policy-field>textarea {
resize: vertical;
font-family: ui-monospace, monospace;
font-size: 12px;
line-height: 1.5;
}
.policy-check {
display: flex;
gap: 8px;
align-items: center;
}
.policy-check>input {
width: auto;
flex: 0 0 auto;
}
.policy-check>span {
line-height: 1.4;
}
.policy-stop {
display: grid;
gap: 5px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.policy-stop .policy-check {
color: var(--text);
}
.policy-rule {
display: grid;
gap: 14px;
@@ -42,13 +138,31 @@
background: var(--panel2);
border-radius: var(--rp-radius-surface, 0px);
}
.policy-rule.is-disabled { border-left-color: var(--muted); }
.policy-rule.is-disabled .policy-order { color: var(--muted); }
.policy-rule-heading > .policy-field:not(.policy-check) { flex: 1 1 180px; }
.policy-order { color: var(--accent); }
.policy-rule.is-disabled {
border-left-color: var(--muted);
}
.policy-rule.is-disabled .policy-order {
color: var(--muted);
}
.policy-rule-heading>.policy-field:not(.policy-check) {
flex: 1 1 180px;
}
.policy-rule-heading>.policy-field:not(.policy-check)>input {
position: relative;
top: -6px;
}
.policy-order {
color: var(--accent);
}
.policy-action {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(155px, 1fr));
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
align-items: end;
padding: 12px;
@@ -56,12 +170,234 @@
border: 1px solid var(--line);
min-width: 0;
}
.policy-action > .policy-row-controls { grid-column: 1 / -1; justify-content: flex-end; }
.http-policy-editor details { min-width: 0; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); }
.http-policy-editor details > summary { padding: 10px 12px; cursor: pointer; color: var(--text); font-weight: 600; }
.policy-detail-body { padding: 12px; border-top: 1px solid var(--line); }
.policy-rule > button,
.policy-detail-body > button { justify-self: start; }
.policy-action>.policy-row-controls {
grid-column: 1 / -1;
justify-content: flex-end;
}
.policy-action[data-policy-fields="1"],
.policy-action[data-policy-fields="3"] {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.policy-action[data-policy-fields="0"] {
grid-template-columns: minmax(0, 1fr) auto;
}
.policy-action[data-policy-fields="0"]>.policy-row-controls {
grid-column: auto;
}
.http-policy-editor details {
min-width: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0px);
}
.http-policy-editor details>summary {
padding: 10px 12px;
cursor: pointer;
color: var(--text);
font-weight: 600;
}
.policy-detail-body {
padding: 12px;
border-top: 1px solid var(--line);
}
.policy-condition-count {
display: inline-block;
margin-left: 10px;
padding: 2px 6px;
border: 1px solid var(--line);
font-weight: 400;
font-size: 11px;
color: var(--muted);
border-radius: var(--rp-radius-control, 0px);
}
.policy-condition-list {
display: grid;
gap: 8px;
min-width: 0;
}
.policy-condition-join {
color: var(--accent);
font-size: 11px;
font-weight: 700;
letter-spacing: .05em;
}
.policy-condition-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 12px;
align-items: center;
padding: 10px;
background: var(--panel);
border: 1px solid var(--line);
}
.policy-condition-row>code {
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
line-height: 1.5;
}
.policy-condition-row>button {
width: auto;
}
.http-policy-editor .policy-condition-advanced>summary {
font-size: 12px;
font-weight: 400;
color: var(--muted);
}
.policy-condition-builder {
padding: 12px;
border: 1px solid var(--line);
background: var(--panel);
}
.policy-condition-controls {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 12px;
align-items: center;
}
.policy-condition-controls>button {
width: auto;
}
.policy-condition-feedback {
color: var(--green);
}
.policy-template-library {
display: grid;
gap: 14px;
padding: 16px;
border: 1px solid var(--accent);
background: var(--panel2);
min-width: 0;
border-radius: var(--rp-radius-surface, 0px);
}
.policy-template-heading {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.policy-template-heading>h4 {
color: var(--text);
}
.policy-template-heading>button {
width: auto;
margin-left: auto;
}
.policy-template-count {
color: var(--muted);
font-size: 12px;
}
.policy-template-filters {
display: grid;
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
gap: 12px;
}
.policy-template-cards {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
max-height: 580px;
max-height: min(64vh, 580px);
overflow: auto;
overscroll-behavior: contain;
min-width: 0;
}
.policy-template-card {
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
border: 1px solid var(--line);
background: var(--panel);
min-width: 0;
border-radius: var(--rp-radius-surface, 0px);
}
.policy-template-card>h4 {
color: var(--text);
font-size: 14px;
line-height: 1.4;
}
.policy-template-card p {
line-height: 1.5;
overflow-wrap: anywhere;
}
.policy-template-card>button {
width: auto;
align-self: flex-start;
margin-top: auto;
}
.policy-template-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.policy-template-badges>span {
padding: 3px 7px;
border: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
border-radius: var(--rp-radius-control, 0px);
}
.policy-template-note {
padding-left: 10px;
border-left: 2px solid var(--line);
}
.http-policy-editor .policy-template-preview>summary {
padding: 7px 9px;
font-size: 12px;
font-weight: 400;
}
.policy-template-preview>.policy-result {
border: 0;
border-top: 1px solid var(--line);
max-height: 240px;
}
.policy-visual>p.fine {
padding: 20px;
border: 1px dashed var(--line);
text-align: center;
}
.policy-rule>button,
.policy-detail-body>button {
justify-self: start;
}
.policy-result {
margin: 0;
padding: 12px;
@@ -75,22 +411,108 @@
font-size: 12px;
line-height: 1.5;
}
.policy-message { padding: 10px; border: 1px solid var(--line); white-space: pre-wrap; }
.policy-message.is-error { color: var(--red); border-color: var(--danger-line-strong); }
.policy-trace { width: 100%; border-collapse: collapse; font-size: 12px; table-layout: fixed; }
.policy-trace th,
.policy-trace td { padding: 8px; text-align: left; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; white-space: pre-wrap; }
.policy-trace .is-matched td:first-child { color: var(--green); }
.policy-trace .is-skipped { color: var(--muted); }
.policy-counter-scroll { overflow: auto; display: grid; gap: 10px; }
.policy-counter-scroll > table { min-width: 520px; }
.docker-policy-editor { margin: 12px 0; border: 1px solid var(--line); padding: 12px; }
.docker-policy-editor > summary { cursor: pointer; font-weight: 600; }
@media (max-width: 760px) {
.policy-grid { grid-template-columns: 1fr; }
.policy-rule { padding: 12px; }
.policy-rule-heading > .policy-row-controls { width: 100%; justify-content: flex-end; }
.policy-action { grid-template-columns: minmax(0, 1fr); }
.policy-toolbar > button { flex: 1 1 auto; }
.policy-guide { margin: 0; }
.policy-message {
padding: 10px;
border: 1px solid var(--line);
white-space: pre-wrap;
}
.policy-message.is-error {
color: var(--red);
border-color: var(--danger-line-strong);
}
.policy-trace {
width: 100%;
border-collapse: collapse;
font-size: 12px;
table-layout: fixed;
}
.policy-trace th,
.policy-trace td {
padding: 8px;
text-align: left;
border-bottom: 1px solid var(--line);
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.policy-trace .is-matched td:first-child {
color: var(--green);
}
.policy-trace .is-skipped {
color: var(--muted);
}
.policy-counter-scroll {
overflow: auto;
display: grid;
gap: 10px;
}
.policy-counter-scroll>table {
min-width: 520px;
}
.docker-policy-editor {
margin: 12px 0;
border: 1px solid var(--line);
padding: 12px;
}
.docker-policy-editor>summary {
cursor: pointer;
font-weight: 600;
}
@media (max-width: 760px) {
.policy-grid {
grid-template-columns: 1fr;
}
.policy-template-filters,
.policy-template-cards {
grid-template-columns: minmax(0, 1fr);
}
.policy-template-library {
padding: 12px;
}
.policy-condition-row {
grid-template-columns: minmax(0, 1fr);
}
.policy-condition-row>button {
justify-self: end;
}
.policy-rule {
padding: 12px;
}
.policy-rule-heading>.policy-row-controls {
width: 100%;
justify-content: flex-end;
}
.policy-action,
.policy-action[data-policy-fields] {
grid-template-columns: minmax(0, 1fr);
}
.policy-action[data-policy-fields="0"]>.policy-row-controls {
grid-column: 1 / -1;
}
.policy-toolbar>button {
flex: 1 1 auto;
}
.policy-guide {
margin: 0;
}
}
+354 -62
View File
@@ -1,4 +1,3 @@
.certificate-card .pill,
.cache-miss-key,
.file-logs-table th .file-log-sort-button:hover,
@@ -164,7 +163,7 @@
.cache-toolbar {
flex-wrap: wrap;
display: flex;
align-items: center;
align-items: flex-end;
gap: 10px;
padding: 12px;
}
@@ -381,9 +380,17 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
.cache-toolbar-status {
margin-left: auto;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
white-space: nowrap;
gap: 6px 12px;
min-width: 0;
min-height: var(--button-min-height);
max-width: 100%;
overflow-wrap: anywhere;
}
.cache-toolbar-status>.check {
margin: 0 !important;
}
.traffic-line {
@@ -494,8 +501,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
color: var(--chart-quaternary);
}
/* Legend keys use the same chart palette variables as their lines, so they
still match when a chart style (for example colour-blind) is selected. */
.cache-hit-key,
.cache-fill-key {
color: var(--chart-secondary);
@@ -805,7 +810,6 @@ button.config-history-day.is-selected,
color: var(--accent);
}
/* Search syntax help: an inline panel inside the workspace (never off-screen). */
.file-log-syntax {
display: grid;
grid-column: 1/-1;
@@ -859,10 +863,18 @@ button.config-history-day.is-selected,
background: var(--panel2);
}
.file-log-chip.is-2xx.active { border-color: var(--green); }
.file-log-chip.is-2xx.active {
border-color: var(--green);
}
.file-log-chip.is-4xx.active,
.file-log-chip.is-protocol.active { border-color: var(--notice-line); }
.file-log-chip.is-5xx.active { border-color: var(--red); }
.file-log-chip.is-protocol.active {
border-color: var(--notice-line);
}
.file-log-chip.is-5xx.active {
border-color: var(--red);
}
#file-log-summary strong {
color: var(--text);
@@ -1226,67 +1238,347 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
color: var(--muted);
}
#panel-cache .cache-table .cache-reasons { min-width: 200px; max-width: 320px; }
.cache-reason-line { display: inline-flex; align-items: baseline; gap: 4px; margin: 0 10px 0 0; font-size: 11px; line-height: 1.5; white-space: nowrap; }
.cache-reason-name { color: var(--muted); }
.cache-reason-count { font-variant-numeric: tabular-nums; font-weight: 600; }
.cache-reason-more { color: var(--muted); cursor: help; margin-right: 0; }
.cache-reason-none { color: var(--muted); }
#panel-cache .cache-table .cache-reasons {
min-width: 200px;
max-width: 320px;
}
.cache-reason-line {
display: inline-flex;
align-items: baseline;
gap: 4px;
margin: 0 10px 0 0;
font-size: 11px;
line-height: 1.5;
white-space: nowrap;
}
.cache-reason-name {
color: var(--muted);
}
.cache-reason-count {
font-variant-numeric: tabular-nums;
font-weight: 600;
}
.cache-reason-more {
color: var(--muted);
cursor: help;
margin-right: 0;
}
.cache-reason-none {
color: var(--muted);
}
#cache-object-scroll .cache-table td:nth-child(n+6):nth-child(-n+12),
#cache-object-scroll .cache-table th:nth-child(n+6):nth-child(-n+12) { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
#cache-object-scroll .cache-table th:nth-child(n+6):nth-child(-n+12) {
text-align: right;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
#cache-object-scroll .cache-table td:nth-child(3),
#cache-object-scroll .cache-table td:nth-child(4) { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; overflow-wrap: normal; }
#cache-object-scroll .cache-table td:nth-child(4) {
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
overflow-wrap: normal;
}
#cache-object-scroll .cache-table td:nth-child(3):hover,
#cache-object-scroll .cache-table td:nth-child(4):hover { white-space: normal; overflow-wrap: anywhere; }
#cache-object-scroll .cache-table tbody tr:hover { background: var(--panel2); }
.cache-tier-pill { display: inline-flex; align-items: center; padding: 2px 6px; border: 1px solid var(--pill-line); border-radius: var(--rp-radius-control, 0); color: var(--muted); font: 9px var(--mono); letter-spacing: 1px; text-transform: uppercase; }
.cache-tier-pill.is-hot { color: var(--green); border-color: var(--pill-live-line); }
#cache-object-scroll .cache-table td:nth-child(4):hover {
white-space: normal;
overflow-wrap: anywhere;
}
.cache-pager { display: inline-flex; 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; }
.cache-pager button:disabled { opacity: .45; }
.cache-pager #cache-page { padding: 0 14px; min-width: 120px; text-align: center; font-variant-numeric: tabular-nums; border-inline: 1px solid var(--line); align-self: stretch; display: flex; align-items: center; justify-content: center; }
.cache-pager #cache-next { flex-direction: row-reverse; }
#cache-object-scroll .cache-table tbody tr:hover {
background: var(--panel2);
}
.transform-vhost-table :is(th, td):nth-child(n+2), .transform-type-table :is(th, td):nth-child(2) { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.transform-vhost-table td, .transform-type-table td { vertical-align: middle; }
.transform-vhost-table td:first-child { color: var(--text); font-weight: 600; }
.transform-type-table td:first-child { color: var(--muted); }
.transform-vhost-table tbody tr:hover, .transform-type-table tbody tr:hover { background: var(--panel2); }
.transform-zero { color: var(--muted); }
.transform-errors-nonzero { color: var(--red, #e5534b); font-weight: 600; }
.transform-reason-list { gap: 4px 12px; }
.transform-reason-list .cache-reason-line { margin: 0; }
.cache-tier-pill {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border: 1px solid var(--pill-line);
border-radius: var(--rp-radius-control, 0);
color: var(--muted);
font: 9px var(--mono);
letter-spacing: 1px;
text-transform: uppercase;
}
.cache-ratio-meter, .cache-ratio-meter>i { border-radius: var(--rp-progress-radius, 0); }
.cache-tier-pill.is-hot {
color: var(--green);
border-color: var(--pill-live-line);
}
.cache-reasons .cache-reason-line { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 10px; align-items: baseline; margin: 0 0 6px; white-space: nowrap; }
.cache-reasons .cache-reason-name { overflow: hidden; text-overflow: ellipsis; }
.cache-reasons .cache-reason-track { grid-column: 1 / -1; display: block; height: 2px; margin-top: 3px; background: var(--line); border-radius: var(--rp-progress-radius, 0); overflow: hidden; }
.cache-reasons .cache-reason-track>i { display: block; height: 100%; background: var(--muted); opacity: .7; border-radius: var(--rp-progress-radius, 0); }
.cache-reasons .cache-reason-more { cursor: default; }
.cache-reasons .cache-reason-more>summary { cursor: pointer; display: inline-flex; align-items: center; gap: 5px; margin: 0 0 6px; padding: 1px 6px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0); font: 10px/1.5 var(--mono); color: var(--muted); list-style: none; user-select: none; }
.cache-reasons .cache-reason-more>summary::-webkit-details-marker { display: none; }
.cache-reasons .cache-reason-more>summary::before { content: "›"; display: inline-block; font-size: 12px; line-height: 1; transition: transform .15s ease; }
.cache-reasons .cache-reason-more[open]>summary::before { transform: rotate(90deg); }
.cache-reasons .cache-reason-more>summary:hover { color: var(--text); border-color: var(--muted); }
.cache-pager {
display: inline-flex;
align-items: center;
gap: 0;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 6px);
overflow: hidden;
}
.cache-target-wrap { display: flex; align-items: center; gap: 6px; min-width: 0; }
.cache-target-text { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cache-target-wrap .cache-transform-badge { flex: 0 0 auto; margin-left: 0; }
.cache-pager button {
border: 0;
border-radius: 0;
min-width: 88px;
margin: 0;
}
#panel-cache .card-heading:has(.cache-pager) { flex-wrap: wrap; row-gap: 8px; }
.cache-pager { flex-wrap: nowrap; flex: 0 0 auto; max-width: 100%; margin-left: auto; }
.cache-pager button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; white-space: nowrap; flex: 0 0 auto; }
.cache-pager #cache-page { flex: 1 1 auto; white-space: nowrap; }
.cache-pager button:disabled {
opacity: .45;
}
.cache-pager { overflow: visible; border-radius: var(--rp-radius-control, 0px); }
.cache-pager button { border-radius: 0; }
.cache-pager>button:first-child { border-radius: max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)); }
.cache-pager>button:last-child { border-radius: 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0; }
.cache-pager button:focus-visible { outline-offset: -2px; }
.cache-pager #cache-page {
padding: 0 14px;
min-width: 120px;
text-align: center;
font-variant-numeric: tabular-nums;
border-inline: 1px solid var(--line);
align-self: stretch;
display: flex;
align-items: center;
justify-content: center;
}
#panel-cache .cache-pager>button { border-radius: 0 !important; }
#panel-cache .cache-pager>button:first-child { border-radius: max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) !important; }
#panel-cache .cache-pager>button:last-child { border-radius: 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 !important; }
.cache-pager #cache-next {
flex-direction: row-reverse;
}
.transform-vhost-table :is(th, td):nth-child(n+2),
.transform-type-table :is(th, td):nth-child(2) {
text-align: right;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.transform-vhost-table td,
.transform-type-table td {
vertical-align: middle;
}
.transform-vhost-table td:first-child {
color: var(--text);
font-weight: 600;
}
.transform-type-table td:first-child {
color: var(--muted);
}
.transform-vhost-table tbody tr:hover,
.transform-type-table tbody tr:hover {
background: var(--panel2);
}
.transform-zero {
color: var(--muted);
}
.transform-errors-nonzero {
color: var(--red, #e5534b);
font-weight: 600;
}
.transform-reason-list {
gap: 4px 12px;
}
.transform-reason-list .cache-reason-line {
margin: 0;
}
.cache-ratio-meter,
.cache-ratio-meter>i {
border-radius: var(--rp-progress-radius, 0);
}
.cache-reasons .cache-reason-line {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
column-gap: 10px;
align-items: baseline;
margin: 0 0 6px;
white-space: nowrap;
}
.cache-reasons .cache-reason-name {
overflow: hidden;
text-overflow: ellipsis;
}
.cache-reasons .cache-reason-track {
grid-column: 1 / -1;
display: block;
height: 2px;
margin-top: 3px;
background: var(--line);
border-radius: var(--rp-progress-radius, 0);
overflow: hidden;
}
.cache-reasons .cache-reason-track>i {
display: block;
height: 100%;
background: var(--muted);
opacity: .7;
border-radius: var(--rp-progress-radius, 0);
}
.cache-reasons .cache-reason-more {
cursor: default;
}
.cache-reasons .cache-reason-more>summary {
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 5px;
margin: 0 0 6px;
padding: 1px 6px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 0);
font: 10px/1.5 var(--mono);
color: var(--muted);
list-style: none;
user-select: none;
}
.cache-reasons .cache-reason-more>summary::-webkit-details-marker {
display: none;
}
.cache-reasons .cache-reason-more>summary::before {
content: "›";
display: inline-block;
font-size: 12px;
line-height: 1;
transition: transform .15s ease;
}
.cache-reasons .cache-reason-more[open]>summary::before {
transform: rotate(90deg);
}
.cache-reasons .cache-reason-more>summary:hover {
color: var(--text);
border-color: var(--muted);
}
.cache-target-wrap {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.cache-target-text {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cache-target-wrap .cache-transform-badge {
flex: 0 0 auto;
margin-left: 0;
}
#panel-cache .card-heading:has(.cache-pager),
#panel-cache .card-heading:has(.cache-domain-filter) {
flex-wrap: wrap;
row-gap: 8px;
}
.cache-pager {
flex-wrap: nowrap;
flex: 0 0 auto;
max-width: 100%;
margin-left: auto;
}
.cache-pager button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
white-space: nowrap;
flex: 0 0 auto;
}
.cache-pager #cache-page {
flex: 1 1 auto;
white-space: nowrap;
}
.cache-pager {
overflow: visible;
border-radius: var(--rp-radius-control, 0px);
}
.cache-pager button {
border-radius: 0;
}
.cache-pager>button:first-child {
border-radius: max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px));
}
.cache-pager>button:last-child {
border-radius: 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0;
}
.cache-pager button:focus-visible {
outline-offset: -2px;
}
#panel-cache .cache-pager>button {
border-radius: 0 !important;
}
#panel-cache .cache-pager>button:first-child {
border-radius: max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) !important;
}
#panel-cache .cache-pager>button:last-child {
border-radius: 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 !important;
}
@media (max-width: 620px) {
.cache-pager {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
width: 100%;
}
.cache-pager #cache-page {
grid-column: 1 / -1;
grid-row: 1;
min-width: 0;
min-height: var(--button-min-height);
padding: 4px 8px;
border-inline: 0;
border-bottom: 1px solid var(--line);
white-space: normal;
overflow-wrap: anywhere;
}
.cache-pager #cache-next {
border-inline-start: 1px solid var(--line);
}
#panel-cache .cache-pager>button:first-child {
border-radius: 0 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) !important;
}
#panel-cache .cache-pager>button:last-child {
border-radius: 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 !important;
}
}
+9 -9
View File
@@ -938,7 +938,7 @@
.log-tools button {
white-space: normal;
max-width: 85px;
max-width: 100%;
}
.page-footer {
@@ -1072,9 +1072,12 @@
max-height: calc((50dvh) / var(--ui-scale, 1));
}
.log-tools select {
max-width: 140px;
flex: 1;
.log-tools>button,
.log-tools>.log-column-picker,
.log-tools select,
.log-tools input:not([type=checkbox]):not([type=radio]) {
max-width: 100%;
flex: 1 1 140px;
}
.logs-dialog.docked {
@@ -1166,9 +1169,6 @@
flex-direction: column;
}
/* Keep the disclosure arrow and the title on one line; the route hint
wraps below them. A column layout put the arrow on its own row and let
the summary items spread vertically, leaving large empty gaps. */
details.docker-service-editor>summary {
flex-direction: row;
flex-wrap: wrap;
@@ -2101,9 +2101,9 @@
flex: 0 0 190px;
}
}
@media (max-width: 760px) {
/* Plain request records do not need an "Event: request" line on phones. */
#panel-filelogs .file-logs-table tbody tr:not([data-event]) td[data-mobile-column=event] {
display: none;
}
}
}
+4 -3
View File
@@ -13,15 +13,16 @@ documentation Reader/API page keeps its independent `../docs.css` stylesheet.
## Module ownership and order
| Order | File | Responsibility |
|---|---|---|
| --- | --- | --- |
| 1 | `00-tokens.css` | Theme palettes, appearance tokens and custom properties shared with JavaScript preferences |
| 2 | `10-base.css` | Reset, typography, buttons, form fields, tables, shared cards, dialogs and overlays |
| 3 | `20-shell.css` | Startup, login, navigation, page structure and editor draft dock |
| 4 | `30-overview.css` | Shared charts/legends and Overview metrics, density, widget layout controls and dashboard presets |
| 5 | `40-editors.css` | Vhosts and backends, Web Server, Streams, redirects, 404 hosts and ACL controls |
| 6 | `50-settings.css` | Settings, certificates, integrations and Docker service/agent management |
| 7 | `60-monitoring.css` | Traffic, cache, transformations, live/stored logs and configuration history |
| 8 | `70-responsive.css` | All viewport/container queries and reduced-motion adjustments, in their required cascade order |
| 7 | `55-policy.css` | Shared visual HTTP policy editor and preset library |
| 8 | `60-monitoring.css` | Traffic, cache, transformations, live/stored logs and configuration history |
| 9 | `70-responsive.css` | All viewport/container queries and reduced-motion adjustments, in their required cascade order |
## Editing rules
+362 -232
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+169 -55
View File
@@ -1,9 +1,15 @@
"use strict";
// The editor only builds configuration. Import, validation and test evaluation use
// the same Rust compiler/evaluator as live traffic; there is no JS policy engine.
window.rustProxyPolicy = (() => {
const STAGES = ["pre_route", "request", "backend_request", "backend_response", "deliver", "after_response"];
const OPERATORS = ["equals", "contains", "prefix", "suffix", "regex", "exists", "cidr", "eq", "ne", "gt", "ge", "lt", "le"];
const TEXT_OPERATORS = ["equals", "contains", "prefix", "suffix", "regex"];
const NUMBER_OPERATORS = ["eq", "ne", "gt", "ge", "lt", "le"];
const ACTION_STAGES = {
set_path: ["pre_route"], set_query: ["pre_route"], use_backend: ["pre_route", "request"], deny: ["pre_route", "request"],
return: ["request"], redirect: ["request"], pass: ["pre_route", "request"], lookup: ["pre_route", "request"], hash_header: ["pre_route", "request"],
no_store: ["pre_route", "request", "backend_response"], set_ttl: ["backend_response"], set_grace: ["backend_response"],
disable_compression: STAGES.filter(stage => stage !== "after_response")
};
const ACTION_FIELDS = {
set_header: ["name", "value"], append_header: ["name", "value"], remove_header: ["name"], set_if_missing: ["name", "value"],
normalize_header: ["name"], merge_header: ["name", "value"], remove_value: ["name", "value"], replace_header: ["name", "pattern", "replacement"], replace_value: ["name", "pattern", "replacement"],
@@ -12,15 +18,20 @@ window.rustProxyPolicy = (() => {
set_ttl: ["seconds"], set_grace: ["seconds"], hash_header: ["name"], disable_compression: [], stop: []
};
const clone = value => structuredClone(value);
const label = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const label = (prefix, value) => t(`${prefix}${String(value).split("_").filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
const text = (tag, key, cls) => { const node = el(tag, t(key), cls); node.dataset.i18n = key; return node; };
const button = (key, fn, cls = "quiet") => { const node = text("button", key, cls); node.type = "button"; node.addEventListener("click", fn); return node; };
const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
let editorSequence = 0;
function settings(value) {
if (!object(value) || (value.rules !== undefined && !Array.isArray(value.rules)) || (value.acls !== undefined && !object(value.acls)) || (value.maps !== undefined && !object(value.maps))) throw Error(t("policyInvalid"));
const copy = clone(value);
copy.rules ??= []; copy.acls ??= {}; copy.maps ??= {};
if (copy.rules.length > 128 || copy.rules.some(rule => !object(rule) || !Array.isArray(rule.actions))) throw Error(t("policyInvalid"));
if (copy.rules.length > 128 || copy.rules.some(rule => !object(rule) || !Array.isArray(rule.actions)
|| rule.actions.some(action => !object(action) || typeof action.type !== "string")
|| (rule.when !== undefined && !object(rule.when))
|| ["id", "name", "stage"].some(key => rule[key] !== undefined && typeof rule[key] !== "string")
|| ["enabled", "stop"].some(key => rule[key] !== undefined && typeof rule[key] !== "boolean"))) throw Error(t("policyInvalid"));
return copy;
}
function headers(source) {
@@ -35,7 +46,7 @@ window.rustProxyPolicy = (() => {
const node = document.createElement(options.type === "textarea" ? "textarea" : options.values ? "select" : "input");
if (options.values) for (const [v, name] of options.values) { const item = el("option", name); item.value = v; node.append(item); }
else if (options.type !== "textarea") node.type = options.type || "text";
if (options.type === "checkbox") node.checked = Boolean(value); else node.value = value ?? "";
if (options.type === "checkbox") { node.checked = Boolean(value); node.classList.add("switch"); } else node.value = value ?? "";
if (!options.values && options.type !== "checkbox") { node.spellcheck = false; node.autocomplete = "off"; }
if (options.rows) node.rows = options.rows;
if (options.maxLength) node.maxLength = options.maxLength;
@@ -52,8 +63,9 @@ window.rustProxyPolicy = (() => {
if (type === "normalize_header") action.name = "Vary";
return action;
}
function limitTerminalActions(select, stage) {
for (const option of select.options) option.disabled = ["return", "redirect"].includes(option.value) && stage !== "request";
function limitActions(select, stage) {
for (const option of select.options) option.disabled = Object.hasOwn(ACTION_STAGES, option.value) && !ACTION_STAGES[option.value].includes(stage);
select.setCustomValidity(select.selectedOptions[0]?.disabled ? t("policyActionStage") : "");
}
function uniqueId(rules, prefix = "policy") { let n = 1; while (rules.some(rule => rule.id === `${prefix}-${n}`)) n++; return `${prefix}-${n}`; }
function mergeImports(current, addition) {
@@ -70,29 +82,27 @@ window.rustProxyPolicy = (() => {
return settings(next);
}
function preset(kind, id) {
const base = { id, name: t(kind === "vary" ? "policyPresetVary" : "policyPresetNormalize"), enabled: true, stage: kind === "vary" ? "backend_response" : "after_response", when: { all: [] }, actions: [], stop: false };
if (kind === "vary") {
base.when.all = [
{ fetch: "res.fhdr_cnt(Vary)", operator: "eq", values: ["2"] },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept-Encoding"], ignore_case: true },
{ fetch: "res.fhdr(Vary)", operator: "equals", values: ["Accept,Accept-Encoding", "Accept, Accept-Encoding"], ignore_case: true }
];
base.actions = [{ type: "set_header", name: "Vary", value: "Accept, Accept-Encoding" }];
} else base.actions = [{ type: "normalize_header", name: "Vary" }];
return base;
const template = window.rustProxyPolicyPresets.find(item => item.id === kind);
if (!template) throw Error(t("policyInvalid"));
const { nameKey, ...rule } = clone(template.rules[0]);
return { ...rule, id, name: t(nameKey || template.titleKey) };
}
function create({ value = {}, scope = "vhost", onChange = () => {} } = {}) {
function create({ value = {}, scope = "vhost", onChange = () => { } } = {}) {
let model = settings(value), mode = "visual", epoch = 0, importResult = null;
const stagesForScope = STAGES.filter(stage => scope !== "location" || stage !== "pre_route");
const node = el("section", undefined, "http-policy-editor vh-wide"), message = el("p", undefined, "policy-message fine");
message.setAttribute("role", "status"); message.setAttribute("aria-live", "polite"); message.hidden = true;
const toolbar = el("div", undefined, "policy-toolbar"), visual = el("div", undefined, "policy-visual"), rawPane = el("div", undefined, "policy-raw"); rawPane.hidden = true;
const toolbar = el("div", undefined, "policy-toolbar"), visual = el("fieldset", undefined, "policy-visual"), rawPane = el("fieldset", undefined, "policy-raw"); rawPane.hidden = true; rawPane.disabled = true;
node.append(text("p", "policyIntro", "fine"), text("p", "policyCompatibility", "fine"), toolbar, message, visual, rawPane);
const raw = input(rawPane, "policyJson", JSON.stringify(model, null, 2), { type: "textarea", rows: 18, maxLength: 262144, wide: true });
const fail = error => { message.textContent = error.message || String(error); message.classList.add("is-error"); message.hidden = false; };
const clear = () => { message.hidden = true; message.classList.remove("is-error"); };
const notice = value => { message.textContent = value; message.classList.remove("is-error"); message.hidden = false; };
const change = () => { epoch++; clear(); onChange(); };
const safely = fn => (...args) => { try { return fn(...args); } catch (error) { fail(error); } };
node.addEventListener("invalid", event => {
for (let parent = event.target.parentElement; parent && parent !== node; parent = parent.parentElement) if (parent.tagName === "DETAILS") parent.open = true;
}, true);
const parse = (control, check = value => value) => {
try { const value = check(JSON.parse(control.value)); control.setCustomValidity(""); return value; }
catch (error) { control.setCustomValidity(error.message || t("policyInvalid")); throw error; }
@@ -106,13 +116,14 @@ window.rustProxyPolicy = (() => {
function setValue(value) { model = settings(value); raw.value = JSON.stringify(model, null, 2); raw.setCustomValidity(""); render(); }
const setMode = safely(next => {
model = read(); mode = next; visual.hidden = mode !== "visual"; rawPane.hidden = mode !== "json";
visual.disabled = mode !== "visual"; rawPane.disabled = mode !== "json";
if (mode === "json") raw.value = JSON.stringify(model, null, 2); else render();
visualButton.setAttribute("aria-pressed", String(mode === "visual")); jsonButton.setAttribute("aria-pressed", String(mode === "json")); clear();
});
const visualButton = button("policyVisual", () => setMode("visual")), jsonButton = button("policyJson", () => setMode("json"));
visualButton.setAttribute("aria-pressed", "true"); jsonButton.setAttribute("aria-pressed", "false"); toolbar.append(visualButton, jsonButton);
raw.addEventListener("input", () => { raw.setCustomValidity(""); change(); });
const guide = el("a", t("documentation"), "policy-guide"); guide.href = "/docs#doc=docs%2FPOLICY.md"; guide.target = "_blank"; guide.rel = "noopener"; toolbar.append(guide);
const guide = text("a", "documentation", "outline policy-guide"); guide.href = "/docs#doc=docs%2FPOLICY.md"; guide.target = "_blank"; guide.rel = "noopener noreferrer"; toolbar.append(guide);
const editJson = (parent, key, current, apply, check = value => value, rows = 4) => {
const area = input(parent, key, JSON.stringify(current, null, 2), { type: "textarea", rows, maxLength: 65536, wide: true }); area.classList.add("policy-config-json");
area._readJson = () => { const data = parse(area, check); apply(data); return data; };
@@ -122,20 +133,91 @@ window.rustProxyPolicy = (() => {
function renderAction(parent, rule, action, index, refresh) {
const row = el("div", undefined, "policy-action"); parent.append(row);
const known = Object.hasOwn(ACTION_FIELDS, action.type), choices = Object.keys(ACTION_FIELDS).map(type => [type, label("policyAction", type)]);
row.dataset.policyFields = String(known ? ACTION_FIELDS[action.type].length : 1);
if (!known) choices.unshift([action.type || "", action.type || t("policyAdvancedAction")]);
const op = input(row, "policyAction", action.type, { values: choices });
op.dataset.policyAction = ""; limitTerminalActions(op, rule.stage || "request");
op.dataset.policyAction = ""; limitActions(op, rule.stage || "request");
op.addEventListener("change", safely(() => { read(); rule.actions[index] = defaultAction(op.value); refresh(); change(); }));
if (!known) editJson(row, "policyAdvancedAction", action, value => { rule.actions[index] = value; }, requireObject);
else for (const key of ACTION_FIELDS[action.type]) {
const number = ["status", "seconds"].includes(key), field = input(row, `policyField${key[0].toUpperCase()}${key.slice(1)}`, action[key], { type: number ? "number" : key === "body" ? "textarea" : "text", rows: key === "body" ? 2 : undefined, maxLength: key === "body" ? 65536 : 8192, min: number ? 0 : undefined });
const number = ["status", "seconds"].includes(key), field = input(row, `policyField${key[0].toUpperCase()}${key.slice(1)}`, action[key], { type: number ? "number" : key === "body" ? "textarea" : "text", rows: key === "body" ? 2 : undefined, maxLength: key === "body" ? 65536 : 8192, min: key === "status" ? (action.type === "deny" ? 400 : 200) : number ? 0 : undefined, max: key === "status" ? 599 : key === "seconds" ? 31536000 : undefined });
field.addEventListener("input", () => { action[key] = number ? Number(field.value) : field.value; change(); });
}
const controls = el("div", undefined, "policy-row-controls"); row.append(controls);
const up = button("policyMoveUp", safely(() => { read(); [rule.actions[index - 1], rule.actions[index]] = [rule.actions[index], rule.actions[index - 1]]; refresh(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [rule.actions[index + 1], rule.actions[index]] = [rule.actions[index], rule.actions[index + 1]]; refresh(); change(); })); down.disabled = index === rule.actions.length - 1;
const up = button("policyMoveUp", safely(() => { read();[rule.actions[index - 1], rule.actions[index]] = [rule.actions[index], rule.actions[index - 1]]; refresh(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read();[rule.actions[index + 1], rule.actions[index]] = [rule.actions[index], rule.actions[index + 1]]; refresh(); change(); })); down.disabled = index === rule.actions.length - 1;
controls.append(up, down, button("remove", safely(() => { read(); rule.actions.splice(index, 1); refresh(); change(); })));
}
function renderConditions(card, rule) {
const conditions = el("details", undefined, "policy-conditions"), summary = el("summary"), count = el("span", undefined, "policy-condition-count");
summary.append(text("span", "policyConditions"), count); conditions.append(summary); card.append(conditions);
const body = el("div", undefined, "policy-detail-body"), list = el("div", undefined, "policy-condition-list"); body.append(list); conditions.append(body);
const advanced = el("details", undefined, "policy-condition-advanced"); advanced.append(text("summary", "policyConditionAdvanced"));
const advancedBody = el("div", undefined, "policy-detail-body"); advanced.append(advancedBody); body.append(advanced);
const groupOf = value => Object.keys(value).length === 1 ? ["all", "any"].find(key => Array.isArray(value[key])) : undefined;
const describe = (value, depth = 0) => {
if (!object(value) || depth > 16) return JSON.stringify(value);
const group = groupOf(value);
if (group) return value[group].length ? `(${value[group].map(item => describe(item, depth + 1)).join(group === "all" ? " AND " : " OR ")})` : t(group === "all" ? "policyConditionAlways" : "policyConditionNever");
if (value.not) return `NOT (${describe(value.not, depth + 1)})`;
if (value.acl) return `ACL: ${value.acl}`;
if (typeof value.fetch === "string" && (value.values === undefined || Array.isArray(value.values))) return `${value.fetch} ${value.operator || ""}${value.operator === "exists" ? "" : ` ${(value.values || []).map(item => JSON.stringify(item)).join(" | ")}`}${value.ignore_case ? ` · ${t("policyIgnoreCase")}` : ""}`;
return JSON.stringify(value);
};
const refreshConditions = () => {
list.replaceChildren(); const value = rule.when || { all: [] }, group = groupOf(value), items = group ? value[group] : [value];
count.textContent = String(items.length); count.title = t("policyConditionsCount").replace("{count}", items.length);
count.setAttribute("aria-label", count.title);
if (!items.length) { list.append(text("p", group === "any" ? "policyConditionNever" : "policyConditionEmpty", "fine")); return; }
if (group) list.append(el("span", group === "all" ? "AND" : "OR", "policy-condition-join"));
items.forEach((item, index) => {
const row = el("div", undefined, "policy-condition-row"); row.append(el("code", describe(item)));
row.append(button("policyConditionRemove", safely(() => {
const current = parse(when, requireObject), currentGroup = groupOf(current);
if (currentGroup) {
const remaining = current[currentGroup].filter((_, at) => at !== index);
rule.when = remaining.length ? { [currentGroup]: remaining } : { all: [] };
} else rule.when = { all: [] };
when.value = JSON.stringify(rule.when, null, 2); when.setCustomValidity(""); refreshConditions(); change();
})));
list.append(row);
});
};
const when = editJson(advancedBody, "policyConditionJson", rule.when || { all: [] }, value => { rule.when = value; refreshConditions(); }, requireObject, 5);
const simple = el("div", undefined, "policy-grid policy-condition-builder");
const fetch = input(simple, "policyFetch", "path", { maxLength: 4096, placeholder: "path, method, req.fhdr(Host)…" });
const operator = input(simple, "policyOperator", "prefix", { values: OPERATORS.map(op => [op, op]) });
const modeSelect = input(simple, "policyCombine", groupOf(rule.when || {}) || "all", { values: [["all", "AND"], ["any", "OR"]] });
const values = input(simple, "policyValues", "", { type: "textarea", rows: 2, maxLength: 8192, wide: true, placeholder: "/api/" });
const controls = el("div", undefined, "policy-condition-controls policy-wide"), ignore = input(controls, "policyIgnoreCase", false, { type: "checkbox" });
const feedback = el("p", undefined, "policy-condition-feedback fine"); feedback.setAttribute("role", "status"); feedback.hidden = true;
const syncOperator = () => { values.disabled = operator.value === "exists"; ignore.disabled = !TEXT_OPERATORS.includes(operator.value); values.setCustomValidity(""); };
operator.addEventListener("change", syncOperator); syncOperator();
const invalid = (control, key) => { control.setCustomValidity(t(key)); control.focus(); control.reportValidity(); throw Error(t(key)); };
controls.append(button("policyAddCondition", safely(() => {
feedback.hidden = true; const before = parse(when, requireObject), sample = fetch.value.trim(), numeric = NUMBER_OPERATORS.includes(operator.value);
if (!sample) invalid(fetch, "policyConditionFetchRequired");
const operands = operator.value === "exists" ? [] : values.value.split(/\r?\n/).filter(value => value.length).map(value => numeric ? value.trim() : value);
if (operator.value !== "exists" && !operands.length) invalid(values, "policyConditionValuesRequired");
if (operands.length > 64) invalid(values, "policyConditionValueLimit");
if (numeric && operands.some(value => !/^[+-]?\d+$/.test(value) || BigInt(value) < -9223372036854775808n || BigInt(value) > 9223372036854775807n)) invalid(values, "policyConditionNumber");
if (numeric && operator.value !== "eq" && operands.length !== 1) invalid(values, "policyConditionSingleNumber");
const condition = { fetch: sample, operator: operator.value, values: operands, ignore_case: !ignore.disabled && ignore.checked };
const group = modeSelect.value, beforeGroup = groupOf(before), empty = beforeGroup && !before[beforeGroup].length;
if (beforeGroup === group && before[group].length >= 32) throw Error(t("policyConditionLimit"));
rule.when = empty ? { [group]: [condition] } : beforeGroup === group ? { [group]: [...before[group], condition] } : { [group]: [before, condition] };
when.value = JSON.stringify(rule.when, null, 2); when.setCustomValidity(""); refreshConditions(); change();
feedback.textContent = t("policyConditionAdded"); feedback.hidden = false;
}), "primary"));
simple.append(controls);
for (const control of simple.querySelectorAll("input, select, textarea")) {
control.setAttribute("form", "rustproxy-policy-tools");
control.addEventListener("input", () => { control.setCustomValidity(""); feedback.hidden = true; });
}
simple.addEventListener("input", event => event.stopPropagation()); simple.addEventListener("change", event => event.stopPropagation());
body.append(text("p", "policyConditionDraft", "fine"), simple, feedback, text("p", "policyConditionsHelp", "fine"));
refreshConditions();
}
function renderRule(parent, rule, index) {
const card = el("article", undefined, `policy-rule${rule.enabled === false ? " is-disabled" : ""}`); card.dataset.ruleId = rule.id || ""; parent.append(card);
const heading = el("div", undefined, "policy-rule-heading"), enabled = input(heading, "enabled", rule.enabled !== false, { type: "checkbox" });
@@ -145,48 +227,81 @@ window.rustProxyPolicy = (() => {
enabled.addEventListener("change", () => { rule.enabled = enabled.checked; card.classList.toggle("is-disabled", !enabled.checked); change(); });
title.addEventListener("input", () => { rule.name = title.value; change(); });
const commands = el("div", undefined, "policy-row-controls"); heading.append(commands);
const up = button("policyMoveUp", safely(() => { read(); [model.rules[index - 1], model.rules[index]] = [model.rules[index], model.rules[index - 1]]; render(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read(); [model.rules[index + 1], model.rules[index]] = [model.rules[index], model.rules[index + 1]]; render(); change(); })); down.disabled = index === model.rules.length - 1;
const up = button("policyMoveUp", safely(() => { read();[model.rules[index - 1], model.rules[index]] = [model.rules[index], model.rules[index - 1]]; render(); change(); })); up.disabled = index === 0;
const down = button("policyMoveDown", safely(() => { read();[model.rules[index + 1], model.rules[index]] = [model.rules[index], model.rules[index + 1]]; render(); change(); })); down.disabled = index === model.rules.length - 1;
commands.append(up, down, button("remove", safely(() => { read(); model.rules.splice(index, 1); render(); change(); })));
const meta = el("div", undefined, "policy-grid"), id = input(meta, "policyRuleId", rule.id, { maxLength: 128 });
const meta = el("div", undefined, "policy-grid policy-rule-meta"), id = input(meta, "policyRuleId", rule.id, { maxLength: 128 });
const stages = [...stagesForScope]; if (rule.stage && !stages.includes(rule.stage)) stages.push(rule.stage);
const stage = input(meta, "policyStage", rule.stage || "request", { values: stages.map(stage => [stage, label("policyStage", stage)]) });
const stop = input(meta, "policyStop", !!rule.stop, { type: "checkbox" });
id.addEventListener("input", () => { rule.id = id.value; change(); }); stop.addEventListener("change", () => { rule.stop = stop.checked; change(); });
const stageHint = el("p", label("policyStageHelp", stage.value), "policy-wide fine");
stage.addEventListener("change", () => { rule.stage = stage.value; stageHint.textContent = label("policyStageHelp", stage.value); for (const op of card.querySelectorAll("select[data-policy-action]")) limitTerminalActions(op, stage.value); change(); });
stage.addEventListener("change", () => { rule.stage = stage.value; stageHint.textContent = label("policyStageHelp", stage.value); for (const op of card.querySelectorAll("select[data-policy-action]")) limitActions(op, stage.value); change(); });
meta.append(stageHint); card.append(meta);
const conditions = el("details", undefined, "policy-conditions"), conditionSummary = text("summary", "policyConditions"); conditions.append(conditionSummary); card.append(conditions);
const conditionBody = el("div", undefined, "policy-detail-body"); conditions.append(conditionBody);
const when = editJson(conditionBody, "policyConditionJson", rule.when || { all: [] }, value => { rule.when = value; }, requireObject, 5);
const simple = el("div", undefined, "policy-grid"), fetch = input(simple, "policyFetch", "res.fhdr(Vary)", { maxLength: 4096 });
const operator = input(simple, "policyOperator", "equals", { values: OPERATORS.map(op => [op, op]) });
const values = input(simple, "policyValues", "Accept-Encoding", { type: "textarea", rows: 2, maxLength: 8192 });
const ignore = input(simple, "policyIgnoreCase", true, { type: "checkbox" });
const modeSelect = input(simple, "policyCombine", "all", { values: [["all", "AND"], ["any", "OR"]] });
operator.addEventListener("change", () => { values.disabled = operator.value === "exists"; });
simple.append(button("policyAddCondition", safely(() => {
const before = parse(when, requireObject), condition = { fetch: fetch.value, operator: operator.value, values: operator.value === "exists" ? [] : values.value.split(/\r?\n/).filter(value => value.length), ignore_case: ignore.checked };
const group = modeSelect.value;
const empty = Object.keys(before).length === 1 && ((Array.isArray(before.all) && !before.all.length) || (Array.isArray(before.any) && !before.any.length));
rule.when = empty ? { [group]: [condition] } : Object.keys(before).length === 1 && Array.isArray(before[group]) ? { [group]: [...before[group], condition] } : { [group]: [before, condition] };
when.value = JSON.stringify(rule.when, null, 2); when.setCustomValidity(""); change();
})));
conditionBody.append(simple, text("p", "policyConditionsHelp", "fine"));
const stopRow = el("div", undefined, "policy-stop"), stop = input(stopRow, "policyStop", !!rule.stop, { type: "checkbox" });
stopRow.append(text("p", "policyStopHelp", "fine")); card.append(stopRow);
id.addEventListener("input", () => { rule.id = id.value; change(); }); stop.addEventListener("change", () => { rule.stop = stop.checked; change(); });
renderConditions(card, rule);
card.append(text("h4", "policyActions")); const actions = el("div", undefined, "policy-actions"); card.append(actions);
const refresh = () => { actions.replaceChildren(); rule.actions.forEach((action, index) => renderAction(actions, rule, action, index, refresh)); };
refresh(); const addAction = button("policyAddAction", safely(() => { read(); if (rule.actions.length >= 16) throw Error(t("policyActionLimit")); rule.actions.push(defaultAction("set_header")); refresh(); change(); })); card.append(addAction);
}
function render() {
visual.replaceChildren();
const bar = el("div", undefined, "policy-toolbar"); visual.append(bar);
const add = safely(kind => {
const bar = el("div", undefined, "policy-toolbar policy-add-toolbar"); visual.append(bar);
const focusRule = (id, expand = false) => {
const card = [...visual.querySelectorAll(".policy-rule")].find(item => item.dataset.ruleId === id);
if (expand && card) card.querySelector(".policy-conditions").open = true;
card?.scrollIntoView?.({ block: "nearest" }); card?.querySelector(".policy-rule-heading input[type=text]")?.focus({ preventScroll: true });
};
const add = safely(() => {
model = read(); if (model.rules.length >= 128) throw Error(t("policyRuleLimit"));
const id = uniqueId(model.rules);
model.rules.push(kind ? preset(kind, id) : { id, name: t("policyNewRule"), enabled: true, stage: "after_response", when: { all: [] }, actions: [defaultAction("set_header")], stop: false });
render(); change();
model.rules.push({ id, name: t("policyNewRule"), enabled: true, stage: "after_response", when: { all: [] }, actions: [defaultAction("set_header")], stop: false });
render(); change(); focusRule(id, true);
});
bar.append(button("policyAddRule", () => add(), "primary"), button("policyPresetVary", () => add("vary")), button("policyPresetNormalize", () => add("normalize")));
const catalog = el("section", undefined, "policy-template-library"); catalog.hidden = true; catalog.id = `policy-presets-${++editorSequence}`; catalog.setAttribute("aria-label", t("policyTemplates"));
const templatesButton = button("policyTemplates", () => {
catalog.hidden = !catalog.hidden; templatesButton.setAttribute("aria-expanded", String(!catalog.hidden));
if (!catalog.hidden) search.focus();
});
templatesButton.setAttribute("aria-expanded", "false"); templatesButton.setAttribute("aria-controls", catalog.id);
bar.append(button("policyAddRule", add, "primary"), templatesButton); visual.append(catalog);
const catalogHeading = el("div", undefined, "policy-template-heading"), catalogCount = el("span", undefined, "policy-template-count");
catalogHeading.append(text("h4", "policyTemplates"), catalogCount, button("close", () => { catalog.hidden = true; templatesButton.setAttribute("aria-expanded", "false"); templatesButton.focus(); }));
const filters = el("div", undefined, "policy-template-filters"), search = input(filters, "policyTemplateSearch", "", { type: "search", maxLength: 128 });
const category = input(filters, "policyTemplateCategory", "all", { values: [["all", t("policyTemplateAll")], ...["headers", "cache", "security", "routing", "diagnostics"].map(key => [key, label("policyPresetCategory", key)])] });
const cards = el("div", undefined, "policy-template-cards"), noResults = text("p", "policyTemplateNone", "fine"); noResults.hidden = true;
catalog.append(catalogHeading, text("p", "policyTemplatesIntro", "fine"), filters, cards, noResults);
const normalizeSearch = value => value.toLocaleLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/ł/g, "l");
const entries = window.rustProxyPolicyPresets.filter(template => template.rules.every(rule => stagesForScope.includes(rule.stage))).map(template => {
const card = el("article", undefined, "policy-template-card"); card.dataset.presetId = template.id;
const title = t(template.titleKey), badges = el("div", undefined, "policy-template-badges");
badges.append(el("span", label("policyPresetCategory", template.category)), el("span", t("policyTemplateCount").replace("{count}", template.rules.length)));
card.append(badges, el("h4", title), el("p", t(template.descriptionKey), "fine"));
if (template.noteKey) card.append(el("p", t(template.noteKey), "policy-template-note fine"));
const preview = el("details", undefined, "policy-template-preview"); preview.append(text("summary", "policyTemplatePreview"));
preview.append(el("pre", JSON.stringify(template.rules.map(({ nameKey, ...rule }) => ({ name: t(nameKey || template.titleKey), ...rule })), null, 2), "policy-result"));
card.append(preview, button("policyTemplateAdd", safely(() => {
const next = read(); if (next.rules.length + template.rules.length > 128) throw Error(t("policyRuleLimit"));
let firstId;
for (const item of template.rules) {
const { nameKey, ...rule } = clone(item), id = uniqueId(next.rules, template.id);
firstId ??= id; next.rules.push({ ...rule, id, name: t(nameKey || template.titleKey) });
}
model = settings(next); render(); change();
notice(t("policyTemplateAdded").replace("{name}", title).replace("{count}", template.rules.length)); focusRule(firstId);
}), "primary")); cards.append(card);
return { card, template, search: normalizeSearch([template.id, title, t(template.descriptionKey), template.noteKey ? t(template.noteKey) : "", label("policyPresetCategory", template.category), JSON.stringify(template.rules)].join(" ")) };
});
const filter = () => {
const query = normalizeSearch(search.value.trim()); let count = 0;
for (const item of entries) { item.card.hidden = (category.value !== "all" && item.template.category !== category.value) || !item.search.includes(query); if (!item.card.hidden) count++; }
noResults.hidden = count > 0; catalogCount.textContent = t("policyTemplateAvailable").replace("{count}", count);
};
for (const control of [search, category]) control.setAttribute("form", "rustproxy-policy-tools");
search.addEventListener("input", filter); category.addEventListener("change", filter);
filters.addEventListener("input", event => event.stopPropagation()); filters.addEventListener("change", event => event.stopPropagation());
catalog.addEventListener("keydown", event => { if (event.key === "Escape") { event.stopPropagation(); catalog.hidden = true; templatesButton.setAttribute("aria-expanded", "false"); templatesButton.focus(); } });
filter();
if (!model.rules.length) visual.append(text("p", "policyEmpty", "fine"));
const rules = el("div", undefined, "policy-rules"); visual.append(rules); model.rules.forEach((rule, index) => renderRule(rules, rule, index));
const definitions = el("details", undefined, "policy-definitions"); definitions.append(text("summary", "policyDefinitions"));
@@ -196,8 +311,7 @@ window.rustProxyPolicy = (() => {
body.append(text("p", "policyDefinitionsHelp", "fine")); visual.append(definitions);
}
render();
// Import is staged: server validation, visible preview, then an explicit add
// to the unsaved draft. Source changes invalidate a pending preview.
const importer = el("details", undefined, "policy-import"); importer.append(text("summary", "policyImport"));
const importBody = el("div", undefined, "policy-detail-body"); importer.append(importBody);
const source = input(importBody, "policyHaproxySource", "", { type: "textarea", rows: 7, maxLength: 262144, wide: true, placeholder: "acl vary_duplicate res.fhdr_cnt(Vary) eq 2\nacl vary_encoding res.fhdr(Vary) -i Accept-Encoding\nacl vary_combined res.fhdr(Vary) -i \"Accept,Accept-Encoding\" \"Accept, Accept-Encoding\"\nhttp-response set-header Vary \"Accept, Accept-Encoding\" if vary_duplicate vary_encoding vary_combined" });
@@ -256,7 +370,7 @@ window.rustProxyPolicy = (() => {
const details = el("details"); details.append(text("summary", "policyFullResult"), el("pre", JSON.stringify(result, null, 2), "policy-result")); resultBox.append(details);
} catch (error) { fail(error); } finally { testButton.disabled = false; }
}, "primary");
// Tester input changes invalidate an in-flight result without dirtying config.
for (const control of testGrid.querySelectorAll("input, select, textarea")) control.setAttribute("form", "rustproxy-policy-tools");
testGrid.addEventListener("input", event => { event.stopPropagation(); epoch++; }); testGrid.addEventListener("change", event => { event.stopPropagation(); epoch++; });
testBody.append(testButton, resultBox); node.append(tester);
+1 -1
View File
@@ -39,7 +39,7 @@
const status = select("redirectStatus", "status_code", [["301", "redirect301"], ["302", "redirect302"], ["303", "redirect303"], ["307", "redirect307"], ["308", "redirect308"]]); status.value = String(data.status_code);
const cache = input("redirectCacheSeconds", "cache_seconds", "number"); cache.min = "0"; cache.max = "31536000"; cache.step = "1"; cache.value = String(data.cache_seconds || 0);
const remove = el("button", t("remove"), "quiet"); remove.type = "button"; remove.addEventListener("click", () => { box.remove(); renumber(); changed(); });
const actions = el("div", undefined, "form-actions"); actions.append(remove); grid.append(actions); box.append(grid); rules.append(box); syncRule(box); targetType.addEventListener("change", () => syncRule(box));
const actions = el("div", undefined, "vh-wide redirect-rule-actions"); actions.append(remove); grid.append(actions); box.append(grid); rules.append(box); syncRule(box); targetType.addEventListener("change", () => syncRule(box));
}
function syncRule(box) {
const kind = box.querySelector('[data-field="target_type"]').value;
@@ -1,190 +0,0 @@
// Cache/VCL editor round-trip regressions. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/cache-rules.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const node = d.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
w.envelope = { config: { cache: { rules: [] }, vhosts: [] } };
w.authenticated = false;
w.fmt = value => String(value);
w.rustProxyChoicePicker = { create: options => { const node = d.createElement('div'); node.className = options.className || ''; return node; } };
let notices = [], calls = [], reply = {}, dirty = 0, editor, checks = 0;
w.toast = (message, error) => notices.push({ message, error });
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); return structuredClone(reply); };
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/cache-rules.js'), 'utf8'));
const api = w.rustProxyCacheRules;
const plain = value => JSON.parse(JSON.stringify(value));
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(rules = [], scope = 'vhost') {
notices = []; calls = []; dirty = 0;
editor = api.create({ rules, scope, vhostId: 'site', autoLoadHits: false, onChange: () => dirty++ });
d.getElementById('root').replaceChildren(editor.node);
}
function button(key, within = editor.node) {
const found = [...within.querySelectorAll('button')].find(node => node.textContent === w.t(key) || node.getAttribute('aria-label') === w.t(key));
assert.ok(found, `button ${key}`); return found;
}
function card(index = 0) { return editor.node.querySelectorAll('.cache-rule')[index]; }
function open(index = 0) { card(index).querySelector('.cache-rule-title').click(); return card(index); }
function field(key, within) {
const found = [...within.querySelectorAll('.cache-rule-field')].find(node => node.firstElementChild?.textContent === w.t(key));
assert.ok(found, `field ${key}`); return found.querySelector('input, select, textarea');
}
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
function drop(from, to) { const event = new w.Event('drop', { bubbles: true, cancelable: true }); Object.defineProperty(event, 'dataTransfer', { value: { getData: () => String(from) } }); card(to).dispatchEvent(event); }
async function importRules(rules, warnings = []) {
reply = { rules, warnings }; button('cacheRulesImportVcl').click();
fill(editor.node.querySelector('.cache-rules-import textarea'), 'sub vcl_recv { if (req.http.X-Mode == "old") { set req.http.X-Mode = "new"; } else { return (pass); } }');
button('cacheRulesImportRun').click(); await flush();
}
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const ordinary = { id: 'ordinary', name: 'Ordinary', enabled: true, stage: 'request', match: 'all', conditions: [{ field: 'path', operator: 'prefix', values: ['/assets'] }], actions: [{ type: 'set_request_header', name: 'X-Device', value: 'desktop' }], stop: false };
const hashing = { id: 'hash', name: 'Imported hash', enabled: true, stage: 'request', match: 'all', conditions: [], actions: [{ type: 'hash_header', name: 'X-Device' }], stop: false, hash_stage: true };
const flow = [
{ ...ordinary, id: 'vcl-if', name: 'If decision', conditions: [], actions: [], vcl_flow: { version: 1, group: 'vcl-fixture', index: 0, count: 3, branches: [{ any: [[{ field: 'header', name: 'X-Mode', operator: 'equals', values: ['old'] }]] }, { any: [[]] }] } },
{ ...ordinary, id: 'vcl-then', name: 'Selected branch', conditions: [], actions: [{ type: 'set_request_header', name: 'X-Mode', value: 'new' }], vcl_flow: { version: 1, group: 'vcl-fixture', index: 1, count: 3, guards: [{ entry: 0, branch: 0 }] } },
{ ...ordinary, id: 'vcl-else', name: 'Else branch', conditions: [], actions: [{ type: 'pass' }], stop: true, vcl_flow: { version: 1, group: 'vcl-fixture', index: 2, count: 3, guards: [{ entry: 0, branch: 1 }] } },
];
await check('existing request and imported hash rules survive opening and save', () => {
mount([ordinary, hashing]); open(); assert.deepEqual(plain(editor.read()), [ordinary, hashing]);
assert.equal(dirty, 0);
});
await check('ordinary reorder keeps hash phase and edited action values', () => {
const first = card(); const input = [...first.querySelectorAll('input')].find(node => node.placeholder === w.t('cacheRuleHeaderValue'));
fill(input, 'mobile'); button('cacheRulesMoveDown', first).click();
assert.deepEqual(plain(editor.read()), [hashing, { ...ordinary, actions: [{ ...ordinary.actions[0], value: 'mobile' }] }]);
assert.equal(ordinary.actions[0].value, 'desktop');
});
await check('tester sends the same saved-rule structure without configuration writes', async () => {
mount([ordinary, hashing]); reply = { request: { cacheable: true }, response: { stored: true, ttl: 60, grace: 0 } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test');
assert.deepEqual(calls[0].body.vhost_rules, [ordinary, hashing]); assert.equal(dirty, 0);
});
await check('opening a branch marker allows zero actions and preserves every condition and guard', () => {
mount(flow); open(); assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0);
const copy = editor.read(); copy[0].vcl_flow.branches[0].any[0][0].values[0] = 'tampered';
copy[1].vcl_flow.guards[0].branch = 1;
assert.deepEqual(plain(editor.read()), flow); assert.equal(flow[0].vcl_flow.branches[0].any[0][0].values[0], 'old');
});
await check('structural controls are disabled and reject synthetic changes without flattening', () => {
const marker = card();
assert.ok(field('cacheRuleStage', marker).disabled); assert.ok(field('cacheRuleMatch', marker).disabled);
assert.ok(marker.querySelector('.cache-rule-stop input').disabled);
assert.ok(button('cacheRuleAddCondition', marker).disabled); assert.ok(button('cacheRuleAddAction', marker).disabled);
fill(field('cacheRuleStage', marker), 'deliver', 'change');
fill(field('cacheRuleMatch', marker), 'any', 'change');
assert.deepEqual(plain(editor.read()), flow); assert.equal(dirty, 0); assert.equal(notices.length, 2);
});
await check('editing an action and renaming a rule preserve branch references', () => {
mount(flow); const row = open(1);
fill(row.querySelector('input[placeholder="' + w.t('cacheRuleHeaderValue') + '"]'), 'reviewed');
fill(field('cacheRuleId', row), 'renamed-action', 'change');
const saved = plain(editor.read());
assert.equal(saved[1].actions[0].value, 'reviewed'); assert.equal(saved[1].id, 'renamed-action');
assert.deepEqual(saved.map(rule => rule.vcl_flow), flow.map(rule => rule.vcl_flow));
assert.equal(flow[1].actions[0].value, 'new');
});
await check('moving any member or dropping a flat rule cannot split a VCL block', () => {
mount([ordinary, ...flow, hashing]);
button('cacheRulesMoveDown', card(2)).click();
assert.deepEqual(plain(editor.read()), [ordinary, hashing, ...flow]);
drop(0, 3); assert.deepEqual(plain(editor.read()), [hashing, ...flow, ordinary]);
button('cacheRulesMoveUp', card(3)).click();
assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
const before = dirty; drop(0, 2); assert.equal(dirty, before); assert.deepEqual(plain(editor.read()), [...flow, hashing, ordinary]);
});
await check('enable controls change the complete block and leave unrelated rules alone', () => {
mount([ordinary, ...flow]);
const toggle = card(2).querySelector('.cache-rule-head input'); toggle.checked = false; toggle.dispatchEvent(new w.Event('change', { bubbles: true }));
assert.deepEqual(plain(editor.read()), [ordinary, ...flow.map(rule => ({ ...rule, enabled: false }))]);
assert.equal(dirty, 1);
});
await check('duplicate creates independent group and rule IDs; remove deletes the complete copy', () => {
mount([ordinary, ...flow]); button('cacheRulesFlowDuplicate', card(2)).click();
const saved = plain(editor.read()), copies = saved.slice(4);
assert.equal(saved.length, 7); assert.equal(new Set(saved.map(rule => rule.id)).size, 7);
assert.match(copies[0].vcl_flow.group, /^vcl-[a-f0-9]{32}$/); assert.notEqual(copies[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.equal(new Set(copies.map(rule => rule.vcl_flow.group)).size, 1);
assert.deepEqual(copies.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
button('cacheRulesFlowRemove', card(5)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...flow]);
});
await check('vhost targeting is updated atomically for the whole global VCL block', () => {
mount([ordinary, ...flow], 'global'); const row = open(2);
row.querySelector('.cache-rule-vhosts').dispatchEvent(new w.CustomEvent('choicechange', { detail: ['site-a', 'site-b'], bubbles: true }));
const saved = plain(editor.read()); assert.deepEqual(saved[0], ordinary);
assert.ok(saved.slice(1).every(rule => JSON.stringify(rule.vhosts) === '["site-a","site-b"]'));
const detached = editor.read(); detached[1].vhosts.push('tampered'); assert.equal(editor.read()[1].vhosts.length, 2);
});
await check('importing the same block again remaps IDs without changing its guards', async () => {
mount(flow); await importRules(flow);
const saved = plain(editor.read()), added = saved.slice(3);
assert.equal(saved.length, 6); assert.deepEqual(saved.slice(0, 3), flow);
assert.equal(new Set(saved.map(rule => rule.id)).size, 6); assert.notEqual(added[0].vcl_flow.group, flow[0].vcl_flow.group);
assert.deepEqual(added.map(rule => ({ ...rule.vcl_flow, group: 'vcl-fixture' })), flow.map(rule => rule.vcl_flow));
assert.equal(dirty, 1); assert.deepEqual(flow[1].vcl_flow.guards, [{ entry: 0, branch: 0 }]);
});
await check('partial import keeps the complete structure only after explicit acceptance', async () => {
mount([ordinary]); await importRules(flow, ['Unsupported log statement was omitted.']);
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
button('cacheRulesImportApplyPartial').click();
assert.deepEqual(plain(editor.read()), [ordinary, ...flow]); assert.equal(dirty, 1);
});
await check('incomplete import is rejected atomically and preserves existing rules', async () => {
mount([ordinary]); await importRules(flow.slice(0, 2));
assert.deepEqual(plain(editor.read()), [ordinary]); assert.equal(dirty, 0);
assert.match(editor.node.querySelector('.cache-rules-import-result .is-error').textContent, /incomplete or structurally changed/);
});
await check('reordered or incomplete saved metadata cannot be saved or accidentally moved', () => {
mount([flow[0], flow[2], flow[1], ordinary]);
assert.throws(() => editor.read(), /incomplete or structurally changed/);
button('cacheRulesMoveUp', card(3)).click(); assert.equal(dirty, 0); assert.equal(notices.length, 1);
assert.equal(card(3).querySelector('.cache-rule-title b').textContent, ordinary.name);
editor.set(flow.slice(0, 2)); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('tester and JSON export preserve the full imported program without executing in JavaScript', async () => {
mount(flow); reply = { request: { cacheable: false, reason: 'pass' } };
button('cacheRulesTesterRun').click(); await flush();
assert.equal(calls.length, 1); assert.equal(calls[0].url, '/api/cache/rules/test'); assert.deepEqual(calls[0].body.vhost_rules, flow);
assert.ok(button('cacheRulesExportJson')); assert.deepEqual(JSON.parse(editor.node.querySelector('.cache-rules-vcl').textContent), flow);
assert.throws(() => api.exportVcl(flow), /complete JSON export/); assert.equal(dirty, 0);
});
await check('a hash-stage imported action retains its phase when its action is edited', () => {
const hashFlow = { ...hashing, vcl_flow: { version: 1, group: 'vcl-hash', index: 0, count: 1 } };
mount([hashFlow]); const row = open();
const name = row.querySelector('input[placeholder="Accept-Language"]'); fill(name, 'X-Experiment');
assert.deepEqual(plain(editor.read()), [{ ...hashFlow, actions: [{ type: 'hash_header', name: 'X-Experiment' }] }]);
});
await check('nested guards and OR clauses survive editing and moving the complete program', () => {
const parent = { entry: 0, branch: 0 };
const nested = [
{ ...flow[0], vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', count: 5, branches: flow[0].vcl_flow.branches.slice(0, 1) } },
{ ...flow[0], id: 'nested-if', vcl_flow: { ...flow[0].vcl_flow, group: 'vcl-nested', index: 1, count: 5, guards: [parent], branches: [{ any: [[{ field: 'header', name: 'X-Inner', operator: 'exists' }], [{ field: 'path', operator: 'prefix', values: ['/public'] }]] }, { any: [[]] }] } },
{ ...flow[1], actions: [{ type: 'remove_request_header', name: 'X-Mode' }], vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 2, count: 5, guards: [parent, { branch: 0, entry: 1 }] } },
{ ...flow[1], id: 'nested-else', vcl_flow: { ...flow[1].vcl_flow, group: 'vcl-nested', index: 3, count: 5, guards: [{ branch: 0, entry: 0 }, { entry: 1, branch: 1 }] } },
{ ...flow[2], vcl_flow: { ...flow[2].vcl_flow, group: 'vcl-nested', index: 4, count: 5, guards: [parent] } },
];
mount([...nested, ordinary]); open(2);
assert.deepEqual(plain(editor.read()), [...nested, ordinary]);
button('cacheRulesMoveDown', card(2)).click(); assert.deepEqual(plain(editor.read()), [ordinary, ...nested]);
const invalid = structuredClone(nested); invalid[4].vcl_flow.guards.push({ entry: 1, branch: 0 });
editor.set(invalid); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
await check('cross-phase guards and altered branch markers are rejected before save', () => {
const wrongPhase = structuredClone(flow); wrongPhase[1].hash_stage = true;
mount(wrongPhase); assert.throws(() => editor.read(), /incomplete or structurally changed/);
const wrongMarker = structuredClone(flow); wrongMarker[0].actions = [{ type: 'pass' }];
editor.set(wrongMarker); assert.throws(() => editor.read(), /incomplete or structurally changed/);
});
console.log(`PASS: ${checks} cache/VCL editor DOM regression checks`);
dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
-130
View File
@@ -1,130 +0,0 @@
// Fast policy editor regressions using a DOM. Requires Node.js and jsdom.
// Run: node src/admin/web/tests/policy.dom.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const root = path.resolve(__dirname, '../../../..');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
const dom = new JSDOM('<html><body><form id="fixture"><main id="root"></main><button type="submit">Save</button></form></body></html>', { runScripts: 'outside-only', url: 'https://panel.example.test' });
const w = dom.window, d = w.document;
w.structuredClone = structuredClone;
w.t = key => translations[key] || key;
w.el = (tag, text, cls) => { const n = d.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n; };
let dirty = 0, bubbled = 0, calls = [], response = {}, pending = false, resolver;
w.api = async (url, options) => { calls.push({ url, body: options?.body ? JSON.parse(options.body) : null }); if (pending) return new Promise(resolve => { resolver = resolve; }); return structuredClone(response); };
d.getElementById('fixture').addEventListener('input', () => bubbled++);
w.eval(fs.readFileSync(path.join(root, 'src/admin/web/policy.js'), 'utf8'));
const plain = value => JSON.parse(JSON.stringify(value));
const api = w.rustProxyPolicy;
let editor, checks = 0;
const flush = () => new Promise(resolve => setImmediate(resolve));
function mount(value = {}, scope = 'vhost') { dirty = 0; bubbled = 0; calls = []; pending = false; editor = api.create({ value, scope, onChange: () => dirty++ }); d.getElementById('root').replaceChildren(editor.node); }
function button(key, within = editor.node) { const found = [...within.querySelectorAll('button')].find(n => n.textContent === w.t(key)); assert.ok(found, `button ${key}`); return found; }
function control(key, within = editor.node) { const found = [...within.querySelectorAll('input, textarea, select')].find(n => n.getAttribute('aria-label') === w.t(key)); assert.ok(found, `control ${key}`); return found; }
function fill(node, value, event = 'input') { node.value = value; node.dispatchEvent(new w.Event(event, { bubbles: true })); }
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('duplicate and empty header fields are preserved', () => {
assert.deepEqual(plain(api.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/')), [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.throws(() => api.headers('not a header'), /Invalid header/);
assert.throws(() => api.headers(' folded: header'), /Invalid header/);
});
await check('opening complex existing settings preserves all values', () => { mount(original); assert.deepEqual(plain(editor.read()), original); assert.equal(editor.node.querySelector('img'), null); });
await check('reordering rules preserves ACLs, maps, conditions and actions', () => {
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read()), { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw JSON round trip is lossless and malformed JSON prevents switching/save', () => {
mount(original); button('policyJson').click(); const raw = editor.node.querySelector('.policy-raw textarea');
assert.deepEqual(plain(editor.read()), original); fill(raw, '{broken'); assert.throws(() => editor.read());
button('policyVisual').click(); assert.equal(editor.node.querySelector('.policy-raw').hidden, false);
fill(raw, JSON.stringify(original)); button('policyVisual').click(); assert.deepEqual(plain(editor.read()), original);
});
await check('editing nested condition JSON is never discarded by reorder', () => {
mount(original); const condition = editor.node.querySelector('.policy-conditions textarea'); fill(condition, '{broken');
button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click(); assert.throws(() => editor.read());
assert.equal(editor.node.querySelector('.policy-rule').dataset.ruleId, 'one');
fill(condition, JSON.stringify({ acl: 'mobile' })); button('policyMoveDown', editor.node.querySelector('.policy-rule-heading')).click();
assert.deepEqual(plain(editor.read().rules[1].when), { acl: 'mobile' });
});
await check('first OR condition replaces the empty default group', () => {
mount(); button('policyAddRule').click(); const conditions = editor.node.querySelector('.policy-conditions');
fill(control('policyCombine', conditions), 'any', 'change'); button('policyAddCondition', conditions).click();
const expression = plain(editor.read().rules[0].when); assert.equal(expression.any.length, 1); assert.equal(expression.any[0].fetch, 'res.fhdr(Vary)');
});
await check('presets encode full-field count and final Vary normalization', () => {
mount(); button('policyPresetVary').click(); button('policyPresetNormalize').click();
const rules = editor.read().rules; assert.equal(rules[0].stage, 'backend_response'); assert.equal(rules[0].when.all.length, 3);
assert.deepEqual(plain(rules[0].when.all[0]), { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(plain(rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]); assert.equal(rules[1].stage, 'after_response');
});
await check('import requires review and explicit add; existing rules are retained', async () => {
mount(original); response = { policy: { rules: [{ ...original.rules[1], id: 'one' }] }, warnings: [] };
fill(control('policyHaproxySource'), 'http-after-response normalize-header Vary'); button('policyImportPreview').click(); await flush();
assert.deepEqual(plain(editor.read()), original); assert.equal(dirty, 0);
button('policyImportAdd').click(); const result = editor.read(); assert.equal(result.rules.length, 3); assert.equal(result.rules[2].id, 'imported-1');
assert.deepEqual(plain(result.acls), original.acls); assert.deepEqual(calls.map(c => c.url), ['/api/policy/import-haproxy']);
});
await check('name collisions reject imports atomically and special keys remain data', () => {
assert.throws(() => api.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'bad', actions: [] }] }), /mobile/);
const special = api.mergeImports({}, JSON.parse('{"acls":{"__proto__":{"all":[]}},"rules":[]}'));
assert.equal(Object.hasOwn(special.acls, '__proto__'), true); assert.equal(Object.getPrototypeOf(special.acls), Object.prototype);
assert.equal(editor.read().rules.length, 3);
});
await check('source edits invalidate a pending import preview', async () => {
mount(); response = { policy: { rules: [original.rules[1]] }, warnings: [] };
fill(control('policyHaproxySource'), 'source'); button('policyImportPreview').click(); await flush();
assert.equal(button('policyImportAdd').disabled, false); fill(control('policyHaproxySource'), 'modified'); assert.equal(button('policyImportAdd').disabled, true);
assert.equal(editor.read().rules.length, 0);
});
await check('server tester receives duplicate headers and renders trace as text', async () => {
mount({ rules: [original.rules[1]] });
response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {} };
button('policyRunTest').click(); await flush();
assert.equal(calls[0].url, '/api/policy/test'); assert.equal(calls[0].body.stage, 'after_response');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(editor.node.querySelectorAll('.policy-trace tbody tr').length, 1); assert.equal(editor.node.querySelector('.policy-test-output script'), null);
assert.match(editor.node.querySelector('.policy-test-output').textContent, /<script>/);
});
await check('tester inputs neither dirty nor invalidate the enclosing config form', async () => {
mount(); fill(control('policyVariables'), 'malformed'); button('policyRunTest').click(); await flush();
assert.equal(dirty, 0); assert.equal(bubbled, 0); assert.equal(control('policyVariables').form, null); assert.equal(d.getElementById('fixture').checkValidity(), true);
});
await check('pre_route is unavailable and rejected in a location draft', () => {
mount({}, 'location'); assert.equal(editor.node.querySelector('.policy-tester option[value="pre_route"]'), null);
button('policyJson').click(); fill(editor.node.querySelector('.policy-raw textarea'), JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.throws(() => editor.read(), /pre_route/);
});
await check('return and redirect are selectable only after request access checks', () => {
mount({ rules: [{ id: 'terminal', stage: 'pre_route', actions: [{ type: 'return', status: 200, body: 'existing draft' }] }] });
const action = control('policyAction', editor.node.querySelector('.policy-action'));
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, true);
assert.equal(action.querySelector('option[value="deny"]').disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
fill(control('policyStage', editor.node.querySelector('.policy-rule')), 'request', 'change');
for (const type of ['return', 'redirect']) assert.equal(action.querySelector(`option[value="${type}"]`).disabled, false);
assert.equal(editor.read().rules[0].actions[0].body, 'existing draft');
});
await check('in-flight test result is discarded when inputs change', async () => {
mount({ rules: [original.rules[1]] }); pending = true; button('policyRunTest').click(); await flush();
fill(control('policyHost'), 'changed.example'); resolver({ trace: [] }); await flush();
assert.match(editor.node.querySelector('.policy-test-output').textContent, /changed during evaluation/); pending = false;
});
await check('live counters use a read-only saved-config request and do not dirty drafts', async () => {
mount(); response = { revision: 7, scopes: [{ scope: 'vhost', vhost: 'site-a', rules: [{ id: 'vary', stage: 'after_response', matches: 32, errors: 1 }] }] };
button('policyRefreshCounters').click(); await flush();
assert.deepEqual(calls, [{ url: '/api/policy/stats', body: null }]); assert.equal(dirty, 0);
const output = editor.node.querySelector('.policy-counter-scroll').textContent; assert.match(output, /7/); assert.match(output, /site-a/); assert.match(output, /32/);
assert.equal(editor.read().rules.length, 0);
});
await check('separate editor instances keep separate drafts', () => {
const first = api.create({ value: original }), second = api.create({ value: { rules: [original.rules[1]] } });
button('policyAddRule', first.node).click(); assert.equal(first.read().rules.length, 3); assert.equal(second.read().rules.length, 1); assert.equal(original.rules.length, 2);
});
console.log(`PASS: ${checks} DOM policy editor regression checks`); dom.window.close();
})().catch(error => { console.error(error); dom.window.close(); process.exitCode = 1; });
-132
View File
@@ -1,132 +0,0 @@
// Component regression tests. Requires Node.js and Playwright Chromium.
// Run: node src/admin/web/tests/policy.test.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '../../../..');
const policyFile = path.join(root, 'src/admin/web/policy.js');
const translations = JSON.parse(fs.readFileSync(path.join(root, 'langs/en_US.json'), 'utf8')).translations;
let checks = 0;
async function check(name, fn) { await fn(); checks++; console.log(`ok ${checks} - ${name}`); }
(async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.POLICY_TEST_CHROMIUM ? { executablePath: process.env.POLICY_TEST_CHROMIUM } : {}) });
try {
const page = await browser.newPage({ viewport: { width: 1180, height: 900 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.setContent('<html><body style="margin:20px"><form id="fixture"><div id="root"></div><button type="submit">Save</button></form></body></html>');
await page.evaluate(translations => {
window.translations = translations;
window.t = key => translations[key] || key;
window.el = (tag, text, cls) => { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; };
window.changed = 0; window.parentChanged = 0; window.calls = [];
document.getElementById('fixture').addEventListener('input', () => window.parentChanged++);
window.api = async (url, options) => { const body = options?.body ? JSON.parse(options.body) : null; window.calls.push({ url, body }); if (window.pendingApi) return new Promise(resolve => { window.resolveApi = resolve; }); return structuredClone(window.apiResult || {}); };
}, translations);
for (const file of ['00-tokens.css', '10-base.css', '55-policy.css']) await page.addStyleTag({ path: path.join(root, 'src/admin/web/css', file) });
await page.addScriptTag({ path: policyFile });
const mount = async (value = {}, scope = 'vhost') => page.evaluate(({ value, scope }) => {
window.changed = 0; window.parentChanged = 0; window.calls = [];
window.editor = window.rustProxyPolicy.create({ value, scope, onChange: () => window.changed++ });
document.getElementById('root').replaceChildren(window.editor.node);
}, { value, scope });
await check('header parser preserves repeated fields and empty values', async () => {
const values = await page.evaluate(() => window.rustProxyPolicy.headers('Vary: Accept-Encoding\nVary: Accept,Accept-Encoding\nX-Empty:\nX-URL: https://example.test:8443/'));
assert.deepEqual(values, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }, { name: 'X-Empty', value: '' }, { name: 'X-URL', value: 'https://example.test:8443/' }]);
assert.equal(await page.evaluate(() => { try { window.rustProxyPolicy.headers('not a header'); return false; } catch { return true; } }), true);
});
const original = { acls: { mobile: { fetch: 'req.fhdr(User-Agent)', operator: 'contains', values: ['mobile'], ignore_case: true } }, maps: { devices: { kind: 'exact', entries: [{ key: 'a', value: 'b' }], default: 'fallback', ignore_case: false } }, rules: [
{ id: 'one', name: '<img src=x onerror=alert(1)>', enabled: false, stage: 'request', when: { any: [{ acl: 'mobile' }, { not: { fetch: 'req.fhdr(X-Test)', operator: 'exists', values: [] } }] }, actions: [{ type: 'set_var', name: 'txn.device', value: '%[req.fhdr(User-Agent),lower,map(devices)]' }], stop: true },
{ id: 'two', name: 'Response', enabled: true, stage: 'after_response', when: { all: [] }, actions: [{ type: 'normalize_header', name: 'Vary' }], stop: false }
] };
await check('complex rules, ACLs and maps survive opening and reading', async () => {
await mount(original); assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
assert.equal(await page.locator('img').count(), 0);
});
await check('rule reorder preserves every condition, action and definition', async () => {
await page.locator('.policy-rule').first().locator('.policy-rule-heading').getByRole('button', { name: 'Move down', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.deepEqual(value, { ...original, rules: [original.rules[1], original.rules[0]] });
});
await check('raw/visual round trip is lossless and invalid raw JSON blocks reading', async () => {
await mount(original); await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.locator('.policy-raw textarea').fill('{broken');
assert.equal(await page.evaluate(() => { try { window.editor.read(); return false; } catch { return true; } }), true);
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.equal(await page.locator('.policy-raw').isVisible(), true);
await page.locator('.policy-raw textarea').fill(JSON.stringify(original));
await page.getByRole('button', { name: 'Rule builder', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
});
await check('Vary preset keeps field-count and separate full-field conditions', async () => {
await mount(); await page.getByRole('button', { name: 'Fix duplicate Vary (exact match)', exact: true }).click();
const rule = await page.evaluate(() => window.editor.read().rules[0]);
assert.equal(rule.stage, 'backend_response'); assert.equal(rule.when.all.length, 3);
assert.deepEqual(rule.when.all[0], { fetch: 'res.fhdr_cnt(Vary)', operator: 'eq', values: ['2'] });
assert.deepEqual(rule.actions, [{ type: 'set_header', name: 'Vary', value: 'Accept, Accept-Encoding' }]);
await page.getByRole('button', { name: 'Normalize Vary (preserve dimensions)', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read().rules[1].actions), [{ type: 'normalize_header', name: 'Vary' }]);
});
await check('import preview never silently activates or replaces existing rules', async () => {
await mount(original); await page.locator('.policy-import > summary').click();
const incoming = { acls: {}, maps: {}, rules: [{ ...original.rules[1], id: 'one' }] };
await page.evaluate(policy => { window.apiResult = { policy, warnings: [] }; }, incoming);
await page.getByLabel('HAProxy source', { exact: true }).fill('http-after-response normalize-header Vary');
await page.getByRole('button', { name: 'Validate and preview import', exact: true }).click();
assert.deepEqual(await page.evaluate(() => window.editor.read()), original);
await page.getByRole('button', { name: 'Add imported rules to draft', exact: true }).click();
const value = await page.evaluate(() => window.editor.read());
assert.equal(value.rules.length, 3); assert.equal(value.rules[2].id, 'imported-1'); assert.deepEqual(value.acls, original.acls);
assert.deepEqual(await page.evaluate(() => window.calls.map(call => call.url)), ['/api/policy/import-haproxy']);
});
await check('conflicting ACL imports are rejected atomically', async () => {
const value = await page.evaluate(original => {
try { window.rustProxyPolicy.mergeImports(original, { acls: { mobile: { all: [] } }, rules: [{ id: 'unsafe', actions: [] }] }); return null; }
catch (error) { return error.message; }
}, original);
assert.match(value, /mobile/);
assert.equal(await page.evaluate(() => window.editor.read().rules.length), 3);
});
await check('tester uses server API and preserves duplicate request/response fields', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
const response = { request: { headers: [{ name: 'X-Unsafe', value: '<script>throw Error(1)</script>' }] }, response: { status: 200, headers: [{ name: 'Vary', value: 'Accept-Encoding, Accept' }] }, trace: [{ rule: 'two', stage: 'after_response', matched: true, actions: ['normalize_header'], warnings: [] }], variables: {}, cache: {} };
await page.evaluate(response => { window.apiResult = response; }, response);
await page.getByRole('button', { name: 'Run test', exact: true }).click();
const calls = await page.evaluate(() => window.calls); assert.equal(calls[0].url, '/api/policy/test');
assert.deepEqual(calls[0].body.response.headers, [{ name: 'Vary', value: 'Accept-Encoding' }, { name: 'Vary', value: 'Accept,Accept-Encoding' }]);
assert.equal(calls[0].body.stage, 'after_response'); assert.equal(await page.locator('.policy-trace tbody tr').count(), 1);
assert.match(await page.locator('.policy-test-output').innerText(), /<script>/); assert.equal(await page.locator('.policy-test-output script').count(), 0);
});
await check('tester inputs do not dirty or invalidate the configuration form', async () => {
await mount(); await page.locator('.policy-tester > summary').click();
await page.getByLabel('Transaction variables (JSON string values)', { exact: true }).fill('malformed');
await page.getByRole('button', { name: 'Run test', exact: true }).click();
assert.equal(await page.evaluate(() => window.changed), 0); assert.equal(await page.evaluate(() => window.parentChanged), 0);
assert.equal(await page.evaluate(() => document.getElementById('fixture').checkValidity()), true);
});
await check('location editor excludes pre_route and refuses raw configuration using it', async () => {
await mount({}, 'location');
assert.equal(await page.locator('.policy-tester option[value="pre_route"]').count(), 0);
await page.getByRole('button', { name: 'Policy JSON', exact: true }).click();
await page.locator('.policy-raw textarea').fill(JSON.stringify({ rules: [{ id: 'bad', stage: 'pre_route', actions: [] }] }));
assert.match(await page.evaluate(() => { try { window.editor.read(); return ''; } catch (error) { return error.message; } }), /pre_route/);
});
await check('asynchronous tester rejects stale results after input changes', async () => {
await mount({ rules: [original.rules[1]] }); await page.locator('.policy-tester > summary').click();
await page.evaluate(() => { window.pendingApi = true; });
await page.getByRole('button', { name: 'Run test', exact: true }).click();
await page.getByLabel('Host', { exact: true }).fill('different.example');
await page.evaluate(() => { window.pendingApi = false; window.resolveApi({ trace: [] }); });
await page.getByText('The draft or test input changed during evaluation. Run the test again.', { exact: true }).waitFor();
});
await check('responsive policy editor remains within the viewport', async () => {
await mount({ rules: [original.rules[1]] });
await page.setViewportSize({ width: 390, height: 850 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= 390), true);
if (process.env.POLICY_TEST_SCREENSHOT) await page.screenshot({ path: process.env.POLICY_TEST_SCREENSHOT, fullPage: true });
});
assert.deepEqual(errors, []); console.log(`PASS: ${checks} policy editor regression checks`);
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
+80 -23
View File
@@ -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: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", policyTitle: "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));
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", policyTitle: "headers", vhHeadersPreview: "headers", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "details"; 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,53 @@ 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"], ["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 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"]]) { 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 jsonDrawer(parent, { name, titleKey, helpKey, value, maxLength, validate = value => value, apply }) {
const node = el("details", undefined, "vh-wide vh-json-editor"), summary = el("summary"), status = el("span", undefined, "vh-json-status");
node.dataset.jsonSection = name; summary.append(text("span", titleKey), status); node.append(summary);
const body = el("div", undefined, "vh-grid vh-json-body"); node.append(body); parent.append(node); note(body, helpKey);
const target = document.createElement("textarea"); target.name = name; target.hidden = true; target.value = JSON.stringify(value, null, 2); body.append(target);
const source = field(body, `${name}-json-draft`, titleKey, target.value, "textarea", { rows: 10, maxLength }); source.classList.add("vh-json-source"); source.setAttribute("aria-label", t(titleKey));
const toolbar = el("div", undefined, "vh-wide vh-json-toolbar"), message = el("p", undefined, "fine vh-wide vh-json-message"); message.hidden = true; message.setAttribute("role", "status");
let baseline = target.value, pending = false;
const parse = () => validate(JSON.parse(source.value));
const fail = error => { message.textContent = error.message || t("vhJsonInvalid"); message.hidden = false; message.classList.add("is-error"); source.setCustomValidity(message.textContent); };
const update = () => {
pending = source.value !== baseline; status.textContent = t(pending ? "vhJsonDraft" : "vhJsonSynced"); node.classList.toggle("has-json-draft", pending);
applyButton.disabled = !pending; source.setCustomValidity(pending ? t("vhJsonPending") : "");
};
const refresh = () => { if (pending) return; baseline = target.value; source.value = baseline; update(); };
const applyButton = button("vhJsonApply", () => {
try {
if (target.value !== baseline) throw Error(t("vhJsonConflict"));
const next = parse(); apply(next); target.value = JSON.stringify(next, null, 2);
pending = false; refresh(); message.classList.remove("is-error"); message.textContent = t("vhJsonApplied"); message.hidden = false;
target.dispatchEvent(new Event("change", { bubbles: true })); changed();
} catch (error) { fail(error); }
}, "primary");
const formatButton = button("vhJsonFormat", () => { try { const next = parse(); source.value = JSON.stringify(next, null, 2); message.hidden = true; update(); if (pending) changed(); } catch (error) { fail(error); } });
const reloadButton = button("vhJsonReload", async () => {
if (pending && !(await appConfirm(t("vhJsonReloadConfirm"), { danger: true, confirmLabel: t("discardAction") }))) return;
pending = false; refresh(); message.hidden = true;
});
toolbar.append(applyButton, formatButton, reloadButton); body.append(toolbar, message);
source.addEventListener("input", () => { message.hidden = true; update(); if (pending) { try { parse(); } catch (error) { fail(error); } } });
source.addEventListener("invalid", () => { node.open = true; activateTab(node.closest(".vh-group")?.dataset.tab || "details"); });
node.addEventListener("toggle", () => { if (node.open) refresh(); }); update();
return { node, target, refresh };
}
function validateInlineAcl(value) {
if (value === null) return value;
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !["default", "rules"].includes(key))
|| (value.default !== undefined && !["allow", "deny"].includes(value.default))
|| (value.rules !== undefined && (!Array.isArray(value.rules) || value.rules.length > 128 || value.rules.some(rule => !rule || typeof rule !== "object" || Array.isArray(rule)
|| Object.keys(rule).some(key => !["network", "action"].includes(key)) || typeof rule.network !== "string" || !rule.network.trim() || rule.network.length > 254 || !["allow", "deny"].includes(rule.action))))) throw Error(t("vhJsonInvalidAcl"));
return value;
}
function validateLocations(value) {
if (!Array.isArray(value) || value.length > 64 || value.some(route => !route || typeof route !== "object" || Array.isArray(route))) throw Error(t("vhJsonInvalidPaths"));
return value;
}
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() {
@@ -80,14 +126,14 @@ function validateHeaders(value) {
const fail = () => { throw new Error(t("headersInvalid")); };
if (!value || Array.isArray(value) || typeof value !== "object" || Object.keys(value).some(k => !["request", "response"].includes(k))) fail();
for (const direction of ["request", "response"]) {
const rules = value[direction] || []; if (!Array.isArray(rules) || rules.length > 32) fail(); for (const rule of rules) {
const rules = Object.hasOwn(value, direction) ? value[direction] : []; if (!Array.isArray(rules) || rules.length > 32) fail(); for (const rule of rules) {
if (!rule || typeof rule !== "object" || Object.keys(rule).some(k => !["op", "name", "value"].includes(k)) || !["set", "append", "remove"].includes(rule.op) || typeof rule.name !== "string" || rule.name.length > 128 || !/^[-!#$%&'*+.^_`|~0-9A-Za-z]+$/.test(rule.name)) fail();
const name = rule.name.toLowerCase(); if (["host", "connection", "content-length", "transfer-encoding", "te", "trailer", "content-encoding", "content-range", "upgrade", "keep-alive", "proxy-connection", "proxy-authorization", "proxy-authenticate", "forwarded", "x-real-ip", "x-request-id", "x-rust-proxy-backend", "x-rust-proxy-backend-time", "x-rustproxy-backend-time"].includes(name) || name.startsWith("x-forwarded-") || name.startsWith("sec-websocket-")) throw new Error(t("headersProtected"));
if (rule.op === "remove") { if (Object.hasOwn(rule, "value") && rule.value !== null) fail(); } else if (typeof rule.value !== "string" || rule.value.length > 8192 || /[\r\n\0]/.test(rule.value)) fail();
}
} return value;
}
// Header value variables (src/headers/mod.rs Var::ALL); true = response rules only.
const HEADER_VARIABLES = [["srv_id", false], ["srv_url", false], ["location", false], ["vhost", false], ["lb_algorithm", false], ["hash_key", false], ["client_ip", false], ["country", false], ["req_id", false], ["method", false], ["host", false], ["path", false], ["cache_status", true], ["backend_time", true]];
const DIAGNOSTIC_PRESETS = [
{ key: "hdrPresetServedBy", direction: "response", rule: { op: "set", name: "X-Served-By", value: "%[srv_id]" } },
@@ -119,8 +165,6 @@ 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; }
// 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"]] });
@@ -140,7 +184,6 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
};
adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction);
block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header"));
// %[variable] chips insert into the last focused value field of this direction.
const chips = el("div", undefined, "hdr-vars"); chips.append(text("span", "hdrVariables", "hdr-vars-label"));
let lastValue = null; rows.addEventListener("focusin", event => { if (event.target.name === "rule-value") lastValue = event.target; });
for (const [name, responseOnly] of HEADER_VARIABLES) {
@@ -155,19 +198,25 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
}
block.append(chips);
}
const set = data => {
const value = validateHeaders(data);
for (const direction of ["request", "response"]) for (const rule of value[direction] || []) {
const result = rule.op === "remove" ? {} : headerValueCheck(rule.value, direction);
if (result.error) throw Error(result.error);
}
for (const direction of ["request", "response"]) {
holders[direction].replaceChildren();
for (const rule of value[direction] || []) adders[direction](rule);
renumber(direction);
}
target.value = JSON.stringify(value, null, 2); target.setCustomValidity(""); onChange();
};
target.addEventListener("input", () => {
try {
const value = validateHeaders(JSON.parse(target.value));
for (const direction of ["request", "response"]) {
holders[direction].replaceChildren();
for (const rule of value[direction] || []) adders[direction](rule);
renumber(direction);
}
target.setCustomValidity(""); onChange();
} catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); }
try { set(JSON.parse(target.value)); }
catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); }
});
note(parent, "locationHeadersHelp"); note(parent, "hdrVariablesHelp");
return { read: () => validateHeaders(JSON.parse(target.value)), add: (direction, rule) => { adders[direction](rule); renumber(direction); sync(); } };
return { read: () => validateHeaders(JSON.parse(target.value)), set, add: (direction, rule) => { adders[direction](rule); renumber(direction); sync(); } };
}
function suspendDraft() {
const state = {
@@ -185,7 +234,7 @@ function restoreDraft(state) {
editing = state.editing; revision = state.revision; basicEditor = state.basicEditor; locationsReader = state.locationsReader; aclControl = state.aclControl;
readBindings = state.readBindings; readHosts = state.readHosts; countryRatesReader = state.countryRatesReader; uaRatesReader = state.uaRatesReader || (() => []); pagesEditor = state.pagesEditor; backendHealthEditorControl = state.backendHealthEditorControl || null;
vhostPolicyEditor = state.vhostPolicyEditor || null; vhostCacheRulesEditor = state.vhostCacheRulesEditor || null;
vhostHeadersControl = state.vhostHeadersControl || null; headersPreviewControl = state.headersPreviewControl || null; presetsRefresh = state.presetsRefresh || (() => {});
vhostHeadersControl = state.vhostHeadersControl || null; headersPreviewControl = state.headersPreviewControl || null; presetsRefresh = state.presetsRefresh || (() => { });
stagedCertificates = state.stagedCertificates || []; uploading = state.uploading === true; initialized = true; dirty = true; $("vhost-editing").textContent = state.label;
if (!dialog.open) dialog.showModal(); if (latestStatus) renderStatus(latestStatus);
}
@@ -342,10 +391,13 @@ function debugOriginIssues(members) {
function aclEditor(parent, initial, onChange = () => { }) {
const enabled = field(parent, "acl-use", "aclUse", !!initial, "checkbox", { switch: true }), body = el("div", undefined, "vh-wide vh-grid"); parent.append(body);
const policy = field(body, "acl-default", "aclDefault", initial?.default || "deny", "select", { values: [["deny", "vhDeny"], ["allow", "aclAllow"]] }), rows = el("div", undefined, "vh-wide"); body.append(rows);
function add(value = { network: "", action: "allow" }) { const row = el("div", undefined, "acl-rule"); field(row, "network", "aclNetwork", value.network, "text", { maxLength: 64 }); field(row, "action", "aclAction", value.action, "select", { values: [["allow", "aclAllow"], ["deny", "vhDeny"]] }); row.append(button("remove", () => { row.remove(); onChange(); })); rows.append(row); }
function add(value = { network: "", action: "allow" }) { const row = el("div", undefined, "acl-rule"); field(row, "network", "aclNetwork", value.network, "text", { maxLength: 254 }); field(row, "action", "aclAction", value.action, "select", { values: [["allow", "aclAllow"], ["deny", "vhDeny"]] }); row.append(button("remove", () => { row.remove(); onChange(); })); rows.append(row); }
body.append(button("aclAdd", () => { add(); onChange(); })); for (const rule of initial?.rules || []) add(rule);
const sync = () => { body.hidden = !enabled.checked; onChange(); }; enabled.addEventListener("change", sync); body.addEventListener("input", onChange); body.addEventListener("change", onChange); body.hidden = !enabled.checked;
note(parent, "aclHelp"); return { read: () => enabled.checked ? { default: policy.value, rules: [...rows.children].map(r => ({ network: str("network", r), action: str("action", r) })) } : null };
note(parent, "aclHelp"); return {
read: () => enabled.checked ? { default: policy.value, rules: [...rows.children].map(r => ({ network: str("network", r), action: str("action", r) })) } : null,
set: value => { validateInlineAcl(value); enabled.checked = value !== null; policy.value = value?.default || "deny"; rows.replaceChildren(); for (const rule of value?.rules || []) add(rule); body.hidden = !enabled.checked; onChange(); }
};
}
function openLocationHelp(topic = "locations") {
const dialog = $("location-help-dialog"), title = $("location-help-title"), body = $("location-help-body");
@@ -375,7 +427,7 @@ function openLocationHelp(topic = "locations") {
dialog.showModal();
}
const LOCATION_GROUP = "__group__";
function locationsEditor(parent, values) {
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(); });
@@ -412,7 +464,7 @@ function locationsEditor(parent, values) {
};
});
}
function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); changed(); } catch { } tester?.run(); }
function sync() { 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) {
if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; }
@@ -588,6 +640,11 @@ function locationsEditor(parent, values) {
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);
read("paths").addEventListener("change", () => { try { const data = JSON.parse(str("paths")); if (!Array.isArray(data) || data.length > 64) return; reloading = true; rows.replaceChildren(); for (const value of data) add(value); } catch { } finally { reloading = false; } });
readRows.set = data => {
validateLocations(data); const previous = [...rows.childNodes]; reloading = true;
try { rows.replaceChildren(); for (const value of data) add(value); readRows(); tester?.run(); }
catch (error) { rows.replaceChildren(...previous); throw error; }
finally { reloading = false; }
};
sync(); return readRows;
}
+20 -12
View File
@@ -207,10 +207,12 @@ function load(value = defaults(), migrationIds = [], show = true) {
g = group("vhHeadersPreview"); headersPreviewControl = headersPreview(g);
g = group("vhBackendDiagnostics");
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: "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");
@@ -306,8 +308,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
profileBox.append(multiWarning); aclFields.append(profileBox); note(aclFields, "vhAclProfileHelp");
const inlineAclFields = subsection(g, "vhIpAccess");
aclControl = aclEditor(inlineAclFields, value.acl, () => { if (aclControl) read("acl").value = JSON.stringify(aclControl.read(), null, 2); });
const aclJson = jsonDrawer(inlineAclFields, { name: "acl", titleKey: "vhAclJson", helpKey: "vhAclJsonHelp", value: value.acl ?? null, maxLength: 32768, validate: validateInlineAcl, apply: data => aclControl.set(data) });
aclControl = aclEditor(inlineAclFields, value.acl, () => { if (aclControl) { aclJson.target.value = JSON.stringify(aclControl.read(), null, 2); aclJson.refresh(); changed(); } });
note(inlineAclFields, "vhInlineAclHelp");
inlineAclFields.append(aclJson.node);
const methodFields = subsection(g, "vhTrafficMethodsSection");
field(methodFields, "method-mode", "vhMethodMode", methodPolicy.mode || "off", "select", { values: [["off", "vhOff"], ["allow", "locationMethodAllow"], ["block", "locationMethodBlock"]] });
@@ -360,14 +364,13 @@ function load(value = defaults(), migrationIds = [], show = true) {
field(uaBlockingFields, "ua-block-enabled", "vhUaBlockEnabled", uaBlock.enabled === true, "checkbox", { switch: true });
field(uaBlockingFields, "ua-block-patterns", "vhUaBlockPatterns", (uaBlock.patterns || []).join("\n"), "textarea", { rows: 4, maxLength: 32768 });
note(uaBlockingFields, "vhUaBlockHelp");
g = group("vhAdvanced", true); field(g, "paths", "vhPaths", JSON.stringify(value.routes || [], null, 2), "textarea", { rows: 5, maxLength: 131072 });
field(g, "acl", "vhAcl", JSON.stringify(value.acl ?? null, null, 2), "textarea", { rows: 5, maxLength: 32768 });
field(g, "headers", "vhHeaders", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 5, maxLength: 65536 });
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");
locationsReader = locationsEditor(g, value.routes || []);
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);
g = group("vhSsl");
const certificateRow = el("div", undefined, "vh-wide vh-certificate-select-row"); g.append(certificateRow);
const selector = field(certificateRow, "certificate-id", "vhCertificate", value.certificate_id || "", "select");
@@ -578,7 +581,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
};
transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
note(transformOptions, "vhTransformHelp");
g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor"); vhostHeadersControl = headerEditors(g, value.headers || {});
g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor");
const headersJson = jsonDrawer(g, { name: "headers", titleKey: "vhHeadersJson", helpKey: "vhHeadersJsonHelp", value: value.headers || {}, maxLength: 65536, validate: validateHeaders, apply: data => vhostHeadersControl.set(data) });
vhostHeadersControl = headerEditors(g, value.headers || {}, headersJson.target, () => { changed(); headersJson.refresh(); });
g.append(headersJson.node);
g = group("policyTitle"); vhostPolicyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "vhost", onChange: changed }); g.append(vhostPolicyEditor.node);
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();
@@ -657,12 +663,14 @@ function collect() {
authentication: selectedAuthentication().provider === "none" ? null : selectedAuthentication(),
tinyauth: { enabled: selectedAuthentication().provider === "tinyauth" && selectedAuthentication().method === "forward_auth", url: str("auth-url"), login_url: str("auth-login"), allow_private: yes("auth-private"), redirect_forbidden: yes("auth-redirect-forbidden"), connect_timeout_seconds: num("auth-connect"), timeout_seconds: num("auth-timeout"), request_headers: lines(str("auth-request-headers")), response_headers: lines(str("auth-response-headers")), address_allowlist: lines(str("auth-allowlist")), tls_ca_pem: nullable("auth-ca") },
authelia: readForwardProvider("authelia"), authentik: readForwardProvider("authentik"),
oidc: { enabled: selectedAuthentication().method === "oidc", issuer_url: str("oidc-issuer"), backend_url: str("oidc-backend"),
oidc: {
enabled: selectedAuthentication().method === "oidc", issuer_url: str("oidc-issuer"), backend_url: str("oidc-backend"),
redirect_url: str("oidc-redirect"), client_id: str("oidc-client"),
client_secret: str("oidc-secret"), session_secret: str("oidc-session"), scopes: str("oidc-scopes"),
allow_private: yes("oidc-private"), address_allowlist: lines(str("oidc-allowlist")),
tls_ca_pem: nullable("oidc-ca"), connect_timeout_seconds: num("oidc-connect"),
timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl") },
timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl")
},
backends: members, routes: paths, acl, headers, policy: vhostPolicyEditor ? vhostPolicyEditor.read() : {},
load_balancing: {
algorithm: str("algorithm"), ...(vhostBalancingControl?.hash() ? { hash: vhostBalancingControl.hash() } : {}), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") },
+3 -5
View File
@@ -92,7 +92,7 @@ function refreshVhostBackendPopup(status = latestStatus) {
scheme = url.protocol.replace(":", "").toUpperCase();
const port = url.port || (scheme === "HTTPS" ? "443" : scheme === "HTTP" ? "80" : "");
address = `${url.hostname}${port ? `:${port}` : ""}`;
} catch { }
} catch { }
const upstream = upstreamProtocolBadgeText(backend, member);
const protocol = `${scheme} · ${upstream.mode}${upstream.observed ? ` → ${upstream.observed}` : ""}`;
const statusCode = Number(member?.last_status);
@@ -225,9 +225,7 @@ function syncPoolSortDirection() {
control.setAttribute("aria-label", t(poolTablePrefs.descending ? "backendSortDescending" : "backendSortAscending"));
}
}
// The backend pool and backend overview tables live on Overview. Rebuilding
// them on every live snapshot while another panel is shown cost tens of
// milliseconds per update; defer them until Overview is shown again.
let overviewViewsPending = false;
const overviewViewsHidden = () => typeof currentPanel !== "undefined" && currentPanel !== "overview";
function flushOverviewViews() { if (!overviewViewsPending) return; overviewViewsPending = false; if (latestStatus) renderStatus(latestStatus); else applyPoolTableView(); }
@@ -913,7 +911,7 @@ form.addEventListener("submit", async event => {
const healthPanel = invalid.closest(".vh-backend-health-panel");
if (healthPanel) backendHealthEditorControl?.reveal([...form.querySelector(".vh-members").children].find(row => row.memberHealthPanel === healthPanel));
activateTab(invalid.closest(".vh-group")?.dataset.tab || "details");
const details = invalid.closest("details"); if (details) details.open = true;
for (let parent = invalid.parentElement; parent && parent !== form; parent = parent.parentElement) if (parent.tagName === "DETAILS") parent.open = true;
invalid.reportValidity(); return;
}
if (revision !== envelope.revision) { toast(t("stale"), true); return; }
+13 -4
View File
@@ -542,13 +542,22 @@ async fn run(
println!(
" ACME: {} certificate(s){}, {} via {}; state in {}",
acme.certificates.len(),
if acme.auto { " + automatic for vhost hosts" } else { "" },
if acme.auto {
" + automatic for vhost hosts"
} else {
""
},
acme.environment,
acme.provider,
data_dir.join("certs").join(rust_proxy::runtime::HEADLESS_ACME_STATE).display()
data_dir
.join("certs")
.join(rust_proxy::runtime::HEADLESS_ACME_STATE)
.display()
);
println!(" Renew: rust-proxy --headless tls renew [--force] [--id NAME]");
if acme.provider == "http01" && !state.active_listeners.iter().any(|listener| !listener.tls) {
if acme.provider == "http01"
&& !state.active_listeners.iter().any(|listener| !listener.tls)
{
tracing::warn!("ACME HTTP-01 needs a plain HTTP listener reachable on port 80");
}
}
@@ -586,7 +595,7 @@ async fn run(
println!(" Sign in with your administrator account.");
}
println!(" Source: https://git.linuxiarz.pl/gru/RustProxy");
println!(" Packages: https://rustproxy.linuxiarz.pl/");
println!(" Packages: https://repo.linuxiarz.pl/");
println!(" Data: {}\n Stop: Ctrl+C\n", data_dir.display());
if state
.active_listeners