From 96eec3b1c6198884b46cb32a01f02c4af1bc72ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Mon, 23 Nov 2026 12:52:41 +0100 Subject: [PATCH] 0.41.0 --- CHANGELOG.md | 3 +- docs/LOAD_BALANCING.md | 2 +- docs/RESPONSE_DELIVERY.md | 2 +- docs/VHOSTS.md | 2 +- langs/en_US.json | 43 +++++-- langs/pl_pl.json | 43 +++++-- src/admin/router.rs | 1 + src/admin/web/css/40-editors.css | 177 ++++++++++++++++++++++++++++ src/admin/web/css/70-responsive.css | 5 + src/admin/web/vhosts/core.js | 36 +++--- src/admin/web/vhosts/editor.js | 34 ++++-- src/admin/web/vhosts/headers-tab.js | 136 +++++++++++++++++++++ 12 files changed, 440 insertions(+), 44 deletions(-) create mode 100644 src/admin/web/vhosts/headers-tab.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d966fb..382f1b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ Release history focused on **features, settings, default behavior, compatibility - **Rules for the whole host:** the new match type `any` (requires at least one condition) applies to every path of the Vhost and ranks like a regular expression — e.g. office network + staff cookie → `office` backends for the whole site. Combined with the 0.40.2 backend groups and per-location balancing this covers frontend-level and path-level `use_backend` rules. - **Correctness and caching:** conditional locations are selected after the final client address and (when a condition needs it) the country are known; earlier stages and proactive cache refreshes only consider unconditional locations, and the response layer uses the finally selected location. Responses of conditional locations are never cached (`cache` must be inherit/off), so a cached unconditional response is never served to a request that matches a conditional location. - **Panel:** each location has a **Conditions** section (source, name, operator, values one per line, NOT, ignore case), an **Add rule for the whole host** button, **↑ / ↓** buttons to order locations, condition counts in the summary and a **Test routing** panel that evaluates the unsaved draft: method, URL, client IP, country and headers → winning location, path ✓/✗ and every condition ✓/✗ for all locations, the target backend (including the consistent-hash member) and the cache bypass. English and Polish texts added. -- **Variables in header values (diagnostic headers, HAProxy `set-header X-S %[srv_id]` style):** `set`/`append` values in global, Vhost and location header rules may contain `%[srv_id]`, `%[srv_url]`, `%[location]`, `%[vhost]`, `%[lb_algorithm]`, `%[hash_key]`, `%[client_ip]`, `%[country]`, `%[req_id]`, `%[method]`, `%[host]`, `%[path]` and, in response rules, `%[cache_status]` and `%[backend_time]`. Rules with variables are rendered per request and applied last: request rules after backend selection (so the origin can receive e.g. `X-Shard: mp3_2`), response rules at final delivery after cache handling — they are never stored in cached objects. Missing values render as `-`; a rendered value that is not a valid header value skips the header. Unknown variables, unterminated `%[` and response-only variables in request rules are rejected. Header-rule editors show clickable variable chips, and **Backends → Backend diagnostics** gains one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend). Rules without `%[` behave exactly as before. See [Variables in header values](docs/RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). +- **Variables in header values (diagnostic headers, HAProxy `set-header X-S %[srv_id]` style):** `set`/`append` values in global, Vhost and location header rules may contain `%[srv_id]`, `%[srv_url]`, `%[location]`, `%[vhost]`, `%[lb_algorithm]`, `%[hash_key]`, `%[client_ip]`, `%[country]`, `%[req_id]`, `%[method]`, `%[host]`, `%[path]` and, in response rules, `%[cache_status]` and `%[backend_time]`. Rules with variables are rendered per request and applied last: request rules after backend selection (so the origin can receive e.g. `X-Shard: mp3_2`), response rules at final delivery after cache handling — they are never stored in cached objects. Missing values render as `-`; a rendered value that is not a valid header value skips the header. Unknown variables, unterminated `%[` and response-only variables in request rules are rejected. Header-rule editors show clickable variable chips, and **Headers → Backend diagnostics** gains one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend). Rules without `%[` behave exactly as before. See [Variables in header values](docs/RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). +- **Vhost editor — new Headers tab:** *Backend diagnostics* (moved from Backends), *Response identity and diagnostics* and the custom request/response header rules (both moved from Security) now share a **Headers** tab; Security keeps traffic policy, HSTS/security headers and User-Agent blocking. The tab opens with a **live header preview** of the unsaved draft — what RustProxy adds, changes or removes towards the backend and towards the client, with the source of each header (global, vhost, location, diagnostics), example values for `%[variables]` and selectable example backend, location and cache result (a `HIT` shows that no request reaches a backend). Diagnostic switches are cards that show the exact header they produce (the backend header is correctly labelled `X-Rust-Proxy-Backend`), diagnostic presets that already exist are greyed out, and header rules are compact one-line rows with a live example of the rendered value or an inline error for unknown, unterminated or response-only variables. Only the layout changed; configuration keys are the same. - **Compatibility:** configurations without `conditions` or `match_type: "any"` are unchanged and serialize as before. Configurations using them, or header values with `%[variables]` (which 0.40.2 would send literally), need 0.41.0. Glob wildcards are still not supported in paths; use regular expressions (documented). - **Verification:** new Rust tests run 19 shared routing cases from `tests/fixtures/routing_conditions_cases.json` (exact/prefix/regex/any precedence, fall-through, every source and operator, negation, country, IPv4/IPv6 CIDR), check that conditional locations are skipped without request facts and never cached, and reject 14 invalid configurations; the panel tester was checked against the same cases. Full suite, `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode against four mock origins: header, IP + cookie (whole-host rule) and POST-only routing reached the expected origins; a cacheable `/api/` response was `HIT` for plain requests while `X-Beta` requests went to the beta origin with `BYPASS / route_disabled`. With header variables, `%[srv_id]` reached the origin as `X-Shard` and came back in `X-S`/`X-Debug` with the location, hash key and `MISS`; on the following `HIT` the cached response carried no earlier values and showed `-` for the backend. In panel mode (Chrome) the tester, a new whole-host rule, reordering, diagnostic presets and saving were exercised. Not tested: production traffic, HTTP/3 clients, GeoIP-based country conditions with a real database. diff --git a/docs/LOAD_BALANCING.md b/docs/LOAD_BALANCING.md index af6c6df..da12b55 100644 --- a/docs/LOAD_BALANCING.md +++ b/docs/LOAD_BALANCING.md @@ -121,7 +121,7 @@ In the panel: add the three backends with **Include in the default load-balancin Locations can additionally require request conditions (header, cookie, query parameter, method, client IP, host, country), and a match type `any` turns a location into a rule for the whole host — together the full HAProxy `use_backend if ` pattern. See [Custom locations → Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). -To see which shard served a request, add a response header rule such as `X-S: %[srv_id]` or `X-LB: %[lb_algorithm] %[hash_key]` (one click under **Backends → Backend diagnostics**); see [Variables in header values](RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). +To see which shard served a request, add a response header rule such as `X-S: %[srv_id]` or `X-LB: %[lb_algorithm] %[hash_key]` (one click under **Headers → Backend diagnostics**); see [Variables in header values](RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). ## Panel helpers diff --git a/docs/RESPONSE_DELIVERY.md b/docs/RESPONSE_DELIVERY.md index ea32e29..5b60b43 100644 --- a/docs/RESPONSE_DELIVERY.md +++ b/docs/RESPONSE_DELIVERY.md @@ -73,7 +73,7 @@ Rules: - Unknown variables, an unterminated `%[` and `%[cache_status]` / `%[backend_time]` in request rules are rejected when saving. Protected header names stay protected. - Values such as `%[path]`, `%[host]` and `%[hash_key]` echo client input, and `%[srv_id]` / `%[srv_url]` reveal internal names — use diagnostic headers for testing or restrict them to trusted locations. -In the panel the header-rule editors show clickable variable chips, and **Vhost → Backends → Backend diagnostics** has one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend) that add the corresponding rules to the Vhost's header rules. The existing switch *Expose selected backend* (`X-Rust-Proxy-Backend`) is unchanged. +In the panel the header-rule editors show clickable variable chips, and **Vhost → Headers → Backend diagnostics** has one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend) that add the corresponding rules to the Vhost's header rules. The existing switch *Expose selected backend* (`X-Rust-Proxy-Backend`) is unchanged. For controlled rollout: diff --git a/docs/VHOSTS.md b/docs/VHOSTS.md index b812a6e..340bbd9 100644 --- a/docs/VHOSTS.md +++ b/docs/VHOSTS.md @@ -100,7 +100,7 @@ Keep Vhost IDs stable for monitoring/history unless renaming is intentional. Ren Within the Vhost editor, **SSL certificates** contains the named certificate selection and the explicit certificate/domain mismatch exception. The next **SSL settings** section contains the optional override of the global TLS 1.2/1.3 and cipher policy. Turning off the TLS override retains the inherited global policy. These two sections are on the same **SSL** tab. -The **Security** tab groups Traffic policy by reusable ACL profiles, HTTP methods, per-IP limits, country access, country-specific limits and User-Agent limits. It also separates HSTS, other security response headers and per-Vhost User-Agent blocking. Within **Custom locations → Access**, profile, HTTP method, country and inline IP/CIDR rules are likewise separated. **Details** separates base Vhost properties from WebSocket options; **Backends** separates balancing strategy, retry behavior and keepalive/connection reuse. The visual grouping does not change saved configuration keys or access precedence. +The **Security** tab groups Traffic policy by reusable ACL profiles, HTTP methods, per-IP limits, country access, country-specific limits and User-Agent limits. It also separates HSTS, other security response headers and per-Vhost User-Agent blocking. Since 0.41.0 the **Headers** tab collects everything else about headers: **Backend diagnostics** (Server-Timing, `X-Rust-Proxy-Backend`, backend time and one-click diagnostic header presets), **Response identity and diagnostics** (Server header, request ID) and the **custom header rules** for requests and responses, including `%[variables]`. The tab starts with a live **header preview** of the unsaved draft for both directions (choose an example backend, location and cache result) and marks where every header comes from; rules show the rendered example value or an error while you type. Within **Custom locations → Access**, profile, HTTP method, country and inline IP/CIDR rules are likewise separated. **Details** separates base Vhost properties from WebSocket options; **Backends** separates balancing strategy, retry behavior and keepalive/connection reuse. The visual grouping does not change saved configuration keys or access precedence. ## Several ACL profiles and intentional TLS mismatch diff --git a/langs/en_US.json b/langs/en_US.json index 1a4e0ed..bbef09e 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -505,7 +505,7 @@ "vhAdvanced": "Advanced: paths, ACL and custom headers", "vhPaths": "Paths (JSON; optional backend_id pins a path to a single pool member)", "vhAcl": "Vhost ACL (JSON or null)", - "vhHeaders": "Request / response header rules (JSON)", + "vhHeaders": "Custom header rules (request / response)", "vhEmpty": "No vhosts yet. Existing routes continue to work.", "vhUnsaved": "Discard unsaved vhost changes?", "vhDelete": "Remove this vhost? Bound sockets are closed after restart.", @@ -943,7 +943,7 @@ "auth.invalid_request": "Invalid request. Check the supplied fields.", "locationProxyHeaders": "Proxy request headers (to backend)", "locationResponseHeaders": "Response headers (to client)", - "locationHeadersHelp": "Set replaces a header, append adds a value, remove deletes it. Applied after global and vhost rules, only for this location. Values are literal (no nginx variables). Transport and verified identity headers stay system-managed.", + "locationHeadersHelp": "Set replaces a header, append adds a value, remove deletes it. Applied after global and vhost rules, only for this location. Values are literal unless they contain %[variables] (HAProxy-style; nginx $variables are not supported). Transport and verified identity headers stay system-managed.", "headersAdvancedJson": "Advanced header rules (JSON)", "headersInvalid": "Invalid header rule. Check name, operation and value.", "headersProtected": "Transport and proxy identity headers cannot be overridden here. Use forwarding, authentication or response settings.", @@ -984,7 +984,7 @@ "vhTrafficCountryRatesSection": "Country-specific rate limits", "vhHttp3Enabled": "Enable HTTP/3 for this vhost", "vhCloudflareClientIp": "Use verified Cloudflare client IP", - "vhTimingHeaders": "Expose Server-Timing diagnostics", + "vhTimingHeaders": "Server-Timing metrics", "vhTimingHeaderNames": "Server-Timing metric names", "vhTimingHeaderNamesStandard": "Reverse proxy (proxy, upstream, proxy-cache)", "vhTimingHeaderNamesCdn": "CDN edge (edge, origin, cdn-cache)", @@ -1533,8 +1533,8 @@ "logUpstreamError": "Upstream error", "listenerDefaultPortsHint": "New vhosts automatically select the standard HTTP :80 listener when it is available.", "vhBackendDiagnostics": "Backend diagnostics", - "vhBackendHeader": "Expose selected backend (X-RustProxy-Backend)", - "vhBackendTimingHeader": "Expose backend response time (X-RustProxy-Backend-Time)", + "vhBackendHeader": "Selected backend (X-Rust-Proxy-Backend)", + "vhBackendTimingHeader": "Backend response time (X-RustProxy-Backend-Time)", "vhBackendDiagnosticsHelp": "Opt-in response headers. Server-Timing is appended to the origin's own metrics; cached responses replace it. Backend time measures origin request-to-response-headers latency; responses served without contacting an origin do not report a backend.", "authModeHelp": "Select an identity provider and a supported integration method. Forward Auth checks sessions via the provider; OIDC uses central login with a callback on the protected application. Existing Vhost integrations remain supported.", "taAdvanced": "Advanced Tinyauth settings", @@ -4037,8 +4037,37 @@ "hdrPresetBalance": "X-LB: algorithm + key", "hdrPresetDebug": "X-Debug: full path", "hdrPresetUpstream": "X-Shard to backend", - "hdrPresetAdded": "Header rule {name} added (Security → header rules).", + "hdrPresetAdded": "Header rule {name} added (Headers → custom header rules).", "hdrPresetExists": "A rule for {name} already exists.", - "hdrPresetsHelp": "Adds a header rule with variables to this vhost (edit or remove it under Security → header rules). Like “http-response set-header X-S %[srv_id]” in HAProxy. Diagnostic headers reveal internal names; keep them for testing or remove them in production." + "hdrPresetsHelp": "Adds a header rule with variables to this vhost (edit or remove it below in the custom header rules). Like “http-response set-header X-S %[srv_id]” in HAProxy. Diagnostic headers reveal internal names; keep them for testing or remove them in production.", + "vhTabHeaders": "Headers", + "vhHeadersPreview": "Header preview", + "hdrExampleBackend": "Example backend", + "hdrExampleLocation": "Location", + "hdrExampleCache": "Cache", + "hdrPreviewRequest": "→ To the backend (request)", + "hdrPreviewRequestHint": "Headers RustProxy adds or changes before forwarding.", + "hdrPreviewResponse": "← To the client (response)", + "hdrPreviewResponseHint": "Headers RustProxy adds, changes or removes in the response.", + "hdrPreviewHelp": "Live preview of the unsaved draft with example values. Global rules come from Settings; the location's own rules apply when you choose it above. Headers sent by the application itself are not shown.", + "hdrSource_global": "global", + "hdrSource_vhost": "vhost", + "hdrSource_location": "location", + "hdrSource_diagnostics": "diagnostics", + "hdrSource_system": "system", + "hdrTagDynamic": "%[…] per request", + "hdrTagRemoved": "removed by", + "hdrForwardingValue": "client address (according to forwarding settings)", + "hdrServerPreserved": "(the backend's value is kept)", + "hdrPreviewNoneRequest": "No extra request headers.", + "hdrPreviewNoneResponse": "No extra response headers.", + "hdrErrUnterminated": "Missing “]” after %[", + "hdrErrUnknown": "Unknown variable %[{name}]", + "hdrErrResponseOnly": "%[{name}] is available only in response rules", + "hdrExample": "Example", + "hdrCardTimingHelp": "Timing metrics for browser DevTools; appended to the application's own Server-Timing.", + "hdrCardBackendHelp": "Which backend served the request; absent on a cache hit.", + "hdrCardBackendTimeHelp": "Time from sending the request to receiving the backend's response headers.", + "hdrPreviewHitNoRequest": "Cache HIT: the request does not reach any backend" } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index b40ecd5..cff31b7 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -505,7 +505,7 @@ "vhAdvanced": "Zaawansowane: ścieżki, ACL i własne nagłówki", "vhPaths": "Sciezki (JSON; opcjonalne backend_id przypina sciezke do jednego backendu)", "vhAcl": "ACL vhosta (JSON lub null)", - "vhHeaders": "Reguły nagłówków żądania / odpowiedzi (JSON)", + "vhHeaders": "Własne reguły nagłówków (żądanie / odpowiedź)", "vhEmpty": "Brak vhostów. Dotychczasowe trasy nadal działają.", "vhUnsaved": "Odrzucić niezapisane zmiany vhosta?", "vhDelete": "Usunąć vhost? Gniazda nasłuchu zostaną zamknięte po restarcie.", @@ -943,7 +943,7 @@ "auth.invalid_request": "Nieprawidłowe żądanie. Sprawdź podane pola.", "locationProxyHeaders": "Nagłówki żądania proxy (do backendu)", "locationResponseHeaders": "Nagłówki odpowiedzi (do klienta)", - "locationHeadersHelp": "Ustaw nadpisuje nagłówek, dopisz dodaje wartość, usuń kasuje go. Reguły lokalizacji są stosowane po globalnych i vhosta. Wartości są dosłowne (bez zmiennych nginx). Nagłówkami transportu i zweryfikowanej tożsamości zarządza system.", + "locationHeadersHelp": "Ustaw nadpisuje nagłówek, dopisz dodaje wartość, usuń kasuje go. Reguły lokalizacji są stosowane po globalnych i vhosta. Wartości są dosłowne, chyba że zawierają zmienne %[…] (jak w HAProxy; zmienne nginx $… nie są obsługiwane). Nagłówkami transportu i zweryfikowanej tożsamości zarządza system.", "headersAdvancedJson": "Zaawansowane reguły nagłówków (JSON)", "headersInvalid": "Nieprawidłowa reguła nagłówka. Sprawdź nazwę, operację i wartość.", "headersProtected": "Nie można tu nadpisać nagłówków transportu i tożsamości proxy. Użyj ustawień forwardingu, autentykacji lub odpowiedzi.", @@ -984,7 +984,7 @@ "vhTrafficCountryRatesSection": "Limity zapytań dla krajów", "vhHttp3Enabled": "Włącz HTTP/3 dla tego vhosta", "vhCloudflareClientIp": "Używaj zweryfikowanego IP klienta z Cloudflare", - "vhTimingHeaders": "Udostępniaj diagnostykę Server-Timing", + "vhTimingHeaders": "Metryki Server-Timing", "vhTimingHeaderNames": "Nazwy metryk Server-Timing", "vhTimingHeaderNamesStandard": "Reverse proxy (proxy, upstream, proxy-cache)", "vhTimingHeaderNamesCdn": "Brzeg CDN (edge, origin, cdn-cache)", @@ -1533,8 +1533,8 @@ "logUpstreamError": "Błąd upstreamu", "listenerDefaultPortsHint": "Nowy vhost automatycznie wybiera standardowy listener HTTP :80, jeśli jest dostępny.", "vhBackendDiagnostics": "Diagnostyka backendu", - "vhBackendHeader": "Udostępniaj wybrany backend (X-RustProxy-Backend)", - "vhBackendTimingHeader": "Udostępniaj czas odpowiedzi backendu (X-RustProxy-Backend-Time)", + "vhBackendHeader": "Wybrany backend (X-Rust-Proxy-Backend)", + "vhBackendTimingHeader": "Czas odpowiedzi backendu (X-RustProxy-Backend-Time)", "vhBackendDiagnosticsHelp": "Opcjonalne nagłówki odpowiedzi. Server-Timing jest dopisywany do metryk originu; odpowiedzi z cache zastępują zapisane metryki. Czas backendu oznacza czas od wysłania żądania do otrzymania nagłówków odpowiedzi; odpowiedzi obsłużone bez kontaktu z originem nie raportują backendu.", "authModeHelp": "Wybierz dostawcę tożsamości i obsługiwaną metodę integracji. Forward Auth sprawdza sesję u dostawcy, a OIDC zapewnia logowanie centralne z callbackiem na domenie chronionej aplikacji. Stare konfiguracje Vhostów pozostają obsługiwane.", "taAdvanced": "Zaawansowane ustawienia Tinyauth", @@ -4037,8 +4037,37 @@ "hdrPresetBalance": "X-LB: algorytm + klucz", "hdrPresetDebug": "X-Debug: pełna ścieżka", "hdrPresetUpstream": "X-Shard do backendu", - "hdrPresetAdded": "Dodano regułę nagłówka {name} (zakładka Bezpieczeństwo → Reguły nagłówków).", + "hdrPresetAdded": "Dodano regułę nagłówka {name} (Nagłówki → własne reguły nagłówków).", "hdrPresetExists": "Reguła dla {name} już istnieje.", - "hdrPresetsHelp": "Dodaje do vhosta regułę nagłówka ze zmiennymi (edytujesz lub usuwasz ją w zakładce Bezpieczeństwo → Reguły nagłówków). Jak „http-response set-header X-S %[srv_id]” w HAProxy. Nagłówki diagnostyczne ujawniają wewnętrzne nazwy; używaj ich do testów albo usuń na produkcji." + "hdrPresetsHelp": "Dodaje do vhosta regułę nagłówka ze zmiennymi (edytujesz lub usuwasz ją niżej, we własnych regułach nagłówków). Jak „http-response set-header X-S %[srv_id]” w HAProxy. Nagłówki diagnostyczne ujawniają wewnętrzne nazwy; używaj ich do testów albo usuń na produkcji.", + "vhTabHeaders": "Nagłówki", + "vhHeadersPreview": "Podgląd nagłówków", + "hdrExampleBackend": "Przykładowy backend", + "hdrExampleLocation": "Lokalizacja", + "hdrExampleCache": "Cache", + "hdrPreviewRequest": "→ Do backendu (żądanie)", + "hdrPreviewRequestHint": "Nagłówki, które RustProxy dodaje lub zmienia przed przekazaniem.", + "hdrPreviewResponse": "← Do klienta (odpowiedź)", + "hdrPreviewResponseHint": "Nagłówki, które RustProxy dodaje, zmienia lub usuwa w odpowiedzi.", + "hdrPreviewHelp": "Podgląd niezapisanego szkicu na żywo, z przykładowymi wartościami. Reguły globalne pochodzą z Ustawień; reguły lokalizacji działają, gdy wybierzesz ją powyżej. Nie widać tu nagłówków wysyłanych przez samą aplikację.", + "hdrSource_global": "globalne", + "hdrSource_vhost": "vhost", + "hdrSource_location": "lokalizacja", + "hdrSource_diagnostics": "diagnostyka", + "hdrSource_system": "system", + "hdrTagDynamic": "%[…] per żądanie", + "hdrTagRemoved": "usuwa", + "hdrForwardingValue": "adres klienta (wg ustawień przekazywania)", + "hdrServerPreserved": "(zostaje wartość z backendu)", + "hdrPreviewNoneRequest": "Brak dodatkowych nagłówków żądania.", + "hdrPreviewNoneResponse": "Brak dodatkowych nagłówków odpowiedzi.", + "hdrErrUnterminated": "Brakuje „]” po %[", + "hdrErrUnknown": "Nieznana zmienna %[{name}]", + "hdrErrResponseOnly": "%[{name}] jest dostępna tylko w regułach odpowiedzi", + "hdrExample": "Przykład", + "hdrCardTimingHelp": "Metryki czasu dla DevTools w przeglądarce; dopisywane do własnego Server-Timing aplikacji.", + "hdrCardBackendHelp": "Który backend obsłużył żądanie; brak przy trafieniu w cache.", + "hdrCardBackendTimeHelp": "Czas od wysłania żądania do otrzymania nagłówków odpowiedzi backendu.", + "hdrPreviewHitNoRequest": "Trafienie w cache: żądanie nie trafia do żadnego backendu" } } diff --git a/src/admin/router.rs b/src/admin/router.rs index 67c310a..f5f9206 100644 --- a/src/admin/router.rs +++ b/src/admin/router.rs @@ -127,6 +127,7 @@ fn admin_vhosts_javascript() -> &'static str { include_str!("web/vhosts/rates.js"), include_str!("web/vhosts/balancing.js"), include_str!("web/vhosts/routing.js"), + include_str!("web/vhosts/headers-tab.js"), include_str!("web/vhosts/editor.js"), include_str!("web/vhosts/render.js"), "})();", diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css index b5dd07c..978f593 100644 --- a/src/admin/web/css/40-editors.css +++ b/src/admin/web/css/40-editors.css @@ -2452,3 +2452,180 @@ h2+.fine { padding: 2px 8px; font: 11px var(--mono); } + +/* Headers tab: live preview, diagnostic cards and compact header rules. */ +.hdr-preview { + display: grid; + gap: 10px; + border: 1px solid var(--accent); + background: var(--panel2); + padding: 12px; +} + +.hdr-preview-controls { + display: flex; + flex-wrap: wrap; + gap: 10px 16px; +} + +.hdr-preview-control { + display: grid; + gap: 3px; + min-width: 150px; + font-size: 11px; + color: var(--muted); +} + +.hdr-preview-columns { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.hdr-preview-col { + min-width: 0; + border: 1px solid var(--line); + background: var(--panel); + padding: 10px; +} + +.hdr-preview-col h4 { + margin: 0; + font-size: 12px; +} + +.hdr-preview-col>p { + margin: 2px 0 8px; +} + +.hdr-preview-list { + display: grid; + gap: 4px; + margin: 0; + padding: 0; + list-style: none; +} + +.hdr-line { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 4px 8px; + border-bottom: 1px solid var(--row-line); + padding: 3px 0; +} + +.hdr-line code { + min-width: 0; + font: 11px var(--mono); + overflow-wrap: anywhere; +} + +.hdr-line code b { + color: var(--accent); + font-weight: 600; +} + +.hdr-line.is-removed code { + opacity: .55; + text-decoration: line-through; +} + +.hdr-line.is-system code { + color: var(--muted); +} + +.hdr-tags { + display: flex; + gap: 4px; +} + +.hdr-tag { + border: 1px solid var(--line); + border-radius: 999px; + padding: 0 6px; + color: var(--muted); + font: 10px var(--mono); + white-space: nowrap; +} + +.hdr-tag.is-dynamic { + border-color: var(--pill-live-line); + color: var(--green); +} + +.hdr-tag.is-removed { + border-color: var(--notice-line); + color: var(--notice-text); +} + +.hdr-cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 10px; +} + +.hdr-card { + display: grid; + align-content: start; + gap: 6px; + border: 1px solid var(--line); + padding: 10px; +} + +.hdr-card.is-on { + border-color: var(--pill-live-line); + background: var(--panel2); +} + +.hdr-card>p { + margin: 0; +} + +.hdr-card-sample { + font: 11px var(--mono); + color: var(--muted); + overflow-wrap: anywhere; +} + +.hdr-card.is-on .hdr-card-sample b { + color: var(--accent); +} + +.lb-preset.is-added { + opacity: .5; +} + +.hdr-row { + padding: 6px 8px; +} + +.vh-header-rule-fields.hdr-row-fields { + display: grid; + grid-template-columns: minmax(90px, 130px) minmax(120px, 1fr) minmax(160px, 2fr) auto; + align-items: end; + gap: 8px; +} + +.hdr-row-remove { + align-self: end; +} + +.hdr-row.is-dynamic { + border-left: 2px solid var(--green); +} + +.hdr-row.is-invalid { + border-left: 2px solid var(--red); +} + +.hdr-row-hint { + margin: 4px 0 0; + font: 11px var(--mono); + overflow-wrap: anywhere; +} + +.hdr-row.is-invalid .hdr-row-hint { + color: var(--red); +} diff --git a/src/admin/web/css/70-responsive.css b/src/admin/web/css/70-responsive.css index 0b5abf8..a998ea9 100644 --- a/src/admin/web/css/70-responsive.css +++ b/src/admin/web/css/70-responsive.css @@ -411,6 +411,11 @@ grid-template-columns: 1fr 1fr; } + .hdr-preview-columns, + .vh-header-rule-fields.hdr-row-fields { + grid-template-columns: 1fr; + } + .lb-bar { grid-template-columns: minmax(60px, 110px) minmax(0, 1fr) 70px; } diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index e54976f..787de33 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -1,6 +1,6 @@ "use strict"; let vhostCacheRulesEditor = null; -let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null; +let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null, headersPreviewControl = null, presetsRefresh = () => { }; const chartHistory = new Map(); const backendTrafficHistory = new Map(); const backendRequestHistory = new Map(); @@ -23,7 +23,7 @@ const field = (parent, name, key, value, type = "text", options = {}) => { }; const group = (key, advanced = false) => { const box = el(advanced ? "details" : "fieldset", undefined, "vh-group"); - box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "backends", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "security", vhHeaders: "security", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key)); + box.dataset.tab = ({ vhEditor: "details", vhFrontends: "details", vhBackendPool: "backends", vhBackendDiagnostics: "headers", vhProxyTimeouts: "backends", vhBalancing: "backends", vhSticky: "backends", vhHealth: "health", vhPassiveHealth: "health", vhSecurity: "security", vhTrafficPolicy: "security", vhTinyauth: "auth", vhResponsePolicy: "headers", vhHeaders: "headers", vhHeadersPreview: "headers", vhAdvanced: "advanced", vhLocations: "locations", vhSsl: "ssl", vhSslSettings: "ssl", vhCache: "cache", vhCompression: "compression", vhTransform: "transform", vhPages: "pages" })[key] || "advanced"; box.append(text(advanced ? "summary" : "legend", key)); const body = el("div", undefined, "vh-grid"); box.append(body); container.append(box); return body; }; const note = (parent, key) => { const node = text("p", key, "fine vh-wide"); parent.append(node); return node; }; @@ -60,7 +60,7 @@ const defaults = () => ({ }); function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); } -function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); } +function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["headers", "vhTabHeaders"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); } function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_ignore_vary_cookie: tri("vh-cache-static-vary-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), expose_detailed_status: tri("vh-cache-detailed-status"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; } function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; } function collectTransform() { @@ -96,7 +96,7 @@ const DIAGNOSTIC_PRESETS = [ { key: "hdrPresetDebug", direction: "response", rule: { op: "set", name: "X-Debug", value: "%[vhost]/%[location] -> %[srv_id] (%[cache_status], %[backend_time])" } }, { key: "hdrPresetUpstream", direction: "request", rule: { op: "set", name: "X-Shard", value: "%[srv_id]" } } ]; -function headerEditors(parent, initial, target = read("headers"), onChange = changed) { +function headerEditors(parent, initial, target = read("headers"), onChange = changed, exampleContext = () => ({})) { const holders = {}, adders = {}, emptyStates = {}; const renumber = direction => { const rows = holders[direction]; @@ -123,16 +123,24 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha const rows = el("div", undefined, "vh-header-rows"); holders[direction] = rows; block.append(rows); parent.append(block); const add = (value = { op: "set", name: "", value: "" }) => { if (rows.children.length >= 32) { toast(t("headerLimit"), true); return; } - const row = el("article", undefined, "vh-header-row"); - const rowHead = el("div", undefined, "vh-header-rule-head"), rowTitle = el("strong", "", "vh-header-rule-title"); - rowHead.append(rowTitle, button("remove", () => { row.remove(); renumber(direction); sync(); })); row.append(rowHead); - const fields = el("div", undefined, "vh-header-rule-fields"); + // Compact one-line rule: operation · name · value · remove, with a live check of + // %[variables] (example value or error) underneath. + const row = el("article", undefined, "vh-header-row hdr-row"); + const fields = el("div", undefined, "vh-header-rule-fields hdr-row-fields"); field(fields, "rule-op", "headerOperation", value.op, "select", { values: [["set", "header_set"], ["append", "header_append"], ["remove", "header_remove"]] }); const name = field(fields, "rule-name", "headerName", value.name, "text", { maxLength: 128 }); name.placeholder = "X-App-Header"; - const ruleValue = field(fields, "rule-value", "headerValue", value.value ?? "", "text", { maxLength: 8192 }); ruleValue.placeholder = "value"; - row.append(fields); - const enabled = () => { ruleValue.disabled = str("rule-op", row) === "remove"; row.classList.toggle("is-remove", ruleValue.disabled); }; - row.addEventListener("change", () => { enabled(); sync(); }); row.addEventListener("input", sync); rows.append(row); enabled(); renumber(direction); + const ruleValue = field(fields, "rule-value", "headerValue", value.value ?? "", "text", { maxLength: 8192 }); ruleValue.placeholder = direction === "response" ? "%[srv_id]" : "value"; + const removeButton = button("remove", () => { row.remove(); renumber(direction); sync(); }, "quiet hdr-row-remove"); + fields.append(removeButton); row.append(fields); + const hint = el("p", "", "fine hdr-row-hint"); row.append(hint); + const check = () => { + const remove = str("rule-op", row) === "remove"; ruleValue.disabled = remove; row.classList.toggle("is-remove", remove); + const result = remove ? { dynamic: false } : headerValueCheck(ruleValue.value, direction, headerExampleVars({ ...headerExampleContext, ...exampleContext() })); + ruleValue.setCustomValidity(result.error || ""); row.classList.toggle("is-invalid", Boolean(result.error)); row.classList.toggle("is-dynamic", Boolean(result.dynamic)); + hint.hidden = !result.error && !result.dynamic; + hint.textContent = result.error ? result.error : result.dynamic ? `${t("hdrExample")}: ${name.value || "X-…"}: ${result.rendered}` : ""; + }; + row.addEventListener("change", () => { check(); sync(); }); row.addEventListener("input", () => { check(); sync(); }); rows.append(row); check(); renumber(direction); }; adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction); block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header")); @@ -145,7 +153,7 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha let target = lastValue?.isConnected && !lastValue.disabled ? lastValue : [...rows.querySelectorAll('[name="rule-value"]:not(:disabled)')].pop(); if (!target) { add({ op: "set", name: "", value: "" }); target = [...rows.querySelectorAll('[name="rule-value"]')].pop(); } const token = `%[${name}]`, at = target.selectionStart ?? target.value.length; - target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; sync(); + target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; target.dispatchEvent(new Event("input", { bubbles: true })); }, "quiet hdr-var"); delete chip.dataset.i18n; chip.textContent = `%[${name}]`; chip.title = t(`hdrVar_${name}`); chips.append(chip); } @@ -495,7 +503,7 @@ function locationsEditor(parent, values) { const visualButton = button("headersVisualBuilder", () => { visualPane.hidden = false; jsonPane.hidden = true; }), jsonButton = button("headersAdvancedJson", () => { visualPane.hidden = true; jsonPane.hidden = false; }), docsButton = button("documentation", () => openLocationHelp("headers")); headerToolbar.append(visualButton, jsonButton, docsButton); headerBody.append(headerToolbar, visualPane, jsonPane); const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 }); - const editor = headerEditors(visualPane, value.headers || {}, raw, sync); row.readHeaders = () => editor.read(); + const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read(); const preview = el("section", undefined, "vh-wide location-preview"); preview.append(text("h4", "locationPreviewTitle")); diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js index 05fa70f..0289157 100644 --- a/src/admin/web/vhosts/editor.js +++ b/src/admin/web/vhosts/editor.js @@ -204,21 +204,30 @@ function load(value = defaults(), migrationIds = [], show = true) { syncFrontendTransports(); g = group("vhBackendPool"); const members = el("div", undefined, "vh-wide vh-members"); g.append(members); (value.backends || []).forEach(m => memberRow(members, m)); g.append(button("vhAddBackend", () => { memberRow(members); changed(); })); + g = group("vhHeadersPreview"); headersPreviewControl = headersPreview(g); g = group("vhBackendDiagnostics"); - field(g, "timing-headers", "vhTimingHeaders", value.timing_headers === true, "checkbox", { switch: true }); - field(g, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] }); - field(g, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com"; - field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox", { switch: true }); - field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true }); + const diagnosticCards = el("div", undefined, "vh-wide hdr-cards"); g.append(diagnosticCards); + diagnosticCard(diagnosticCards, { name: "timing-headers", key: "vhTimingHeaders", checked: value.timing_headers === true, header: "Server-Timing", example: "proxy;dur=1.8, upstream;dur=12.4", help: "hdrCardTimingHelp", extra: body => { + field(body, "timing-header-names", "vhTimingHeaderNames", value.timing_header_names || "standard", "select", { values: [["standard", "vhTimingHeaderNamesStandard"], ["cdn", "vhTimingHeaderNamesCdn"], ["legacy", "vhTimingHeaderNamesLegacy"]] }); + field(body, "timing-allow-origin", "vhTimingAllowOrigin", (value.timing_allow_origin || []).join(", "), "text", { maxLength: 2048 }).placeholder = "https://app.example.com"; + } }); + diagnosticCard(diagnosticCards, { name: "backend-header", key: "vhBackendHeader", checked: value.backend_header === true, header: "X-Rust-Proxy-Backend", example: `${value.id || "vhost"}/${(value.backends || [])[0]?.id || "origin-1"}`, help: "hdrCardBackendHelp" }); + diagnosticCard(diagnosticCards, { name: "backend-timing-header", key: "vhBackendTimingHeader", checked: value.backend_timing_header === true, header: "X-RustProxy-Backend-Time", example: "12.40ms", help: "hdrCardBackendTimeHelp" }); note(g, "vhBackendDiagnosticsHelp"); const diagnosticPresets = el("div", undefined, "vh-wide hdr-presets"); diagnosticPresets.append(text("span", "hdrPresets", "hdr-vars-label")); - for (const preset of DIAGNOSTIC_PRESETS) diagnosticPresets.append(button(preset.key, () => { - if (!vhostHeadersControl) return; - const current = vhostHeadersControl.read()[preset.direction] || []; - if (current.some(rule => rule.name.toLowerCase() === preset.rule.name.toLowerCase())) { toast(t("hdrPresetExists").replace("{name}", preset.rule.name)); return; } - vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name)); - }, "quiet lb-preset")); + const presetButtons = []; + const syncPresets = () => { const current = safeHeaders(); for (const [preset, node] of presetButtons) { const exists = (current[preset.direction] || []).some(rule => rule.name?.toLowerCase() === preset.rule.name.toLowerCase()); node.disabled = exists; node.classList.toggle("is-added", exists); node.title = exists ? t("hdrPresetExists").replace("{name}", preset.rule.name) : `${preset.direction === "request" ? "→" : "←"} ${preset.rule.name}: ${preset.rule.value}`; } }; + const safeHeaders = () => { try { return vhostHeadersControl?.read() || {}; } catch { return {}; } }; + for (const preset of DIAGNOSTIC_PRESETS) { + const node = button(preset.key, () => { + if (!vhostHeadersControl) return; + vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name)); syncPresets(); + container.querySelector(".hdr-rules-anchor")?.scrollIntoView({ behavior: "smooth", block: "start" }); + }, "quiet lb-preset"); + presetButtons.push([preset, node]); diagnosticPresets.append(node); + } g.append(diagnosticPresets); note(g, "hdrPresetsHelp"); + presetsRefresh = syncPresets; const proxyTimeouts = { ...defaultProxyTimeouts(), ...(value.proxy_timeouts || {}) }; g = group("vhProxyTimeouts"); field(g, "proxy-connect-timeout", "vhProxyConnectTimeout", proxyTimeouts.connect_timeout_seconds ?? 10, "number", { required: true, min: 1, max: 300 }); @@ -569,9 +578,10 @@ function load(value = defaults(), migrationIds = [], show = true) { }; transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform(); note(transformOptions, "vhTransformHelp"); - g = group("vhHeaders"); vhostHeadersControl = headerEditors(g, value.headers || {}); + g = group("vhHeaders"); g.parentElement.classList.add("hdr-rules-anchor"); vhostHeadersControl = headerEditors(g, value.headers || {}); g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {}); initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal(); + headersPreviewControl?.refresh(); presetsRefresh(); } function collect() { diff --git a/src/admin/web/vhosts/headers-tab.js b/src/admin/web/vhosts/headers-tab.js new file mode 100644 index 0000000..3f15403 --- /dev/null +++ b/src/admin/web/vhosts/headers-tab.js @@ -0,0 +1,136 @@ +// Headers tab of the vhost editor: live preview of the headers RustProxy sends to the +// backend and to the client, example values for %[variables] and diagnostic cards. +const HEADER_VARIABLE_NAMES = new Set(HEADER_VARIABLES.map(([name]) => name)); +const HEADER_RESPONSE_ONLY = new Set(HEADER_VARIABLES.filter(([, only]) => only).map(([name]) => name)); +let headerExampleContext = { member: "", location: "main", cache: "MISS" }; + +// Example values for header variables, based on the draft (first eligible backend…). +function headerExampleVars(context = headerExampleContext) { + const members = (typeof balancingMembers === "function" ? balancingMembers() : []).filter(m => m.id); + const member = members.find(m => m.id === context.member) || members.find(m => m.enabled && m.pool_eligible) || members[0]; + const hits = context.cache === "HIT"; + let algorithm = "least_connections"; + try { algorithm = str("algorithm") || algorithm; } catch { } + return { + srv_id: hits ? "-" : member?.id || "-", srv_url: hits ? "-" : member?.url || "-", location: context.location || "main", + vhost: (() => { try { return str("id") || "vhost"; } catch { return "vhost"; } })(), lb_algorithm: algorithm, + hash_key: algorithm === "hash" || algorithm === "ip_hash" ? "/media/a.mp3" : "-", client_ip: "203.0.113.10", country: "PL", + req_id: "7f3a9c1e2b4d", method: "GET", host: (() => { try { return lines(read("hosts")?.value || "")[0] || "example.com"; } catch { return "example.com"; } })(), + path: "/media/a.mp3", cache_status: context.cache, backend_time: hits ? "-" : "12.40ms" + }; +} +// Checks a header value and renders it with example variables. +function headerValueCheck(value, direction, vars = headerExampleVars()) { + const text = String(value ?? ""); + if (!text.includes("%[")) return { dynamic: false, rendered: text }; + let rendered = "", rest = text; + while (rest.includes("%[")) { + const start = rest.indexOf("%["), end = rest.indexOf("]", start); + if (end < 0) return { error: t("hdrErrUnterminated") }; + const name = rest.slice(start + 2, end); + if (!HEADER_VARIABLE_NAMES.has(name)) return { error: t("hdrErrUnknown").replace("{name}", name) }; + if (direction === "request" && HEADER_RESPONSE_ONLY.has(name)) return { error: t("hdrErrResponseOnly").replace("{name}", name) }; + rendered += rest.slice(0, start) + (vars[name] || "-"); rest = rest.slice(end + 1); + } + return { dynamic: true, rendered: rendered + rest }; +} +// Applies header rules to an ordered header list [{name, value, source, dynamic}]. +function headerApplyRules(list, rules, source, direction, vars, stage) { + for (const rule of rules || []) { + if (!rule?.name) continue; + const check = rule.op === "remove" ? { dynamic: false } : headerValueCheck(rule.value, direction, vars); + if (check.error) continue; + if (stage === "static" && check.dynamic) continue; + if (stage === "dynamic" && !check.dynamic) continue; + const lower = rule.name.toLowerCase(); + if (rule.op === "remove") { for (const item of list) if (item.name.toLowerCase() === lower && !item.removed) item.removed = source; continue; } + if (rule.op === "set") for (const item of list) if (item.name.toLowerCase() === lower && !item.removed) item.removed = source; + list.push({ name: rule.name, value: check.rendered, source, dynamic: check.dynamic }); + } +} + +function headersPreview(parent) { + const box = el("div", undefined, "vh-wide hdr-preview"); parent.append(box); + const controls = el("div", undefined, "hdr-preview-controls"); box.append(controls); + const select = (key, onChange) => { const label = el("label", undefined, "hdr-preview-control"), input = document.createElement("select"); label.append(text("span", key), input); controls.append(label); input.addEventListener("change", () => { onChange(input.value); render(); }); return input; }; + const memberSelect = select("hdrExampleBackend", value => { headerExampleContext.member = value; }); + const locationSelect = select("hdrExampleLocation", value => { headerExampleContext.location = value; }); + const cacheSelect = select("hdrExampleCache", value => { headerExampleContext.cache = value; }); + for (const value of ["MISS", "HIT", "BYPASS"]) { const o = el("option", value); o.value = value; cacheSelect.append(o); } + const columns = el("div", undefined, "hdr-preview-columns"); box.append(columns); + const column = (key, hint) => { const col = el("section", undefined, "hdr-preview-col"); col.append(text("h4", key), text("p", hint, "fine")); const listNode = el("ul", undefined, "hdr-preview-list"); col.append(listNode); columns.append(col); return listNode; }; + const requestList = column("hdrPreviewRequest", "hdrPreviewRequestHint"), responseList = column("hdrPreviewResponse", "hdrPreviewResponseHint"); + box.append(text("p", "hdrPreviewHelp", "fine")); + const fillSelect = (node, options, current) => { node.replaceChildren(...options.map(([value, label]) => { const o = el("option", label); o.value = value; return o; })); node.value = options.some(([v]) => v === current) ? current : options[0]?.[0] ?? ""; return node.value; }; + const readRoutes = () => { try { return JSON.parse(read("paths")?.value || "[]"); } catch { return []; } }; + const safe = fn => { try { return fn(); } catch { return undefined; } }; + const renderList = (node, items, empty) => { + node.replaceChildren(); + if (!items.length) { node.append(el("li", t(empty), "fine")); return; } + for (const item of items) { + const li = el("li", undefined, `hdr-line${item.removed ? " is-removed" : ""}${item.system ? " is-system" : ""}`); + const code = el("code"); code.append(el("b", item.name), document.createTextNode(item.value === undefined ? "" : `: ${item.value}`)); li.append(code); + const tags = el("span", undefined, "hdr-tags"); + tags.append(el("span", t(`hdrSource_${item.source}`), `hdr-tag is-${item.source}`)); + if (item.dynamic) tags.append(el("span", t("hdrTagDynamic"), "hdr-tag is-dynamic")); + if (item.removed) tags.append(el("span", `${t("hdrTagRemoved")} (${t(`hdrSource_${item.removed}`)})`, "hdr-tag is-removed")); + li.append(tags); node.append(li); + } + }; + const render = () => { + const members = safe(() => balancingMembers()) || []; + headerExampleContext.member = fillSelect(memberSelect, members.filter(m => m.id).map(m => [m.id, m.id]), headerExampleContext.member); + const routes = readRoutes(); + headerExampleContext.location = fillSelect(locationSelect, [["main", t("rtMainSource")], ...routes.filter(r => r.id && !r.internal).map(r => [r.id, r.id])], headerExampleContext.location); + cacheSelect.value = headerExampleContext.cache; + const vars = headerExampleVars(), route = routes.find(r => r.id === headerExampleContext.location); + const global = envelope?.config?.headers || {}, vhost = safe(() => vhostHeadersControl?.read()) || {}, location = route?.headers || {}; + // Request: static rules (global → vhost → location), then forwarding, then rules with variables. + const request = [], requestVars = headerExampleVars({ ...headerExampleContext, cache: "MISS" }); + if (headerExampleContext.cache === "HIT") request.push({ name: t("hdrPreviewHitNoRequest"), value: undefined, source: "system", system: true }); + else for (const stage of ["static", "dynamic"]) { + if (stage === "dynamic" && safe(() => yes("forward-client-ip"))) request.push({ name: "X-Forwarded-For / X-Real-IP", value: t("hdrForwardingValue"), source: "system", system: true }); + headerApplyRules(request, global.request, "global", "request", requestVars, stage); + headerApplyRules(request, vhost.request, "vhost", "request", requestVars, stage); + headerApplyRules(request, location.request, "location", "request", requestVars, stage); + } + // Response: static rules, diagnostics and identity, then rules with variables. + const response = []; + headerApplyRules(response, global.response, "global", "response", vars, "static"); + headerApplyRules(response, vhost.response, "vhost", "response", vars, "static"); + headerApplyRules(response, location.response, "location", "response", vars, "static"); + if (safe(() => yes("timing-headers"))) response.push({ name: "Server-Timing", value: "proxy;dur=1.8, upstream;dur=12.4", source: "diagnostics" }); + if (safe(() => yes("backend-header")) && vars.srv_id !== "-") response.push({ name: "X-Rust-Proxy-Backend", value: `${vars.vhost}/${vars.srv_id}`, source: "diagnostics" }); + if (safe(() => yes("backend-timing-header")) && vars.backend_time !== "-") response.push({ name: "X-RustProxy-Backend-Time", value: vars.backend_time, source: "diagnostics" }); + const serverMode = safe(() => str("server-mode")) || "inherit"; + const globalServer = envelope?.config?.server_header || { mode: "custom", value: "RustProxy" }; + const effectiveServer = serverMode === "inherit" ? globalServer : { mode: serverMode, value: safe(() => str("server-value")) }; + if (effectiveServer.mode === "custom") response.push({ name: "Server", value: effectiveServer.value || "RustProxy", source: serverMode === "inherit" ? "global" : "vhost" }); + else if (effectiveServer.mode === "preserve") response.push({ name: "Server", value: t("hdrServerPreserved"), source: "system", system: true }); + const requestId = safe(() => yes("diag-inherit")) ? envelope?.config?.diagnostic_headers?.request_id : safe(() => yes("diag-request_id")); + if (requestId) response.push({ name: "X-Request-ID", value: vars.req_id, source: "diagnostics" }); + headerApplyRules(response, global.response, "global", "response", vars, "dynamic"); + headerApplyRules(response, vhost.response, "vhost", "response", vars, "dynamic"); + headerApplyRules(response, location.response, "location", "response", vars, "dynamic"); + renderList(requestList, request, "hdrPreviewNoneRequest"); + renderList(responseList, response, "hdrPreviewNoneResponse"); + }; + let pending = 0; + const refresh = () => { cancelAnimationFrame(pending); pending = requestAnimationFrame(() => { if (box.isConnected) render(); }); }; + return { refresh }; +} + +// One switch as a card that shows the header it produces. +function diagnosticCard(parent, { name, key, checked, header, example, help, extra }) { + const card = el("div", undefined, "hdr-card"), head = el("div", undefined, "hdr-card-head"); card.append(head); + const input = field(head, name, key, checked, "checkbox", { switch: true }); + const sample = el("code", undefined, "hdr-card-sample"); sample.append(el("b", header), document.createTextNode(`: ${example}`)); card.append(sample); + if (help) card.append(text("p", help, "fine")); + let body = null; if (extra) { body = el("div", undefined, "vh-grid hdr-card-extra"); card.append(body); extra(body); } + const sync = () => { card.classList.toggle("is-on", input.checked); if (body) body.hidden = !input.checked; }; + input.addEventListener("change", sync); sync(); parent.append(card); return input; +} + +// The preview follows every edit in the editor and the Headers tab button. +for (const type of ["input", "change", "click"]) container.addEventListener(type, () => { headersPreviewControl?.refresh(); presetsRefresh(); }); +$("vhost-tabs").addEventListener("click", () => headersPreviewControl?.refresh());