diff --git a/AGENTS.md b/AGENTS.md index 5371e29..13d6b6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.42.4**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.43.0**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9938b79..e5ad144 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.43.0 — Unified info tooltips, Docker Headers section, FastCGI I/O buffering + +- **Information icons and bubbles:** every "i" information icon in the panel (Overview widgets, Cache settings, FastCGI profiles) and the Docker label help "?" button now share one look that follows Settings → Appearance (corner style, theme colors, UI scale). The "?" button still opens the label help dialog. Information bubbles open next to their icon, stay inside the visible area (horizontal shift, open upwards near the bottom), close on Escape or a click elsewhere, and only one is open at a time. Long help text inside a bubble is no longer collapsed to two lines in Settings. +- **Docker Vhosts:** "Diagnostic headers" becomes **Headers**. It contains the diagnostic header switches and, collapsed inside it, **HTTP policies** (previously a separately styled box below). The section summary shows which diagnostic headers are on and how many policy rules exist. Stored assignment fields (`timing_headers`, `backend_header`, `backend_timing_header`, `policy`) are unchanged. +- **Custom locations redesign:** the location list is now a routing table — collapsed rows show order, state, ID, match, path/conditions, action and chips for settings that differ from the Vhost (access, headers, cache, balancing, HTTP policies, error fallback). An expanded location is split into **When** (match), **What** (action; only the fields of the selected action are shown) and **Options** tabs (Access, Headers, Cache, Errors, Backends & balancing, HTTP policies) with per-tab state. **Add location** offers starting points (backend path, Web Service, redirect, fixed response, internal `error_page` location, whole-host rule, empty). Existing locations open collapsed; a validation error opens the location and the tab that holds the field. No field, setting or behavior was removed: an unchanged save produces the same JSON as 0.42.4, and the same edit sequence (internal fallback location proxied to a dedicated backend, backend change, cache/method/rewrite changes, reordering, deletion) produced identical configuration and identical proxy responses in 0.42.4 and 0.43.0. +- **Vhost / Custom location error fallback:** "Intercepted status codes" is replaced by a status picker (403, 404, 500, 502, 503, 504) labelled "Run the fallback for these upstream statuses", with clearer help that explains `error_page` semantics and scope (main route vs. one location). The target field suggests the IDs of enabled internal locations. Saved `error_fallback` JSON is unchanged; at least one status always stays selected, and statuses are inactive until a target is set. +- **FastCGI / PHP-FPM:** TCP connections to the responder use `TCP_NODELAY`; request records are buffered (one write for requests without a body), responses are read through a buffer, and already-received `STDOUT` records are merged into larger body chunks without delaying streamed output. Measured on a local PHP-FPM 8.3 pool: about 5 instead of 15 read/write system calls per small PHP request and 13 instead of 27 for a 200 KB page; throughput on the 2-core test machine stayed within measurement noise. Timeouts, limits, error handling and truncation behavior are unchanged; new regression tests cover many small records with interleaved stderr and a 200 KB upload, prompt delivery of flushed output, and a truncated stream. +- **Panel stylesheet cleanup:** removed rules for classes that no element uses (`cache-reason`, `runtime-information-grid`, `overview-layout-hidden-item`), 20 declarations that a later rule with the same selector always overrides, an empty rule, and two references to undefined custom properties (replaced by their effective fallback). Removed `app/dashboard-layout-editor.js`, which has not been part of the panel bundle since 0.33.7 and targeted elements that no longer exist. Rendering is unchanged. +- Fixed the label of the selected-backend diagnostic header: it is `X-RustProxy-Backend`. + ## 0.42.4 — Vhost/global error pages for generated Web Server and Basic Auth failures - **Web Server:** distinguish RustProxy-generated static and filesystem errors from PHP/FastCGI output and `.htaccess ErrorDocument` responses. Generated errors now use the configured Vhost error page, falling back to the global error page and then the Web Server built-in HTML. Application-provided error bodies remain unchanged unless explicitly selected in Vhost `intercept_statuses`. diff --git a/Cargo.lock b/Cargo.lock index 22444dc..ece2271 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.42.4" +version = "0.43.0" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index a852939..b4cac97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.42.4" +version = "0.43.0" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/SHA256SUMS b/SHA256SUMS index c665fa2..a64d7c9 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,10 +1,10 @@ 61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example 0a5e87541831edca0e7164c6469dba01a8a7053ab14dbfb8019c83e4db10edc2 .gitignore -1c275142e27441c2f70c5361b1065f0cdf5fccf731eaf114a7b2bdf4ae23bd21 AGENTS.md -ecfb8b157f19c966da2523ab0e209966f5cfb7ca7c8525ba74ae72b3437fb7c6 CHANGELOG.md -193d722f4403a57494929392d1256fd73a33246a02edeab9143640b4b61b02ac Cargo.lock -d0a17bcb665bcd7814d41e24d7a462427c1b65ec837700aeedbe8d10b14703c1 Cargo.toml +903ca521af6ef7e54f83dc0b4b0436d116c88f064c36f0317b689b7cce79ab27 AGENTS.md +30a6ceefeeb80279c5bde1fcd698870be76211d4367b8af7b2cd2ae8dcd72b0f CHANGELOG.md +1ed75ec0adde5af3a0fe565689b45a973c5dad8a8e382ea279f631d9688f7326 Cargo.lock +8bfe4cf8793a43e61ad29a013092069381c51120f85c1ef358fd048d6a22556e Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE a8d456f1b84dbc5f412f7dda9b98b4e765578111d31e7b26027aeb83c26f3f54 README.md @@ -45,11 +45,11 @@ bfe96dd91dfc6e07918a662d98b036f12ceb011a5aa8381b3778bd0c964b19ab docs/CACHE.md 51d34823d139ff3b0b8e1cf1a31850746be5ed7da847a2cca51be36fd5f7733a docs/CACHE_TEMPLATE_LIBRARY.md 31285f000cf725d018a926023fe608fec983b959053f7a55e0954b962a8bc20c docs/CERTIFICATES.md 81df6715e2f07617fe0bbb0960c4d5bdac28cf665ce7297fa3768118e6ab28ba docs/CONFIGURATION.md -2cede323fe2767100258b5e1d3e3a8b362e2a91acf2b0ee61090c4a2db97d952 docs/CUSTOM_LOCATIONS.md +32b076170bc2669d676ec78a067efec461a0072ddf8f68df1e7655b208e1c9c0 docs/CUSTOM_LOCATIONS.md 7b286e85330fad398fc6f9df1b894e004a42fb33ab7168eb93f87220a3bf5503 docs/DASHBOARD.md -53cb0ce7db5ce25e4c2381de3a6e875d212deeed08861da63050de6c51a442bd docs/DOCKER_DISCOVERY.md +7279ed7ac64d60ed96d90625dac494f305655883aba538c7b6fbcd0d801bdc99 docs/DOCKER_DISCOVERY.md 279afcf0b5b8d2f8ef7b723ba0b5050ca4536f14445f3ee1b71e9f32b800bb9b docs/ERROR_PAGES.md -d297397fad57b3fbaf876025e8b3aceb15307d745272d75b1428d498e7153570 docs/FASTCGI.md +469e5d59d2fcab76f2610571cb9cbbba51cbadb40fec2495b3389a94f0c7b591 docs/FASTCGI.md 01b6d461d6b17b321d63cfb51435814858b29b437ed3e0bb13aba4351eaaf735 docs/FEATURES.md f7bb59821e0d6c45ae2a1789086fd9dab33d91c0ceae784ae68f64bd13b5f496 docs/HEADLESS.md bce732d845c23ad677ae811e7529b9322ab41d04ca808e04087d0f76bccd9309 docs/INSTALL.md @@ -59,7 +59,7 @@ e5e50be31b3160588599336b1871b07a1e829b202454a67d2dc4e2e754d23eab docs/LOGS.md 48105c4303401aa99ffff00d3ebaf3024535a492a4a7b883c6803e4732b37434 docs/MONITORING.md 6d3937088eeb67a9f690d44ebe0b6e660b68116dbf69091ac7816bdc52cec2b6 docs/PERFORMANCE.md 96a69bf9b68e72e6f352f23173bcd0b013af8d6d9cef56141e49efbe35f68f2d docs/PHP_FPM.md -45ce24998bda40e60f34756bef29616114aec9fd5cdd5e1aed692ff2371a3af1 docs/POLICY.md +b0c97a728d4c2d372e483d14bd8383bec17869e634cc0123f7919c1e56b7ac91 docs/POLICY.md 54e9e771707777144105a59c4d6dd6589cc74d735aea660af5366283cf820ee6 docs/README.md e90842a75459ddb5892334f66a4139d9301280b4d0c17077d211749bd7c90d80 docs/RESPONSE_DELIVERY.md 95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md @@ -138,8 +138,8 @@ e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/r 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh ae2ee2887fcba096d0de25edcc18faa1ffec35759274518db1bf6d6982f7176c langs/README.md -8d4af9a24fd055c670ce3d4578ae6dcd21e95f5fe5a8edd86ebc8c11c4ca4e24 langs/en_US.json -4e090839dd038a41d09a445347fe3381f88dce1446e4c46607dbfa44d854fd40 langs/pl_pl.json +44f13c8577f0c2a6798d3b977f41291800446b2b0ddecde5e8e5974bc4fcc9d9 langs/en_US.json +427774933ff725ca6a6568ddf42a615793e4e72a2c2de5e2655b66d5b308fed1 langs/pl_pl.json 38773ed251a8c24af353f4744e498ae2bc7d4151df7927e942c4ac223f6008e1 make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -213,7 +213,7 @@ f9b2c8fe62cc92d7693e46145b2543b12dd6d4943fe2d52c67ed6958d4af83de src/admin/docu e2253599b5e39510946729920d240711403a3889cc495eb49824296228f1d080 src/admin/file_logs_query.rs 1594c8666991c1d07487a6a718211ef404cf49114721960f7e119bb7f605e3d2 src/admin/logging_api.rs 781fd5f176dd8f2372f75bd90edcf160708e2d0a8d6a115ba4b283c0cd49eb2d src/admin/mod.rs -e04ae9e0a71d41849315dbebfb51755e7e73489741ffa0fd6b815a6e74be576a src/admin/openapi.json +10e2b373b117fa40d8b42bcb055a9c8bd26e6d3ac24e70dab9c44fa96f16e01a src/admin/openapi.json 9f8842cdec27d703d1795dd6eb37d9420e9f5a2e56a0df93278c92bace5d1f4c src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs @@ -243,10 +243,9 @@ aed3aea4eef0011c6b51d39736782e7d1ec52662e422f40e0c7b9ddfc19d0378 src/admin/web/ dedda129e173a347ebca9445c8a313849d1d678c256deabeb18f9977559e021a src/admin/web/app/config-history.js 112498688da2641cc44c1205c303ea08e20919cf61365db34c2988a1b8eee565 src/admin/web/app/core.js 1fe90b27e241477e67b24283f3ae8a15a1770e3a3a8f5017a0732396294bff90 src/admin/web/app/dashboard-inline-layout.js -ce6518e953908b302c034346ec13ddaec308950ca2af1d54d063a87ff03efab3 src/admin/web/app/dashboard-layout-editor.js e9830fdbaaf0a671f7ce2121564cfd7960c49733b172a4bd927f15d0e722fc4d src/admin/web/app/dashboard-presets.js fce1fe268749b28ab68ac41519ced05252c1193f11bc9a3851de45dae4c419ad src/admin/web/app/docker-dashboard.js -f01c5fe8eb9c8249b1d07563f42bb63c397de0b602eb178c131b8a9e50d3b1c4 src/admin/web/app/icons.js +78569bbc055a6fe2e689ea372b6dad922350ba0dcc090c192dca7cd5d1f2c407 src/admin/web/app/icons.js 9fc3165febd83a6661b2827aacd612fbc0f834e99ef1585ec54e03e97fe54a72 src/admin/web/app/logo-animation.js 92ed982c3ac4bc4218a24a200d2a33f30fc6705b77b260db2be31b0ce91a7df9 src/admin/web/app/memory-breakdown.js e165db3dd12be8dbff2dfffe3bb9608ce9125924cb97558c26826e9f3d070699 src/admin/web/app/overview-extra-metrics.js @@ -284,21 +283,21 @@ e9cfe14e8e5093e8f8be504d9590643d71935846241f4e73ea4afcafb7f0f806 src/admin/web/ 9efc37b434336db30333f28c09e14355c45332e1d28c64bb6b88f875ba9fd297 src/admin/web/cf_page/placeholder.html 38bb67d9ec6b6e08298d63267afa3a92cbc0818fb0a21fc39520afdca4a995e4 src/admin/web/cf_page/welcome.html c2912a5e218896177776d4c5920e240092a3de66f9a4b95c1631796771e0ce3c src/admin/web/css/00-tokens.css -a7bfda3be5d72876679d532f03db00705f5e11426d665d8d1e6dc5b35e389c22 src/admin/web/css/10-base.css +90a03a0ec649801837a85b2cc3dfa2eb3b4b504c25a8f96e4fa3278afb84bbb3 src/admin/web/css/10-base.css 9cd9b62ff8cfba47cb180e29ea5f69b8e97c7817dfcfddcb55fc4e08d11a7184 src/admin/web/css/20-shell.css -5af483ff7937ff245d8718179dc6001716d2b279f6ce935f5aa0c9fcfa370ab8 src/admin/web/css/30-overview.css -2763ff8969567cbd001ba4b5d5b669aea7aec347088ffe7c2b164b82396755d5 src/admin/web/css/40-editors.css -5dc4d6c8329e44e9a5bba4b5ef8d5afaca8fabf580954c3578e63187eee6f92d src/admin/web/css/50-settings.css -3c6914b1a896627abd83efca18c7c4d769b8d6e301bf5cf95044b0325cb26082 src/admin/web/css/55-policy.css -1bda60afe216056d74776774c2afbb9dfda1ff6b4628835fa6951e7bdee1a171 src/admin/web/css/60-monitoring.css -28202c943f6b98157eb4f25354f51a245ffa0b6e035f997901e460ea24d538b8 src/admin/web/css/70-responsive.css +fa12ba689dd8002c3a8bf2b4d05de210ea2b6793d90d9e318da9ebfa07dace65 src/admin/web/css/30-overview.css +7893733ce807ccc83e8ededbb5b9fb7b76e8e8f8257897615147b9f91410ed41 src/admin/web/css/40-editors.css +5029fad7af88e1d4bc3f72cc66c0899c47c4269d51637e12e4efe2c1a8310841 src/admin/web/css/50-settings.css +fbaca765920866bb77280d3d762a81ffdd4e730869d87c3e653b2d298b39ef89 src/admin/web/css/55-policy.css +7691a9608e376bcc1f0802edef8b19e5c5ecb522e560a2fa7168a14985eb561a src/admin/web/css/60-monitoring.css +9e0836087aba67d7493d515a54435234785416adb730b40881afafff80739302 src/admin/web/css/70-responsive.css 4149881632a6ed48340443c51362c59d2ac7ae16eba8d724fa9a9555d2af8314 src/admin/web/css/README.md ea08fbe1a616042f2dab32d829dba837660a5facb068bb9d5a9b3abdb5c00717 src/admin/web/css/manifest.json 7d3c09f13e3026e3230f35472a9d163b790c7c68b672127ed9fb0e66b26e3d70 src/admin/web/dashboard-builtin-presets.json 78bf6179f769b68d518028464697e50dea5d75e33ecb1b89d88e2c2b01e86bf2 src/admin/web/dashboard-defaults.json 355046ecb80ce6adb73ceabd29825b0cf79ca364771070cedd5eb44760fae890 src/admin/web/dashboard-widgets.json 50d1ebcbaf4d0b2968da23bb943fc3f67131c5d32df3f61d23ff37aad9da5b81 src/admin/web/demo.html -fb2800f2bcbe06d1cd933d5f0e8082e2b098aee41cedb00850b4371560650fe3 src/admin/web/docker.js +95da56f5fa86b9f973de4cc47001196a674ec8947d8811f2c9b0bd90f9e416ec src/admin/web/docker.js 8bf5d1f4f06d6e87536d808a680bf3d3a0c90c1637df0e58da667fd22ad4782d src/admin/web/docs.css aeffd403fa1823df7d9fa4c48280b4033b2d15e4cb9f66608caff89290de0a52 src/admin/web/docs.html 306db8db9e4d651a85e09dbc15464e7f920d7fe5bd9ec9d1d8068321eb0106ab src/admin/web/docs.js @@ -331,7 +330,7 @@ bd94e61e051a6bebe0afbda0a21aa36349c2067516b974986765555ed47455cc src/admin/web/ 943121aaaaddcee81ce70fb153820666d06a41abab17d60c20c7e3dba1894f8c src/admin/web/policy.js 80d6eb03f204a90f7b140c5b053d0fd8facb350b1c96b74fa1402e2a35d4fb10 src/admin/web/prometheus-token.js bb16f579d1de89c565c95adb496def4051553f17d928d2128f4bf08ca66e5ca1 src/admin/web/redirects.js -86700d2cb268ecf6eae8292acc6513b9c650810a5290823e7e2d69f836ba3537 src/admin/web/settings.js +a68bc028c6b12a8c02ab097c49cfba57cf596da4a995d04d89dbd56980656958 src/admin/web/settings.js 8eadbada619b15087783dcfa0e889a81f88e78034d084c5ab616f7912b835940 src/admin/web/status_200.html 6322e589c449eee6db9c3499bb5643d6261f5fc3a5d730cff12cef70d5699fa2 src/admin/web/streams.js 14ef42dec556c5fa62ff4ed4d6865d28f322e8e963dc43e3a714ef9d0af12ac6 src/admin/web/system-info.js @@ -339,8 +338,8 @@ bb16f579d1de89c565c95adb496def4051553f17d928d2128f4bf08ca66e5ca1 src/admin/web/ 336cc5b2a3e5e2514b6b15eed5f2b1ba714458d0e3e913d6f9ad7c870623c758 src/admin/web/traffic-panel.js 675ea169d4cc55fda5e291af536338b882bede1eaa6c9d5cc7dfde0779c7c4d1 src/admin/web/transform-panel.js c30373b0f2dc5672f88bc6fad0ffd5f6d85496d75da8fae83c6aa306e4e0f676 src/admin/web/vhosts/balancing.js -2035bbee6d91aa124fecc0de4fb97c418b7cdba7fb06a3dde0885b929bc9ffff src/admin/web/vhosts/core.js -1920fd45cb922ffdea5401f998f1307fb021174fefa9a1a35e4659960b2c6b2c src/admin/web/vhosts/editor.js +95ba07e8533c39b05db12a45375a8ff1a3e70d3ca9224cd6e7c5b7a5905242ef src/admin/web/vhosts/core.js +b73051f1ecfecac3ccd4283e8c703983c0ab7c2c1868026b26d046c6859ae485 src/admin/web/vhosts/editor.js f082588c35d981fc689542d4c12a7614638279335220d587fdee5d3fff822e80 src/admin/web/vhosts/headers-tab.js 3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js @@ -650,8 +649,8 @@ c8722700c4e42b5daa212e70a4c56938f41c1ada8c541cb6b614a2d496369741 src/vhost/test a4d394582f34ab16bb046780d4f755c6bbcc6afb497b03e277980750ab2e5f25 src/web_server/config/model.rs 9a3056d371219b7327d612b40b89587a0c30c7f8487386ba95e69050d0bdf11f src/web_server/config/validation.rs 86c744216d7132d8294a6e90ba9be5fd871646006313d1c62506d40c81db9b12 src/web_server/fastcgi.rs -d15716d8fa0d722e3189367fd395cac71c2f2a178335120a74a01696abc7cc04 src/web_server/fastcgi/protocol.rs -6b24c3ed2249e7c0d29ab27a5bc8ea05527a2a0314ae067acd6035327db3e814 src/web_server/fastcgi/response.rs +c0a00d9e72a41250ed75e1a3551098936d16e0abf4cc0b42c184dad7e9991bdb src/web_server/fastcgi/protocol.rs +508da845651652641110ec850034385a49b53e5698065635228627a6a56e3731 src/web_server/fastcgi/response.rs 92d2ab4d7ecb766bbc705f8eba94c1ca33347ffb84b36e0ad0eccfed5915473f src/web_server/filesystem.rs d4fec3682532b0f2d11a0aefcd024f69fb623a39922ddb6c528a2d2de265347d src/web_server/htaccess.rs a4d955e9225022a4402885cbbe9b03929a651acb8eac57d304dac297f075eb14 src/web_server/htaccess/model.rs @@ -669,7 +668,7 @@ e5f5fbe702f66bfcbcbc1d1f3cd3d89bdbb929bb86aed94868a2a06a4b9e59e3 src/web_server 2665d4eac9a6430d68224874784cb65d9b9d424353af77735caf044401d08cb4 src/web_server/routing.rs 9e584eb4455a18641c2c89f9e9725745c93f32877abf0f0f2fbea9e3d5ef38c3 src/web_server/security.rs ca7fbabd87fa117f6cfd9cccb2375396432a999f15d4e9af0f6f3420eb2ae57f src/web_server/serve.rs -8b20e20a967c75b9510c48fad1a9465b55012b2fbc46587e473337b36cb5f397 src/web_server/tests.rs +3b2005d4e0dfa7597b4577363eebd6e5afb96f5f356a2c96905f5af1f9cc2058 src/web_server/tests.rs f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures/argon2id.json 9540e9a904455a2190c2d0a32b47b1345976e4c4618767ed2b55898d13da9987 tests/fixtures/balance_rendezvous_vectors.txt affb5c728d2d2bd58807c080f22ac17575e06486c7cca38dc13cf58ad01873ae tests/fixtures/routing_conditions_cases.json diff --git a/docs/CUSTOM_LOCATIONS.md b/docs/CUSTOM_LOCATIONS.md index 4730d3e..89624e0 100644 --- a/docs/CUSTOM_LOCATIONS.md +++ b/docs/CUSTOM_LOCATIONS.md @@ -2,6 +2,16 @@ Custom locations add exceptions to a Vhost's normal source. They are **not** required for the root path `/`: any request not matched by a custom rule continues to the Vhost's main backend pool or Web Service. Configure them under **Vhosts → Edit → Custom locations**. +## Panel layout + +The list works as a routing table: each collapsed row shows its order, on/off state, ID, match type, path or conditions, the action (proxy target, Web Service, redirect or fixed response) and what it sets differently from the Vhost (access, headers, cache, own balancing, HTTP policies, error fallback). Click a row to edit it: + +1. **When — match:** ID, match type, path or regular expression, *Internal named location* and optional request conditions. +2. **What — action:** proxy to a backend (one backend, the Vhost pool or a group), a Web Service, a redirect or a fixed response, plus the backend path rewrite. Only the fields of the chosen action are shown. +3. **Options:** tabs for Access (ACL profile, HTTP methods, countries, inline IP rules), Headers, Cache, Errors (error fallback), Backends & balancing and HTTP policies. A tab shows a short state when the location sets something there; empty tabs inherit the Vhost settings. + +**Add location** offers starting points (path to another backend, files/PHP from a Web Service, redirect, fixed response, internal location for `error_page`, whole-host rule, empty location). They only pre-fill ordinary fields; everything stays editable. The effective behavior preview and the Up/Down/Delete actions remain at the bottom of each location. Saved JSON is identical to earlier releases. + ## Path matching | Match mode | Purpose | Priority | @@ -91,6 +101,8 @@ Each location can add request/response header operations (`set`, `append`, `remo Mark a location **Internal** to make it unavailable to ordinary public URI matching. A Vhost or location may direct specific origin responses (`403`, `404`, `500`, `502`, `503`, `504`) to a named internal location ID in the same Vhost. The dispatch is internal, not a browser redirect; request context and access evaluation are preserved. Invalid targets or loops are rejected. +In the panel, the Vhost **Locations** tab has an **Error fallback (error_page)** section for the main route (requests not matched by any location), and each location has the same two controls under **Options → Errors**: the fallback location (suggestions list the enabled internal locations) and a status picker. A location's fallback applies only to requests it handles; it does not inherit the Vhost-level fallback. The statuses are inactive until a fallback location is set, and at least one status stays selected. + If all you need is a different error **page body**, use **Vhost → Pages → Intercept application error responses**, which keeps the original status without making a second origin request. ## Not an Nginx configuration parser diff --git a/docs/DOCKER_DISCOVERY.md b/docs/DOCKER_DISCOVERY.md index 70ce334..f2cc490 100644 --- a/docs/DOCKER_DISCOVERY.md +++ b/docs/DOCKER_DISCOVERY.md @@ -156,7 +156,7 @@ In **Docker vhosts**, select the service and set: | **Force HTTPS / WebSockets** | Enable only when needed and when the right frontend listeners exist. | | **Cache / compression / transforms** | Optional; obey the global limits and privacy policy of the application. With **Cache** enabled, **Cache for this vhost** sets a default TTL (empty = global default) and the same cache rules editor as an ordinary vhost (templates, VCL import/preview, compact two-section tester, *Ignore global cache rules*). **Cache & VCL guide** opens the shared modal and inserts examples into this Docker vhost's importer, never the global editor. Tests use unsaved service rules plus saved applicable global rules, unless ignored; a path-only test uses the current service hostname as `Host` when no explicit Host is provided. Unpublished service tests may lack saved vhost settings; see [Cache rules](CACHE.md#cache-rules-vcl-style). Stored as `cache_default_ttl_seconds`, `cache_rules` and `cache_ignore_global_rules` on the assignment. | **Security and access** | Everything an internet-facing app usually needs, without creating an ordinary vhost: **HTTP Basic Auth** (see below), **HTTP methods** (allow only / block listed, the same method picker as vhosts), **per-client IP rate limit** (requests per window and burst; exceeded requests get `429`), **country access** (block or allow only listed countries via GeoIP; country rules of ACL profiles also apply), **security headers** (HSTS with max-age and includeSubDomains, `X-Content-Type-Options: nosniff`, `X-Frame-Options`, `Referrer-Policy`) and **Use verified Cloudflare client IP** when the app is behind Cloudflare. The summary line of the section shows what is active. Stored as `method_policy`, `rate_limit`, `security_headers` and `cloudflare_client_ip`; unused options are not stored. Docker apps have no login of their own; to require one, publish the app through an ordinary vhost with HTTP Basic Auth, forward auth or OIDC. | -| **Diagnostic headers** | `Server-Timing`, the selected backend (`X-Rust-Proxy-Backend`) and the backend time, for testing; keep them off in production. For Docker publications the backend header uses `/<12-character-service-hash>` (for example `node1/012345abcdef`), rather than the internal `docker-node1-012345abcdef/docker` identifier. Ordinary Vhosts retain their usual backend IDs; the change affects only header presentation, not routing, logs or metrics. Stored as `timing_headers`, `backend_header`, `backend_timing_header`. | +| **Headers** | Diagnostic headers — `Server-Timing`, the selected backend (`X-RustProxy-Backend`) and the backend time (`X-RustProxy-Backend-Time`), for testing; keep them off in production. The collapsed **HTTP policies** editor inside this section holds the assignment's policy rules (see [HTTP policies](POLICY.md)); the section summary shows the enabled headers and the rule count. For Docker publications the backend header uses `/<12-character-service-hash>` (for example `node1/012345abcdef`), rather than the internal `docker-node1-012345abcdef/docker` identifier. Ordinary Vhosts retain their usual backend IDs; the change affects only header presentation, not routing, logs or metrics. Stored as `timing_headers`, `backend_header`, `backend_timing_header`. | | **Health / ACL / timeouts** | **Access control** shows the agent default ACL profiles pre-selected (*Agent default in use: …*). Unchecking or changing them overrides the default for this service only; leaving them as they are keeps following the agent default. **Public vhost (no agent default ACL)** publishes the service without the agent default profiles (`inherit_acl_profiles: false`) and disables the per-app ACL; global block/allow rules still apply. Up to eight reusable ACL profiles per app; selected profiles appear as removable badges and the summary line shows the effective state. Optional inline ACL remains independently enforced. Explicit denies and country blocks beat merged allows. Test allowed and blocked clients. | ### HTTP Basic Auth for Docker apps diff --git a/docs/FASTCGI.md b/docs/FASTCGI.md index 8fdb671..90a5627 100644 --- a/docs/FASTCGI.md +++ b/docs/FASTCGI.md @@ -112,6 +112,14 @@ curl -Ik https://n.linuxiarz.pl/nagios/.htaccess Expect redirects for `/` and `/nagios`, a Basic Auth challenge without credentials, a PHP/static page for `/nagios/`, FastCGI output (not CGI source code) for the CGI URL, and `403` for dotfiles (a Basic Auth challenge may happen first). A `502` suggests a missing backend/socket or bad socket permissions; a `403` can also mean the script is inaccessible/non-executable, and `404` can mean a wrong rewrite or document root. The exact Nagios page may require additional stylesheets/aliases or Nagios-specific CGI environment and permissions. Test these against a real installed Nagios, not only a mock FastCGI server. +## Connection handling + +Each FastCGI request uses one new connection to the configured endpoint (no `FCGI_KEEP_CONN` pooling). A PHP-FPM worker serves one connection at a time, so keeping idle connections open would pin workers that other requests need. + +- TCP endpoints are opened with `TCP_NODELAY`; the request records (`BEGIN_REQUEST`, `PARAMS`, `STDIN`) are written through a 16 KiB buffer, so a request without a body is sent in a single write. With a request body, the parameters are sent first and the body follows as it arrives from the client. +- Responses are read through a 32 KiB buffer. `STDOUT` records that have already arrived are merged into one body chunk of up to 64 KiB; RustProxy never waits for more output to fill a chunk, so `flush()` in the application still reaches the client immediately. +- The connect/request timeouts, concurrency limit, header limit and stderr limit are unchanged. + ## Migrating from Nginx / Angie | Original directive | RustProxy equivalent | diff --git a/docs/POLICY.md b/docs/POLICY.md index 369a818..6240340 100644 --- a/docs/POLICY.md +++ b/docs/POLICY.md @@ -17,7 +17,7 @@ below. VCL remains the owner of its existing cache-rule precedence and terminal - In the panel, open **Settings → Rules & headers → HTTP policies** globally, **Vhost → Headers → HTTP policies**, the location's **HTTP policies** section, - or the Docker assignment's policy section. The shared editor offers a rule + or **Docker Vhosts → service → Headers → HTTP policies** for a Docker assignment. The shared editor offers a rule builder, scenario presets, a JSON view, import preview and a draft tester. Global settings use the same editor at `settings?tab=policies`. Reordering uses the visible rule order; switching views preserves the same policy object. diff --git a/langs/en_US.json b/langs/en_US.json index 17bb9bb..eb58fe7 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -865,6 +865,30 @@ "locationAccess": "Location access control", "locationHeaders": "Location headers", "locationAddBackend": "Add dedicated backend", + "locationStepWhen": "When — match", + "locationStepWhat": "What — action", + "locationStepOptions": "Options", + "locationTabAccess": "Access", + "locationTabHeaders": "Headers", + "locationTabCache": "Cache", + "locationTabErrors": "Errors", + "locationInternalShort": "internal", + "locationChipBalancing": "own balancing", + "locationChipFallback": "fallback", + "locationTplProxy": "Path to another backend", + "locationTplProxyHelp": "e.g. /api/ → a selected backend, prefix stripped", + "locationTplWeb": "Files / PHP from a Web Service", + "locationTplWebHelp": "e.g. /static/ or a PHP application", + "locationTplRedirect": "Redirect", + "locationTplRedirectHelp": "old path → new URL, 301–308", + "locationTplReturn": "Fixed response", + "locationTplReturnHelp": "/healthz, robots.txt, maintenance text", + "locationTplInternal": "Internal location (error_page target)", + "locationTplInternalHelp": "not matched by URLs; served as an error fallback, e.g. proxy to an error backend", + "locationTplHostHelp": "any path when a header, cookie or client IP matches", + "locationTplBlank": "Empty location", + "locationTplBlankHelp": "all fields, no presets", + "locationChipGroup": "group of {count}", "locationAdd": "Add location", "locationHelp": "The longest matching prefix wins. The original path and query are retained. Select a backend from this host or add a dedicated backend. Host authentication and ACL always apply.", "aclUse": "Enable IP access list", @@ -1540,7 +1564,7 @@ "logUpstreamError": "Upstream error", "listenerDefaultPortsHint": "New vhosts automatically select the standard HTTP :80 listener when it is available.", "vhBackendDiagnostics": "Backend diagnostics", - "vhBackendHeader": "Selected backend (X-Rust-Proxy-Backend)", + "vhBackendHeader": "Selected backend (X-RustProxy-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.", @@ -1614,6 +1638,10 @@ "dockerClientIp": "Client IP", "dockerDiagnostics": "Diagnostic headers", "dockerDiagnosticsHelp": "Server-Timing, selected backend and backend time in responses; for testing, off in production", + "dockerHeaders": "Headers", + "dockerHeadersHelp": "Diagnostic response headers and HTTP policy rules", + "dockerPolicyRuleCount": "Rules: {count}", + "dockerPolicyNone": "No rules", "dockerRefresh": "Refresh agents", "dockerAgentsSettings": "Docker agents settings", "dockerAgents": "Docker agents", @@ -2619,13 +2647,15 @@ "vhWwwNoHosts": "Add an exact hostname above to enable a WWW redirect. Wildcards cannot be the destination.", "vhWwwSharedCount": "{count} names / one vhost", "vhWwwEnable": "Enable 308 redirect", - "vhErrorFallbackTarget": "Main error fallback target", - "vhErrorFallbackStatuses": "Intercepted status codes", - "vhErrorFallbackHelp": "Target must be an enabled internal Custom Location. Supported statuses: 403, 404, 500, 502, 503, 504. The request is dispatched internally without an HTTP redirect.", + "vhErrorFallbackSection": "Error fallback (error_page)", + "errorFallbackTargetPlaceholder": "off — e.g. errors", + "vhErrorFallbackTarget": "Fallback location (internal location ID)", + "vhErrorFallbackStatuses": "Run the fallback for these upstream statuses", + "vhErrorFallbackHelp": "Nginx error_page equivalent for the main vhost route (requests not matched by a Custom Location). When the backend or Web Service answers with a selected status, RustProxy serves the chosen enabled internal Custom Location instead — an internal dispatch, not an HTTP redirect. Leave the location empty to turn it off.", "locationInternal": "Internal named location", - "locationErrorFallbackTarget": "Error fallback target", - "locationErrorFallbackStatuses": "Intercepted status codes", - "locationErrorFallbackHelp": "Optional Nginx-style error fallback. Target an enabled internal location by ID. Supported statuses: 403, 404, 500, 502, 503, 504.", + "locationErrorFallbackTarget": "Fallback location (internal location ID)", + "locationErrorFallbackStatuses": "Run the fallback for these upstream statuses", + "locationErrorFallbackHelp": "Applies only to requests handled by this location; the vhost-level fallback is not inherited. Pick an enabled internal location; it is served for the selected statuses without an HTTP redirect.", "webServicePhpPathInfo": "Enable FastCGI PATH_INFO splitting", "phpProfileSelect": "FastCGI configuration source", "phpProfileLocal": "Local configuration", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index d676c4c..2d316e9 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -865,6 +865,30 @@ "locationAccess": "Dostęp do lokalizacji", "locationHeaders": "Nagłówki lokalizacji", "locationAddBackend": "Dodaj osobny backend", + "locationStepWhen": "Kiedy — dopasowanie", + "locationStepWhat": "Co — akcja", + "locationStepOptions": "Opcje", + "locationTabAccess": "Dostęp", + "locationTabHeaders": "Nagłówki", + "locationTabCache": "Cache", + "locationTabErrors": "Błędy", + "locationInternalShort": "wewnętrzna", + "locationChipBalancing": "własne balansowanie", + "locationChipFallback": "fallback", + "locationTplProxy": "Ścieżka do innego backendu", + "locationTplProxyHelp": "np. /api/ → wybrany backend, z obcięciem prefiksu", + "locationTplWeb": "Pliki / PHP z Web Service", + "locationTplWebHelp": "np. /static/ albo aplikacja PHP", + "locationTplRedirect": "Przekierowanie", + "locationTplRedirectHelp": "stara ścieżka → nowy URL, 301–308", + "locationTplReturn": "Stała odpowiedź", + "locationTplReturnHelp": "/healthz, robots.txt, tekst przerwy technicznej", + "locationTplInternal": "Lokalizacja wewnętrzna (cel error_page)", + "locationTplInternalHelp": "nie pasuje do URL-i; obsługuje fallback błędów, np. proxy do backendu stron błędów", + "locationTplHostHelp": "dowolna ścieżka, gdy pasuje nagłówek, cookie lub IP klienta", + "locationTplBlank": "Pusta lokalizacja", + "locationTplBlankHelp": "wszystkie pola, bez ustawień wstępnych", + "locationChipGroup": "grupa: {count}", "locationAdd": "Dodaj lokalizację", "locationHelp": "Wygrywa najdłuższy pasujący prefiks. Ścieżka i query pozostają bez zmian. Wybierz backend hosta lub dodaj osobny. Uwierzytelnianie i ACL hosta obowiązują zawsze.", "aclUse": "Włącz listę dostępu IP", @@ -1540,7 +1564,7 @@ "logUpstreamError": "Błąd upstreamu", "listenerDefaultPortsHint": "Nowy vhost automatycznie wybiera standardowy listener HTTP :80, jeśli jest dostępny.", "vhBackendDiagnostics": "Diagnostyka backendu", - "vhBackendHeader": "Wybrany backend (X-Rust-Proxy-Backend)", + "vhBackendHeader": "Wybrany backend (X-RustProxy-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.", @@ -1614,6 +1638,10 @@ "dockerClientIp": "Adres IP klienta", "dockerDiagnostics": "Nagłówki diagnostyczne", "dockerDiagnosticsHelp": "Server-Timing, wybrany backend i czas backendu w odpowiedziach; do testów, na produkcji wyłączone", + "dockerHeaders": "Nagłówki", + "dockerHeadersHelp": "Nagłówki diagnostyczne odpowiedzi i reguły HTTP", + "dockerPolicyRuleCount": "Reguły: {count}", + "dockerPolicyNone": "Brak reguł", "dockerRefresh": "Odśwież agentów", "dockerAgentsSettings": "Ustawienia agentów Dockera", "dockerAgents": "Agenty Dockera", @@ -2619,13 +2647,15 @@ "vhWwwNoHosts": "Dodaj powyżej konkretną domenę. Wildcard nie może być adresem docelowym.", "vhWwwSharedCount": "{count} nazw / jeden vhost", "vhWwwEnable": "Włącz przekierowanie 308", - "vhErrorFallbackTarget": "Główny cel fallbacku błędów", - "vhErrorFallbackStatuses": "Przechwytywane kody statusu", - "vhErrorFallbackHelp": "Cel musi być włączoną wewnętrzną Custom Location. Obsługiwane statusy: 403, 404, 500, 502, 503, 504. Request jest przekazywany wewnętrznie, bez redirectu HTTP.", + "vhErrorFallbackSection": "Fallback błędów (error_page)", + "errorFallbackTargetPlaceholder": "wyłączone — np. errors", + "vhErrorFallbackTarget": "Lokalizacja fallbacku (ID lokalizacji wewnętrznej)", + "vhErrorFallbackStatuses": "Uruchom fallback dla tych statusów upstreamu", + "vhErrorFallbackHelp": "Odpowiednik error_page z Nginx dla głównej trasy vhosta (żądania niedopasowane do żadnej Custom Location). Gdy backend lub Web Service zwróci zaznaczony status, RustProxy obsłuży zamiast tego wybraną włączoną wewnętrzną Custom Location — wewnętrznie, bez przekierowania HTTP. Pozostaw lokalizację pustą, aby wyłączyć.", "locationInternal": "Wewnętrzna nazwana lokalizacja", - "locationErrorFallbackTarget": "Cel fallbacku błędów", - "locationErrorFallbackStatuses": "Przechwytywane kody statusu", - "locationErrorFallbackHelp": "Opcjonalny fallback błędów w stylu Nginx. Wskaż ID włączonej lokalizacji wewnętrznej. Obsługiwane statusy: 403, 404, 500, 502, 503, 504.", + "locationErrorFallbackTarget": "Lokalizacja fallbacku (ID lokalizacji wewnętrznej)", + "locationErrorFallbackStatuses": "Uruchom fallback dla tych statusów upstreamu", + "locationErrorFallbackHelp": "Dotyczy tylko żądań obsługiwanych przez tę lokalizację; fallback z poziomu vhosta nie jest dziedziczony. Wskaż włączoną lokalizację wewnętrzną; dla zaznaczonych statusów zostanie obsłużona bez przekierowania HTTP.", "webServicePhpPathInfo": "Włącz dzielenie FastCGI PATH_INFO", "phpProfileSelect": "Źródło konfiguracji FastCGI", "phpProfileLocal": "Konfiguracja lokalna", diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 0c78060..0f0b9d7 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "RustProxy Administration API", - "version": "0.42.4", + "version": "0.43.0", "description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only." }, "servers": [ diff --git a/src/admin/web/app/dashboard-layout-editor.js b/src/admin/web/app/dashboard-layout-editor.js deleted file mode 100644 index 9a9df20..0000000 --- a/src/admin/web/app/dashboard-layout-editor.js +++ /dev/null @@ -1,283 +0,0 @@ -window.rustProxyDashboardLayout = (() => { - const dialog = $("overview-layout-dialog"); - const visibleRoot = $("overview-layout-visible"); - const hiddenRoot = $("overview-layout-hidden"); - const saveButton = $("overview-layout-save"); - const cancelButton = $("overview-layout-cancel"); - const search = $("overview-layout-search"); - const typeFilter = $("overview-layout-type-filter"); - const message = $("overview-layout-message"); - const defaultButton = $("overview-layout-default"); - const resetButton = $("overview-layout-reset"); - const resetConfirm = $("overview-reset-confirm"); - const resetCancel = $("overview-reset-cancel"); - const resetApply = $("overview-reset-apply"); - let draft = null; - let dragging = null; - let saving = false; - let opening = false; - - function initialDraft() { - const prefs = window.rustProxyPreferences?.current?.() || ADMIN_APPEARANCE_DEFAULTS; - const order = normalizeDashboardWidgets(prefs.dashboard_widgets); - return { - order, hidden: new Set(normalizeHiddenDashboardWidgets(prefs.dashboard_hidden_widgets, prefs.dashboard_widgets)), - sizes: normalizeDashboardWidgetSizes(prefs.dashboard_widget_sizes) - }; - } - function defaultDraft() { - return { - order: [...ADMIN_DASHBOARD_WIDGETS], - hidden: new Set(ADMIN_DEFAULT_HIDDEN_WIDGETS), - sizes: null, - }; - } - function label(id) { - const widget = ADMIN_DASHBOARD_BY_ID.get(id); - return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id; - } - function visibleIds() { - return dashboardVisualOrder(draft.order, draft.sizes) - .filter(id => !draft.hidden.has(id)); - } - function enterFreeLayout() { - if (draft.sizes === null) { - draft.order = dashboardVisualOrder(draft.order, null); - draft.sizes = {}; - } - } - function reorderVisible(nextVisible) { - enterFreeLayout(); - const iter = nextVisible.values(); - draft.order = draft.order.map(id => draft.hidden.has(id) ? id : iter.next().value); - render(); - } - function move(id, target, after = false) { - const next = visibleIds(); - if (id === target || !next.includes(id) || !next.includes(target)) return; - next.splice(next.indexOf(id), 1); - next.splice(next.indexOf(target) + (after ? 1 : 0), 0, id); - reorderVisible(next); - } - function nudge(id, direction) { - const next = visibleIds(), index = next.indexOf(id), other = index + direction; - if (index < 0 || other < 0 || other >= next.length) return; - [next[index], next[other]] = [next[other], next[index]]; - reorderVisible(next); - visibleRoot.querySelector(`[data-preview-widget="${id}"] .overview-layout-up`)?.focus(); - } - function resize(id, delta) { - if (!draft) return; - const widths = dashboardAllowedWidths(id); - const next = widths[widths.indexOf(dashboardWidgetWidth(id, draft.sizes)) + delta]; - if (next === undefined) return; - enterFreeLayout(); - if (next === dashboardDefaultWidth(id)) delete draft.sizes[id]; - else draft.sizes[id] = next; - render(); - visibleRoot.querySelector(`[data-preview-widget="${id}"] .${delta < 0 ? "overview-layout-narrow" : "overview-layout-widen"}`)?.focus(); - } - function preview(id) { - const original = document.querySelector(`#panel-overview [data-dashboard-widget="${id}"]`); - if (!original) return el("article", label(id), "stat"); - if (ADMIN_DASHBOARD_BY_ID.get(id)?.category === "panels") { - const card = el("article", undefined, "overview-layout-panel-preview"); - card.append(el("strong", label(id))); - const chart = id === "backend_tiny" || id === "backend_table" ? null : original.querySelector?.("svg"); - if (chart) { - const graphic = chart.cloneNode(true); - for (const node of [graphic, ...graphic.querySelectorAll("[id]")]) node.removeAttribute("id"); - graphic.removeAttribute("data-i18n-aria"); - graphic.setAttribute("aria-hidden", "true"); - card.append(graphic); - } - const detailKey = ADMIN_DASHBOARD_BY_ID.get(id)?.description_key; - if (detailKey) card.append(el("small", t(detailKey))); - card.setAttribute("aria-hidden", "true"); - return card; - } - const copy = original.cloneNode(true); - copy.hidden = false; - copy.removeAttribute("data-dashboard-widget"); - for (const node of [copy, ...copy.querySelectorAll("[id]")]) node.removeAttribute("id"); - for (const node of copy.querySelectorAll("[aria-labelledby], [aria-describedby]")) { - node.removeAttribute("aria-labelledby"); node.removeAttribute("aria-describedby"); - } - copy.classList.add("overview-layout-card-preview"); - copy.setAttribute("aria-hidden", "true"); - return copy; - } - function render() { - if (!draft || !dialog) return; - const visible = visibleIds(); - const tiles = visible.map((id, index) => { - const tile = el("div", undefined, "overview-layout-tile"); - tile.dataset.previewWidget = id; - tile.dataset.dashboardSpan = String(dashboardWidgetWidth(id, draft.sizes)); - if (ADMIN_DASHBOARD_BY_ID.get(id)?.category === "panels") tile.classList.add("is-panel"); - tile.draggable = true; - tile.setAttribute("role", "listitem"); - tile.setAttribute("aria-label", label(id)); - const toolbar = el("div", undefined, "overview-layout-tile-toolbar"); - const grip = el("span", "⠿", "overview-layout-grip"); - grip.setAttribute("aria-hidden", "true"); - const up = el("button", "←", "quiet overview-layout-up"); - up.type = "button"; up.disabled = index === 0; - up.setAttribute("aria-label", `${t("moveUp")}: ${label(id)}`); - up.addEventListener("click", () => nudge(id, -1)); - const down = el("button", "→", "quiet overview-layout-down"); - down.type = "button"; down.disabled = index === visible.length - 1; - down.setAttribute("aria-label", `${t("moveDown")}: ${label(id)}`); - down.addEventListener("click", () => nudge(id, 1)); - const hide = el("button", t("overviewLayoutEditorHide"), "quiet overview-layout-hide"); - hide.type = "button"; - hide.setAttribute("aria-label", `${t("overviewLayoutEditorHide")}: ${label(id)}`); - hide.addEventListener("click", () => { draft.hidden.add(id); render(); }); - const widths = dashboardAllowedWidths(id); - const width = dashboardWidgetWidth(id, draft.sizes); - const at = widths.indexOf(width); - const narrow = el("button", "−", "quiet overview-layout-narrow"); - narrow.type = "button"; narrow.disabled = at <= 0; - narrow.setAttribute("aria-label", `${t("overviewLayoutNarrow")}: ${label(id)}`); - narrow.addEventListener("click", () => resize(id, -1)); - const widen = el("button", "+", "quiet overview-layout-widen"); - widen.type = "button"; widen.disabled = at === widths.length - 1; - widen.setAttribute("aria-label", `${t("overviewLayoutWiden")}: ${label(id)}`); - widen.addEventListener("click", () => resize(id, 1)); - const widthValue = el("span", `${width}/12`, "overview-layout-width-value"); - widthValue.title = t("overviewLayoutWidth"); - const sizeActions = el("span", undefined, "overview-layout-size-actions"); - sizeActions.append(narrow, widthValue, widen); - const orderActions = el("span", undefined, "overview-layout-order-actions"); - orderActions.append(up, down, hide); - const controls = el("span", undefined, "overview-layout-controls"); - controls.append(sizeActions, orderActions); - toolbar.append(grip, dashboardWidgetTypeBadge(id), controls); - tile.append(toolbar, preview(id)); - tile.addEventListener("dragstart", event => { - if (event.target !== tile) return; - dragging = id; - event.dataTransfer?.setData("text/plain", id); - if (event.dataTransfer) event.dataTransfer.effectAllowed = "move"; - tile.classList.add("is-dragging"); - }); - tile.addEventListener("dragover", event => { - if (!dragging || dragging === id) return; - event.preventDefault(); - if (event.dataTransfer) event.dataTransfer.dropEffect = "move"; - tile.classList.add("is-drop-target"); - }); - tile.addEventListener("dragleave", () => tile.classList.remove("is-drop-target")); - tile.addEventListener("drop", event => { - event.preventDefault(); - tile.classList.remove("is-drop-target"); - if (dragging && dragging !== id) { - const startIndex = visibleIds().indexOf(dragging); - const targetIndex = visibleIds().indexOf(id); - move(dragging, id, startIndex < targetIndex); - } - dragging = null; - }); - tile.addEventListener("dragend", () => { dragging = null; tile.classList.remove("is-dragging", "is-drop-target"); }); - return tile; - }); - visibleRoot.replaceChildren(...(tiles.length ? tiles : [el("p", t("overviewLayoutEditorEmpty"), "fine")])); - const query = (search?.value || "").trim().toLocaleLowerCase(); - const docker = window.rustProxyDockerDashboard; - const hiddenLabel = id => docker?.isDocker?.(id) ? dashboardWidgetBaseLabel(id) : label(id); - const collapsed = docker?.collapseHidden?.(draft.order.filter(id => draft.hidden.has(id))) || draft.order.filter(id => draft.hidden.has(id)); - const hidden = collapsed.filter(id => (typeFilter?.value === "all" || !typeFilter?.value || dashboardWidgetType(id) === typeFilter.value) - && (`${hiddenLabel(id)} ${dashboardWidgetTypeLabel(id)}`).toLocaleLowerCase().includes(query)); - const hiddenItems = hidden.map(id => { - const item = el("div", undefined, "overview-layout-hidden-item"); - item.setAttribute("role", "listitem"); - const name = el("span", hiddenLabel(id)); - const meta = ADMIN_DASHBOARD_BY_ID.get(id)?.description_key; - if (meta) name.title = t(meta); - const picker = docker?.agentPicker?.(id); - const add = el("button", t("overviewLayoutEditorShow"), "outline"); - add.type = "button"; - add.setAttribute("aria-label", `${t("overviewLayoutEditorShow")}: ${hiddenLabel(id)}`); - add.addEventListener("click", async () => { const slot = docker?.slotFor?.(id, draft.hidden) || id; add.disabled = true; try { await docker?.addWithScope?.(slot, picker); } finally { add.disabled = false; } draft.hidden.delete(slot); render(); }); - item.append(name, dashboardWidgetTypeBadge(id)); - if (picker) item.append(picker); - item.append(add); - return item; - }); - hiddenRoot.replaceChildren(...(hiddenItems.length || query ? hiddenItems : [el("p", t("overviewLayoutEditorHiddenEmpty"), "fine")])); - } - async function open() { - if (dialog?.open || opening || window.rustProxyInlineLayout?.isEditing?.()) return; - opening = true; - try { await window.rustProxyPreferences?.load?.(); } - catch (error) { if (error?.status === 401) { opening = false; return; } } - opening = false; - draft = initialDraft(); - dragging = null; - search.value = ""; - if (typeFilter) typeFilter.value = "all"; - message.textContent = ""; - render(); - dialog.showModal(); - cancelButton.focus(); - } - function setSaving(value) { - saving = value; - for (const control of [saveButton, cancelButton, defaultButton, resetButton, resetCancel, resetApply]) - if (control) control.disabled = value; - } - function restoreDefaultPreview() { - if (saving || !draft) return; - draft = defaultDraft(); - dragging = null; - if (search) search.value = ""; - if (typeFilter) typeFilter.value = "all"; - message.textContent = t("overviewLayoutDefaultLoaded"); - render(); - } - async function resetToDefault() { - if (saving || !draft) return; - setSaving(true); - message.textContent = t("overviewLayoutEditorSaving"); - const defaults = defaultDraft(); - try { - await window.rustProxyPreferences.update({ - dashboard_widgets: [...defaults.order], dashboard_hidden_widgets: [...defaults.hidden], - dashboard_widget_sizes: null, dashboard_widget_heights: null, - }); - resetConfirm.close(); - dialog.close(); - toast(t("overviewLayoutResetSaved")); - } catch (error) { message.textContent = error.message; } - finally { setSaving(false); } - } - async function save() { - if (saving || !draft) return; - setSaving(true); - message.textContent = t("overviewLayoutEditorSaving"); - try { - await window.rustProxyPreferences.update({ - dashboard_widgets: [...draft.order], dashboard_hidden_widgets: [...draft.hidden], - dashboard_widget_sizes: draft.sizes === null ? null : { ...draft.sizes }, - }); - dialog.close(); - toast(t("overviewLayoutEditorSaved")); - } catch (error) { message.textContent = error.message; } - finally { setSaving(false); } - } - for (const id of ["overview-layout-open", "overview-layout-open-settings"]) $(id)?.addEventListener("click", () => { void open(); }); - cancelButton.addEventListener("click", () => { if (!saving) dialog.close(); }); - saveButton.addEventListener("click", () => { void save(); }); - defaultButton?.addEventListener("click", restoreDefaultPreview); - resetButton?.addEventListener("click", () => { - if (!saving && draft && !resetConfirm.open) resetConfirm.showModal(); - }); - resetCancel?.addEventListener("click", () => { if (!saving) resetConfirm.close(); }); - resetApply?.addEventListener("click", () => { void resetToDefault(); }); - resetConfirm?.addEventListener("cancel", event => { if (saving) event.preventDefault(); }); - search.addEventListener("input", render); - typeFilter?.addEventListener("change", render); - dialog.addEventListener("cancel", event => { if (saving || resetConfirm.open) event.preventDefault(); }); - dialog.addEventListener("close", () => { draft = null; dragging = null; message.textContent = ""; }); - return { open, refresh: () => { if (dialog.open) render(); } }; -})(); diff --git a/src/admin/web/app/icons.js b/src/admin/web/app/icons.js index a00364b..1333b3b 100644 --- a/src/admin/web/app/icons.js +++ b/src/admin/web/app/icons.js @@ -302,3 +302,52 @@ const uiIconObserver = new MutationObserver(records => { targets.forEach(uiDecorateIconTarget); }); window.rustProxyIcons = { refresh: refreshUiIcons, setEnabled: setUiIconsEnabled, iconFor: uiIconForTarget }; + +// Shared information popovers (
): one is open at a time, Escape or +// a click elsewhere closes it, and its bubble is kept inside the visible (clipping) area. +(() => { + const MARGIN = 8; + const visibleArea = node => { + const root = document.documentElement; + const area = { left: 0, top: 0, right: root.clientWidth, bottom: root.clientHeight }; + for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) { + const style = getComputedStyle(parent); + if (style.overflowX === "visible" && style.overflowY === "visible") continue; + const rect = parent.getBoundingClientRect(); + area.left = Math.max(area.left, rect.left); area.right = Math.min(area.right, rect.right); + area.top = Math.max(area.top, rect.top); area.bottom = Math.min(area.bottom, rect.bottom); + } + return area; + }; + const reset = details => { details.style.removeProperty("--rp-info-shift-x"); details.classList.remove("is-above"); }; + const place = details => { + const popover = details.querySelector(":scope > .metric-info-popover"), summary = details.querySelector(":scope > summary"); + if (!popover || !summary) return; + reset(details); + const zoom = Number.parseFloat(getComputedStyle(document.body).zoom) || 1, area = visibleArea(details), rect = popover.getBoundingClientRect(); + let shift = 0; + if (rect.right > area.right - MARGIN) shift = area.right - MARGIN - rect.right; + if (rect.left + shift < area.left + MARGIN) shift = area.left + MARGIN - rect.left; + if (Math.abs(shift) >= 1) details.style.setProperty("--rp-info-shift-x", `${Math.round(shift / zoom)}px`); + const anchor = summary.getBoundingClientRect(), viewportBottom = document.documentElement.clientHeight; + if (rect.bottom > Math.min(area.bottom, viewportBottom) - MARGIN && anchor.top - rect.height - MARGIN > Math.max(area.top, 0)) details.classList.add("is-above"); + }; + const openInfo = () => document.querySelectorAll("details.metric-info[open]"); + document.addEventListener("toggle", event => { + const details = event.target; + if (!(details instanceof HTMLDetailsElement) || !details.classList.contains("metric-info")) return; + if (!details.open) { reset(details); return; } + openInfo().forEach(other => { if (other !== details && !other.contains(details)) other.open = false; }); + place(details); + }, true); + document.addEventListener("pointerdown", event => { + openInfo().forEach(details => { if (!details.contains(event.target)) details.open = false; }); + }, true); + document.addEventListener("keydown", event => { + if (event.key !== "Escape") return; + const open = [...openInfo()]; if (!open.length) return; + event.preventDefault(); event.stopPropagation(); + for (const details of open) { const focused = details.contains(document.activeElement); details.open = false; if (focused) details.querySelector(":scope > summary")?.focus(); } + }, true); + window.addEventListener("resize", () => openInfo().forEach(place)); +})(); diff --git a/src/admin/web/css/10-base.css b/src/admin/web/css/10-base.css index 7f162eb..a190421 100644 --- a/src/admin/web/css/10-base.css +++ b/src/admin/web/css/10-base.css @@ -1367,9 +1367,19 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { position: relative; } -.metric-info>summary { +/* One information affordance for the whole panel:
+ with a summary popover, or a .rp-info-icon button that opens a help dialog. + Shape follows the Appearance corner style; colors follow the theme. */ +.metric-info>summary, +.rp-info-icon { + box-sizing: border-box; + flex: 0 0 auto; width: 18px; height: 18px; + min-width: 18px; + min-height: 0; + margin: 0; + padding: 0; display: inline-grid; place-items: center; list-style: none; @@ -1377,9 +1387,10 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { border: 1px solid var(--line); color: var(--muted); background: var(--panel2); - font: 700 10px var(--mono); + font: 700 10px/1 var(--mono); user-select: none; border-radius: var(--rp-radius-control, 50%); + transition: color .12s ease, border-color .12s ease, background-color .12s ease; } .metric-info>summary::-webkit-details-marker, @@ -1391,14 +1402,18 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { } .metric-info>summary:hover, -.metric-info[open]>summary { - color: var(--text); - border-color: var(--border-hover); +.metric-info[open]>summary, +.rp-info-icon:hover, +.rp-info-icon[aria-expanded=true] { + color: var(--accent); + border-color: var(--accent); + background: var(--panel2); } -.metric-info>summary:focus-visible { - color: var(--text); - border-color: var(--border-hover); +.metric-info>summary:focus-visible, +.rp-info-icon:focus-visible { + color: var(--accent); + border-color: var(--accent); outline: 2px solid var(--accent); outline-offset: 2px; } @@ -1414,9 +1429,18 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { border-radius: var(--rp-radius-surface, 6px); background: var(--panel2); box-shadow: 0 12px 30px var(--shadow-mid); + color: var(--text); + font-size: 12px; + line-height: 1.5; white-space: normal; text-align: left; overflow-wrap: break-word; + translate: var(--rp-info-shift-x, 0px) 0; +} + +.metric-info.is-above>.metric-info-popover { + top: auto; + bottom: calc(100% + 7px); } .metric-info-popover .fine { diff --git a/src/admin/web/css/30-overview.css b/src/admin/web/css/30-overview.css index 6a41a7c..ab00148 100644 --- a/src/admin/web/css/30-overview.css +++ b/src/admin/web/css/30-overview.css @@ -1012,23 +1012,6 @@ html[data-dashboard-density=ultra] #panel-overview .stat-cache-outcomes .cache-m font-weight: 600; } -.runtime-information-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); - gap: 12px; -} - -.runtime-information-grid>div { - min-width: 0; - display: grid; - gap: 5px; -} - -.runtime-information-grid code { - overflow-wrap: anywhere; - white-space: normal; -} - .connection-card h2 { display: flex; align-items: baseline; @@ -2073,7 +2056,7 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty border-radius: var(--rp-radius-surface) !important; } -html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(button:not(.nav):not(.file-log-tab):not(.vhost-backend-trigger), input:not([type=checkbox]):not([type=radio]):not([type=range]), select, textarea, .pill, .vhost-backend-protocol-badge, .overview-widget-type, .quiet, .outline, .primary, .code, .command, .dashboard-widget-toggle, .settings-tabs button, .overview-inline-restore), +html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(button:not(.nav):not(.file-log-tab):not(.vhost-backend-trigger):not(.location-tab), input:not([type=checkbox]):not([type=radio]):not([type=range]), select, textarea, .pill, .vhost-backend-protocol-badge, .overview-widget-type, .quiet, .outline, .primary, .code, .command, .dashboard-widget-toggle, .settings-tabs button, .overview-inline-restore), html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(.nav, .file-log-tab, .vhost-backend-trigger, .backend-column-options, .docker-service-quick-actions a, .docker-service-quick-actions button, .docker-view-toggle, .provider-picker, .renewal-meta-item) { border-radius: var(--rp-radius-control) !important; } diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css index d6e2ca2..09e7ab8 100644 --- a/src/admin/web/css/40-editors.css +++ b/src/admin/web/css/40-editors.css @@ -368,12 +368,227 @@ border-bottom: 1px solid var(--row-line); } +/* Collapsed Custom Location = one routing-table row. */ .location-summary { + display: grid; + grid-template-columns: 26px 12px minmax(0, 120px) 120px minmax(0, 1fr) minmax(0, 1.3fr) minmax(0, 1.3fr); + align-items: center; + gap: 4px 10px; overflow-wrap: anywhere; cursor: pointer; - padding: 10px 12px; - font: 600 11px/1.45 var(--mono); + padding: 9px 12px; + font: 400 12px/1.45 var(--sans); color: var(--text); + list-style: none; +} + +.location-summary::-webkit-details-marker { + display: none; +} + +.location-summary:hover { + background: var(--panel2); +} + +.loc-order { + color: var(--muted); + font: 600 11px var(--mono); +} + +.loc-state { + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--green); +} + +.vh-location.is-disabled .loc-state { + background: var(--line); +} + +.vh-location.is-disabled .location-summary { + color: var(--muted); +} + +.loc-id, +.loc-path { + font: 600 11px var(--mono); +} + +.loc-match { + justify-self: start; + padding: 2px 7px; + border: 1px solid var(--line); + border-radius: var(--rp-radius-control, 4px); + background: var(--panel2); + color: var(--muted); + font: 600 10px var(--mono); + white-space: nowrap; +} + +.loc-match.is-internal { + border-color: var(--accent); + color: var(--accent); +} + +.loc-chips { + display: flex; + flex-wrap: wrap; + gap: 4px; + min-width: 0; +} + +.loc-chip { + padding: 1px 7px; + border: 1px solid var(--line); + border-radius: var(--rp-radius-control, 999px); + color: var(--muted); + font-size: 11px; + white-space: nowrap; +} + +.loc-chip.is-fallback { + border-color: var(--accent); + color: var(--accent); +} + +.vh-location[open]>.location-summary { + background: var(--panel2); +} + +.location-headline { + margin: 0; + font: 600 12px/1.5 var(--mono); + overflow-wrap: anywhere; +} + +.location-cards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.location-card, +.location-options { + min-width: 0; + border: 1px solid var(--line); + border-radius: var(--rp-radius-surface, 0px); + background: var(--panel); +} + +.location-card { + padding: 10px 12px 12px; +} + +.location-card-title { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 8px; + font-size: 12px; +} + +.location-card-grid { + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); +} + +.location-step { + color: var(--accent); + font: 600 12px var(--mono); +} + +.location-options-head { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 4px 14px; + padding: 10px 12px 0; + border-bottom: 1px solid var(--line); +} + +.location-options-head>.location-card-title { + margin-bottom: 9px; +} + +.location-tabs { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.location-tab { + min-height: 0; + padding: 7px 10px; + border: 0; + border-bottom: 2px solid transparent; + border-radius: 0; + background: transparent; + color: var(--muted); + font-size: 12px; +} + +.location-tab:hover, +.location-tab.is-set { + color: var(--text); +} + +.location-tab.active { + border-bottom-color: var(--accent); + color: var(--text); + font-weight: 600; +} + +.location-tab-state { + color: var(--muted); + font-weight: 400; +} + +.location-tab-panel { + padding: 12px; +} + +.location-add-menu { + position: relative; +} + +.location-templates { + position: absolute; + z-index: 30; + top: calc(100% + 6px); + left: 0; + width: calc(min(560px, calc(100 * var(--rp-vw)) - 48px)); + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; + padding: 8px; + border: 1px solid var(--line); + border-radius: var(--rp-radius-surface, 6px); + background: var(--panel2); + box-shadow: 0 12px 30px var(--shadow-mid); +} + +.location-templates[hidden] { + display: none; +} + +.location-template { + display: grid; + gap: 3px; + min-height: 0; + padding: 8px 10px; + border: 1px solid var(--line); + background: var(--panel); + color: var(--text); + text-align: left; +} + +.location-template:hover, +.location-template:focus-visible { + border-color: var(--accent); +} + +.location-template>b { + font-size: 12px; } .vh-health-summary { @@ -447,15 +662,10 @@ display: flex; flex-direction: row; margin-inline-start: 0; - gap: 3px; position: sticky; top: 29px; z-index: 2; background: var(--panel); - padding: 5px 0 8px; - border-bottom: 1px solid var(--line); - margin-bottom: 9px; - flex-wrap: nowrap; overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: thin; @@ -464,14 +674,10 @@ .vh-tabs button { width: auto; flex: 0 1 auto; - font-size: 10px; - padding: 6px 9px; white-space: nowrap; } .vh-tabs button.active { - color: var(--text); - background: var(--nav-selected-bg); border-color: var(--green); } @@ -2101,7 +2307,7 @@ html.app-loading, min-width: 0; } -.fine+:is(.switch-grid, .settings-tabs, .table-scroll, .soft-card, .appearance-settings-grid, .runtime-information-grid, details), +.fine+:is(.switch-grid, .settings-tabs, .table-scroll, .soft-card, .appearance-settings-grid, details), .form-actions+.fine, .table-scroll+:is(.empty, .fine), .empty+.file-logs-pager { @@ -2707,4 +2913,55 @@ h2+.fine { .hdr-row.is-invalid .hdr-row-hint { color: var(--red); -} \ No newline at end of file +} +/* Error fallback status picker (vhost and Custom Location). */ +.vh-error-fallback-statuses { + display: grid; + gap: 5px; + min-width: 0; +} + +.vh-status-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.vh-status-chip { + position: relative; + display: inline-flex; + align-items: center; + gap: 5px; + margin: 0; + padding: 3px 8px; + border: 1px solid var(--line); + border-radius: var(--rp-radius-control, 999px); + background: var(--panel2); + font: 600 11px var(--mono); + cursor: pointer; +} + +.vh-status-chip>input { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + opacity: 0; + pointer-events: none; +} + +.vh-status-chip:has(input:checked) { + border-color: var(--accent); + color: var(--accent); + background: color-mix(in srgb, var(--accent) 12%, var(--panel2)); +} + +.vh-status-chip:has(input:focus-visible) { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.vh-error-fallback-statuses.is-inactive .vh-status-chip { + opacity: .55; + cursor: default; +} diff --git a/src/admin/web/css/50-settings.css b/src/admin/web/css/50-settings.css index 38a9970..82d3966 100644 --- a/src/admin/web/css/50-settings.css +++ b/src/admin/web/css/50-settings.css @@ -304,6 +304,7 @@ .docker-protocol-editor, .docker-security-editor, .docker-diagnostics-editor, +.docker-policy-editor, .docker-timeout-editor { border-top: 1px solid var(--line); padding-top: 9px; @@ -315,11 +316,11 @@ .docker-protocol-editor>summary, .docker-security-editor>summary, .docker-diagnostics-editor>summary, +.docker-policy-editor>summary, .docker-timeout-editor>summary { cursor: pointer; display: flex; align-items: center; - justify-content: space-between; gap: 12px; user-select: none; } @@ -641,7 +642,6 @@ html:not([data-switch-controls="false"]) .docker-publish-field input.docker-publ cursor: pointer; display: flex; align-items: center; - justify-content: space-between; gap: 14px; user-select: none; } @@ -1684,8 +1684,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, color: var(--accent); } -.overview-inline-hidden-item .docker-widget-scope, -.overview-layout-hidden-item .docker-widget-scope { +.overview-inline-hidden-item .docker-widget-scope { max-width: 160px; min-height: 26px; padding: 2px 6px; @@ -1707,7 +1706,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, } .docker-spark-primary { - stroke: var(--chart-primary, var(--accent)); + stroke: var(--accent); } .docker-spark-secondary { @@ -1965,26 +1964,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, min-width: 0; } -.docker-label-info { - flex: 0 0 auto; - width: 20px; - height: 20px; - min-height: 0; - padding: 0; - border-radius: var(--rp-radius-control, 0px); - border: 1px solid var(--line); - background: var(--panel); - color: var(--accent); - font-size: 12px; - font-weight: 700; - line-height: 1; - cursor: pointer; -} - -.docker-label-info:hover { - border-color: var(--accent); -} - #location-help-body .docker-label-table { width: 100%; table-layout: auto; @@ -2724,7 +2703,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px 14px; - align-items: end; } .cache-rule-field { @@ -3554,7 +3532,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, .docker-service-group-rows { display: grid; - gap: var(--ui-gap-sm, 8px); + gap: 8px; padding: 0 8px 8px; } @@ -3574,11 +3552,13 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, min-width: 0; } -.docker-security-grid .docker-wide-field { +.docker-security-grid .docker-wide-field, +.docker-diagnostics-grid .docker-wide-field { grid-column: 1 / -1; } -.docker-security-grid .docker-subheading { +.docker-security-grid .docker-subheading, +.docker-diagnostics-grid .docker-subheading { grid-column: 1 / -1; margin: 8px 0 0; padding-top: 8px; @@ -3590,7 +3570,8 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, text-transform: uppercase; } -.docker-security-grid .docker-subheading:first-child { +.docker-security-grid .docker-subheading:first-child, +.docker-diagnostics-grid .docker-subheading:first-child { margin-top: 0; padding-top: 0; border-top: 0; diff --git a/src/admin/web/css/55-policy.css b/src/admin/web/css/55-policy.css index ed57306..ec0c383 100644 --- a/src/admin/web/css/55-policy.css +++ b/src/admin/web/css/55-policy.css @@ -457,15 +457,14 @@ min-width: 520px; } -.docker-policy-editor { - margin: 12px 0; - border: 1px solid var(--line); - padding: 12px; +/* HTTP policies are nested in the Docker service "Headers" section and use the + same disclosure row as the other Docker service sections. */ +.docker-headers-editor .docker-policy-editor { + margin-top: 12px; } -.docker-policy-editor>summary { - cursor: pointer; - font-weight: 600; +.docker-policy-editor>.http-policy-editor { + margin-top: 10px; } @media (max-width: 760px) { diff --git a/src/admin/web/css/60-monitoring.css b/src/admin/web/css/60-monitoring.css index 067eccb..5cca71a 100644 --- a/src/admin/web/css/60-monitoring.css +++ b/src/admin/web/css/60-monitoring.css @@ -219,15 +219,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool min-width: 190px; } -.cache-reason { - display: inline-block; - border: 1px solid var(--line); - border-radius: var(--rp-radius-surface, 4px); - padding: 2px 5px; - margin: 1px 4px 2px 0; - font-size: 10px; -} - #panel-cache thead th { position: sticky; top: 0; @@ -237,8 +228,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool #panel-cache .cache-table .cache-reasons { white-space: normal; - min-width: 210px; - max-width: 300px; } #panel-cache .cache-copy-cell { @@ -429,7 +418,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool .transform-reason-list { display: flex; flex-wrap: wrap; - gap: 7px; } .cache-transform-badge { @@ -991,7 +979,6 @@ html[data-table-density=ultra] .file-log-inline-detail pre { .cache-varnish-info, .cache-maintenance-info { - position: static; flex-shrink: 0; } @@ -1232,12 +1219,6 @@ html[data-table-density=ultra] .file-log-inline-detail pre { background: var(--chart-accent); } -#cache-domain-scroll .cache-reason { - border-color: transparent; - background: var(--panel2); - color: var(--muted); -} - #panel-cache .cache-table .cache-reasons { min-width: 200px; max-width: 320px; @@ -1320,13 +1301,10 @@ html[data-table-density=ultra] .file-log-inline-detail pre { align-items: center; gap: 0; border: 1px solid var(--line); - border-radius: var(--rp-radius-control, 6px); - overflow: hidden; } .cache-pager button { border: 0; - border-radius: 0; min-width: 88px; margin: 0; } diff --git a/src/admin/web/css/70-responsive.css b/src/admin/web/css/70-responsive.css index b719498..32761d7 100644 --- a/src/admin/web/css/70-responsive.css +++ b/src/admin/web/css/70-responsive.css @@ -762,6 +762,21 @@ grid-template-columns: 1fr 1fr; } + .location-summary { + grid-template-columns: 22px 10px minmax(0, 1fr) auto; + } + + .location-summary>.loc-path, + .location-summary>.loc-action, + .location-summary>.loc-chips { + grid-column: 3 / -1; + } + + .location-cards, + .location-templates { + grid-template-columns: minmax(0, 1fr); + } + .location-actions, .location-toolbar { align-items: stretch; @@ -1804,6 +1819,7 @@ .docker-protocol-editor>summary, .docker-security-editor>summary, .docker-diagnostics-editor>summary, +.docker-policy-editor>summary, .docker-timeout-editor>summary, .docker-passive-health-editor>summary { list-style: none; @@ -1816,6 +1832,7 @@ .docker-protocol-editor>summary::-webkit-details-marker, .docker-security-editor>summary::-webkit-details-marker, .docker-diagnostics-editor>summary::-webkit-details-marker, +.docker-policy-editor>summary::-webkit-details-marker, .docker-timeout-editor>summary::-webkit-details-marker, .docker-passive-health-editor>summary::-webkit-details-marker { display: none; @@ -1828,6 +1845,7 @@ .docker-protocol-editor>summary::before, .docker-security-editor>summary::before, .docker-diagnostics-editor>summary::before, +.docker-policy-editor>summary::before, .docker-timeout-editor>summary::before, .docker-passive-health-editor>summary::before { content: "›"; @@ -1847,6 +1865,7 @@ .docker-protocol-editor[open]>summary::before, .docker-security-editor[open]>summary::before, .docker-diagnostics-editor[open]>summary::before, +.docker-policy-editor[open]>summary::before, .docker-timeout-editor[open]>summary::before, .docker-passive-health-editor[open]>summary::before { transform: rotate(90deg); @@ -1857,11 +1876,6 @@ flex: 0 0 auto; } -.docker-service-editor>summary .docker-config-hint { - flex: 1; - min-width: 0; -} - .docker-service-editor:not(.docker-service-metrics)>summary:hover>span { color: var(--green); } @@ -1889,6 +1903,7 @@ .docker-protocol-editor>summary:focus-visible, .docker-security-editor>summary:focus-visible, .docker-diagnostics-editor>summary:focus-visible, +.docker-policy-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); @@ -2055,6 +2070,7 @@ .docker-protocol-editor>summary, .docker-security-editor>summary, .docker-diagnostics-editor>summary, +.docker-policy-editor>summary, .docker-timeout-editor>summary, .docker-passive-health-editor>summary { justify-content: flex-start; @@ -2068,6 +2084,7 @@ .docker-protocol-editor>summary>span, .docker-security-editor>summary>span, .docker-diagnostics-editor>summary>span, +.docker-policy-editor>summary>span, .docker-timeout-editor>summary>span, .docker-passive-health-editor>summary>span { text-align: left; @@ -2080,6 +2097,7 @@ .docker-protocol-editor>summary>small, .docker-security-editor>summary>small, .docker-diagnostics-editor>summary>small, +.docker-policy-editor>summary>small, .docker-timeout-editor>summary>small, .docker-passive-health-editor>summary>small { flex: 1 1 auto; @@ -2096,6 +2114,7 @@ .docker-protocol-editor>summary>span, .docker-security-editor>summary>span, .docker-diagnostics-editor>summary>span, + .docker-policy-editor>summary>span, .docker-timeout-editor>summary>span, .docker-passive-health-editor>summary>span { flex: 0 0 190px; diff --git a/src/admin/web/docker.js b/src/admin/web/docker.js index 0939fa4..99ae1c8 100644 --- a/src/admin/web/docker.js +++ b/src/admin/web/docker.js @@ -485,7 +485,7 @@ provisionInput.addEventListener("keydown", event => { if (event.key === "Enter") { event.preventDefault(); void applyProvision(); } }); row.focusProvision = () => { provision.open = true; provisionInput.focus(); }; const labelPublish = input("", "checkbox", "docker-agent-label-publish switch"); labelPublish.checked = value.label_publish === true; - const labelField = checkboxField("dockerLabelPublish", labelPublish), labelHelp = el("small", undefined, "fine docker-label-help"), labelInfo = el("button", "?", "docker-label-info"); labelInfo.type = "button"; labelInfo.dataset.uiIconName = "none"; labelInfo.title = t("dockerLabelHelpTitle"); labelInfo.setAttribute("aria-label", t("dockerLabelHelpTitle")); labelInfo.addEventListener("click", openLabelHelp); + const labelField = checkboxField("dockerLabelPublish", labelPublish), labelHelp = el("small", undefined, "fine docker-label-help"), labelInfo = el("button", "?", "docker-label-info rp-info-icon"); labelInfo.type = "button"; labelInfo.setAttribute("aria-haspopup", "dialog"); labelInfo.dataset.uiIconName = "none"; labelInfo.title = t("dockerLabelHelpTitle"); labelInfo.setAttribute("aria-label", t("dockerLabelHelpTitle")); labelInfo.addEventListener("click", openLabelHelp); labelHelp.append(el("span", t("dockerLabelPublishHelp")), labelInfo); labelField.append(labelHelp); let closeBubble = null; const showBubble = (text, kind) => { @@ -875,17 +875,33 @@ basic_auth: collectBasicAuth(row), }; } - function diagnosticsEditor(assignment) { - const details = el("details", undefined, "docker-diagnostics-editor"), summary = el("summary"); summary.append(el("span", t("dockerDiagnostics")), el("small", t("dockerDiagnosticsHelp"), "fine")); details.append(summary); + // "Headers": diagnostic response headers and the vhost's HTTP policy rules. + // The policy editor stays collapsed inside this section until it is needed. + function headersEditor(assignment, row) { + const details = el("details", undefined, "docker-diagnostics-editor docker-headers-editor"), summary = el("summary"), state = el("small", "", "fine"); + summary.append(el("span", t("dockerHeaders")), state); details.append(summary); const grid = el("div", undefined, "field-grid docker-diagnostics-grid"); const box = (cls, value) => { const node = input("", "checkbox", `${cls} switch`); node.checked = value === true; return node; }; - grid.append(checkboxField("vhTimingHeaders", box("docker-timing-headers", assignment?.timing_headers)), checkboxField("vhBackendHeader", box("docker-backend-header", assignment?.backend_header)), checkboxField("vhBackendTimingHeader", box("docker-backend-timing-header", assignment?.backend_timing_header))); - details.append(grid); return details; - } - function policyEditor(assignment, row) { - const details = el("details", undefined, "docker-policy-editor"); details.append(el("summary", t("policyTitle"))); - const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => row.classList.add("is-dirty") }); - details.append(policy.node); row._readPolicy = () => policy.read(); return details; + const timing = box("docker-timing-headers", assignment?.timing_headers), backend = box("docker-backend-header", assignment?.backend_header), backendTiming = box("docker-backend-timing-header", assignment?.backend_timing_header); + grid.append(el("h4", t("dockerDiagnostics"), "docker-subheading docker-wide-field"), el("p", t("dockerDiagnosticsHelp"), "fine docker-wide-field"), + checkboxField("vhTimingHeaders", timing), checkboxField("vhBackendHeader", backend), checkboxField("vhBackendTimingHeader", backendTiming)); + const policyBox = el("details", undefined, "docker-policy-editor"), policySummary = el("summary"), policyState = el("small", "", "fine"); + policySummary.append(el("span", t("policyTitle")), policyState); policyBox.append(policySummary); + let sync = () => { }; + const policy = window.rustProxyPolicy.create({ value: assignment?.policy || {}, scope: "vhost", onChange: () => { row.classList.add("is-dirty"); sync(); } }); + policyBox.append(policy.node); row._readPolicy = () => policy.read(); + details.append(grid, policyBox); + let ruleCount = (assignment?.policy?.rules || []).length; + sync = () => { + const rules = policy.node.querySelector(".policy-visual:not([hidden]) .policy-rules"); + if (rules) ruleCount = rules.querySelectorAll(":scope > .policy-rule").length; + const rulesText = ruleCount ? t("dockerPolicyRuleCount").replace("{count}", ruleCount) : t("dockerPolicyNone"); + policyState.textContent = rulesText; + const enabled = [[timing, "Server-Timing"], [backend, "X-RustProxy-Backend"], [backendTiming, "X-RustProxy-Backend-Time"]].filter(([control]) => control.checked).map(([, label]) => label); + state.textContent = enabled.length || ruleCount ? [...enabled, ...(ruleCount ? [rulesText] : [])].join(" · ") : t("dockerHeadersHelp"); + }; + details.addEventListener("input", sync); details.addEventListener("change", sync); sync(); + return details; } function collectDiagnostics(row) { const on = cls => row.querySelector(cls)?.checked === true; @@ -1068,7 +1084,7 @@ protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled)); protocolBox.append(protocolSummary, protocolOptions); route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp(); - editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), diagnosticsEditor(assignment), policyEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment)); + editor.append(route, protocolBox, aclEditor(assignment, agent), securityEditor(assignment), cacheEditor(assignment, agent, key, cacheEnabled, () => expandedHost(host.value.trim() || technical, domainSelect.value)), headersEditor(assignment, row), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment)); const actions = el("div", undefined, "docker-service-actions"); apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions); function updateHint() { syncCertificateHint(); editorHint.textContent = hintFor({ hostname: host.value.trim(), domain: domainSelect.value, targetLabel: target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), scheme: scheme.value, h2: h2Enabled.checked, h3: h3Enabled.checked, aliasCount: aliases.count() }); } updateHint(); for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); } diff --git a/src/admin/web/settings.js b/src/admin/web/settings.js index 1857eec..45f1d73 100644 --- a/src/admin/web/settings.js +++ b/src/admin/web/settings.js @@ -348,7 +348,7 @@ const restart = t("restartFieldBadge"); panel.querySelectorAll("[data-restart]").forEach(node => { const span = node.querySelector(":scope > span"); if (span && span.dataset.restartBadge !== restart) span.dataset.restartBadge = restart; node.title = t("restartFieldHelp"); }); panel.querySelectorAll(".settings-page .fine:not([role=status]):not(.help-clamp)").forEach(node => { - if (node.id?.endsWith("-status") || node.closest(".certificate-api-credential-item, .acl-picker, .docker-container-state, dialog")) return; + if (node.id?.endsWith("-status") || node.closest(".certificate-api-credential-item, .acl-picker, .docker-container-state, .metric-info-popover, dialog")) return; if ((node.textContent || "").trim().length < HELP_CLAMP_LENGTH) return; node.classList.add("help-clamp"); node.tabIndex = 0; node.setAttribute("aria-expanded", "false"); const toggle = () => { const open = !node.classList.contains("is-open"); node.classList.toggle("is-open", open); node.setAttribute("aria-expanded", String(open)); }; diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index 14f152e..71a3923 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -426,12 +426,63 @@ function openLocationHelp(topic = "locations") { } dialog.showModal(); } +// Error fallback = target internal location + the upstream statuses it handles. +// The status chips write the legacy comma-separated "-statuses" field, +// so readers, JSON drawers and saved configuration keep their exact format. +const ERROR_FALLBACK_STATUSES = [403, 404, 500, 502, 503, 504]; +let errorFallbackListId = 0; +const internalLocationIds = () => [...form.querySelectorAll('.vh-location [name="location-internal"]')].filter(box => box.checked) + .map(box => read("location-id", box.closest(".vh-location"))?.value.trim()).filter(Boolean); +function errorFallbackFields(parent, prefix, value, keys) { + const target = field(parent, `${prefix}-target`, keys.target, value?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" }); + target.placeholder = t("errorFallbackTargetPlaceholder"); target.autocomplete = "off"; + const list = el("datalist"); list.id = `vh-error-fallback-targets-${++errorFallbackListId}`; target.setAttribute("list", list.id); target.closest("label").append(list); + const fillTargets = () => list.replaceChildren(...internalLocationIds().map(id => { const option = el("option"); option.value = id; return option; })); + target.addEventListener("focus", fillTargets); + const box = el("div", undefined, "vh-field vh-error-fallback-statuses"), caption = text("span", keys.statuses); + const hidden = document.createElement("input"); hidden.type = "hidden"; hidden.name = `${prefix}-statuses`; + const chips = el("div", undefined, "vh-status-chips"); chips.setAttribute("role", "group"); chips.setAttribute("aria-label", t(keys.statuses)); + const initial = [...new Set((value?.statuses?.length ? value.statuses : [404]).map(Number))]; + const choices = [...ERROR_FALLBACK_STATUSES, ...initial.filter(code => !ERROR_FALLBACK_STATUSES.includes(code))]; + const boxes = choices.map(code => { + const label = el("label", undefined, "vh-status-chip"), input = document.createElement("input"); + input.type = "checkbox"; input.value = String(code); input.checked = initial.includes(code); + label.append(input, el("span", String(code))); chips.append(label); return input; + }); + const write = () => { hidden.value = boxes.filter(input => input.checked).map(input => input.value).join(", "); }; + const sync = () => { const off = !target.value.trim(); box.classList.toggle("is-inactive", off); for (const input of boxes) input.disabled = off; }; + chips.addEventListener("change", event => { + // At least one status stays selected; an empty list would silently mean 404. + if (!boxes.some(input => input.checked)) event.target.checked = true; + write(); hidden.dispatchEvent(new Event("input", { bubbles: true })); + }); + target.addEventListener("input", sync); + box.append(caption, chips, hidden); parent.append(box); write(); sync(); + return { target, statuses: hidden }; +} const LOCATION_GROUP = "__group__"; function locationsEditor(parent, values, onChange = changed) { const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations"); - const addTop = button("locationAdd", () => { add(); sync(); }, "primary"); - const addHostRule = button("rtAddHostRule", () => { add({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }, true); sync(); }); - toolbar.append(addTop, addHostRule, button("documentation", () => openLocationHelp("locations"))); + // "Add location" opens starting points; each one only pre-fills ordinary fields. + const addMenu = el("div", undefined, "location-add-menu"), templates = el("div", undefined, "location-templates"); templates.hidden = true; + const showTemplates = open => { templates.hidden = !open; addTop.setAttribute("aria-expanded", String(open)); }; + const addTop = button("locationAdd", () => showTemplates(templates.hidden), "primary"); addTop.setAttribute("aria-haspopup", "true"); addTop.setAttribute("aria-expanded", "false"); + const template = (key, helpKey, make, openConditions = false) => { + const choice = el("button", undefined, "location-template"); choice.type = "button"; choice.append(text("b", key), text("span", helpKey, "fine")); + choice.addEventListener("click", () => { showTemplates(false); add(make(), openConditions); sync(); rows.lastElementChild?.scrollIntoView({ block: "nearest" }); rows.lastElementChild?.querySelector('[name="location-id"]')?.focus(); }); + templates.append(choice); + }; + template("locationTplProxy", "locationTplProxyHelp", () => ({ id: nextId("api"), path_prefix: "/api/", rewrite: { mode: "strip_prefix" } })); + template("locationTplWeb", "locationTplWebHelp", () => ({ id: nextId("files"), path_prefix: "/static/", source: { type: "web_server", web_service_id: "" } })); + template("locationTplRedirect", "locationTplRedirectHelp", () => ({ id: nextId("redirect"), path_prefix: "/old/", redirect: { status: 301, target: "", preserve_query: true } })); + template("locationTplReturn", "locationTplReturnHelp", () => ({ id: nextId("health"), match_type: "exact", path_prefix: "/healthz", response: { status: 200, content_type: "text/plain; charset=utf-8", body: "ok" } })); + template("locationTplInternal", "locationTplInternalHelp", () => ({ id: nextId("error"), internal: true })); + template("rtAddHostRule", "locationTplHostHelp", () => ({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }), true); + template("locationTplBlank", "locationTplBlankHelp", () => ({})); + addMenu.addEventListener("keydown", event => { if (event.key === "Escape" && !templates.hidden) { event.preventDefault(); event.stopPropagation(); showTemplates(false); addTop.focus(); } }); + addMenu.addEventListener("focusout", event => { if (!addMenu.contains(event.relatedTarget)) showTemplates(false); }); + addMenu.append(addTop, templates); + toolbar.append(addMenu, button("documentation", () => openLocationHelp("locations"))); parent.append(toolbar); note(parent, "locationHelp"); note(parent, "rtOrderHelp"); const tester = routingTester(parent, () => readRows()); parent.append(rows); let reloading = false; @@ -464,32 +515,64 @@ function locationsEditor(parent, values, onChange = changed) { }; }); } - function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); } + function renumber() { [...rows.children].forEach((row, index) => { if (row._order) row._order.textContent = String(index + 1); }); } + function sync() { renumber(); if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); } function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; const groupOption = text("option", "locationBackendGroup"); groupOption.value = LOCATION_GROUP; select.replaceChildren(base, groupOption, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; } - function add(value = {}, openConditions = false) { + function add(value = {}, openConditions = false, open = true) { if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; } - const row = el("details", undefined, "vh-location"); row.open = true; + const row = el("details", undefined, "vh-location"); row.open = open; const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body); + // Collapsed row = one line of the routing table; expanded = When / What / Options. + const sumOrder = el("span", String(rows.children.length + 1), "loc-order"), sumState = el("span", undefined, "loc-state"), sumId = el("span", "", "loc-id"); + const sumMatch = el("span", "", "loc-match"), sumPath = el("span", "", "loc-path"), sumAction = el("span", "", "loc-action"), sumChips = el("span", undefined, "loc-chips"); + sumState.setAttribute("role", "img"); summary.append(sumOrder, sumState, sumId, sumMatch, sumPath, sumAction, sumChips); row._order = sumOrder; + const headline = el("p", "", "vh-wide location-headline"); body.append(headline); + const card = (cls, number, key) => { + const box = el("section", undefined, `location-card ${cls}`), head = el("h4", undefined, "location-card-title"), grid = el("div", undefined, "vh-grid location-card-grid"); + head.append(el("span", number, "location-step"), text("span", key)); box.append(head, grid); return [box, grid]; + }; + const [whenCard, whenGrid] = card("location-when", "1", "locationStepWhen"), [whatCard, whatGrid] = card("location-what", "2", "locationStepWhat"); + const cards = el("div", undefined, "vh-wide location-cards"); cards.append(whenCard, whatCard); body.append(cards); + const options = el("section", undefined, "vh-wide location-options"), optionsHead = el("div", undefined, "location-options-head"), tabList = el("div", undefined, "location-tabs"), panels = el("div", undefined, "location-tab-panels"); + const optionsTitle = el("h4", undefined, "location-card-title"); optionsTitle.append(el("span", "3", "location-step"), text("span", "locationStepOptions")); + tabList.setAttribute("role", "tablist"); optionsHead.append(optionsTitle, tabList); options.append(optionsHead, panels); body.append(options); + const tabs = new Map(); let activeTab = "access"; + const optionTab = (name, key) => { + const tab = el("button", undefined, "location-tab"), state = el("small", "", "location-tab-state"), panel = el("div", undefined, "vh-grid location-tab-panel"); + tab.type = "button"; tab.setAttribute("role", "tab"); tab.append(text("span", key), state); panel.setAttribute("role", "tabpanel"); panel.hidden = true; + tab.addEventListener("click", () => selectTab(name)); tabList.append(tab); panels.append(panel); tabs.set(name, { tab, state, panel }); return panel; + }; + const selectTab = name => { + const available = item => !item.tab.hidden; + let target = tabs.get(name); if (!target || !available(target)) target = [...tabs.values()].find(available); + for (const [key, item] of tabs) { const on = item === target; if (on) activeTab = key; item.tab.setAttribute("aria-selected", String(on)); item.tab.classList.toggle("active", on); item.panel.hidden = !on; } + }; + const setTabAvailable = (name, available) => { const item = tabs.get(name); item.tab.hidden = !available; if (!available && activeTab === name) selectTab("access"); else if (activeTab === name) selectTab(name); }; + const accessPanel = optionTab("access", "locationTabAccess"), headersPanel = optionTab("headers", "locationTabHeaders"), cachePanel = optionTab("cache", "locationTabCache"); + const errorsPanel = optionTab("errors", "locationTabErrors"), backendPanel = optionTab("backend", "locationBalancing"), policyPanel = optionTab("policy", "policyTitle"); + row.addEventListener("invalid", event => { + const panel = event.target.closest?.(".location-tab-panel"), entry = panel && [...tabs].find(([, item]) => item.panel === panel); + if (entry) selectTab(entry[0]); row.open = true; + }, true); const used = new Set([...rows.children].map(r => str("location-id", r))); let suffix = 1; while (used.has(`location-${suffix}`)) suffix++; - field(body, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 }); - const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] }); - const path = field(body, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/"; - const internal = field(body, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true }); + field(whenGrid, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 }); + const match = field(whenGrid, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] }); + const path = field(whenGrid, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/"; + const internal = field(whenGrid, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true }); const initialAction = value.response ? "return" : value.redirect ? "redirect" : value.source?.type === "web_server" ? "web_server" : "proxy"; - const action = field(body, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] }); + const action = field(whatGrid, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] }); const initialTarget = value.backend_ids?.length ? LOCATION_GROUP : value.backend_id || ""; - const backend = field(body, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget); - const webService = field(body, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || ""); - field(body, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true }); - const cache = field(body, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] }); + const backend = field(whatGrid, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget); + const webService = field(whatGrid, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || ""); + field(whatGrid, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true }); + const cache = field(cachePanel, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] }); - const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); body.append(conditionBox); + const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); whenGrid.append(conditionBox); conditionBox.open = openConditions || Boolean(value.conditions?.length); note(conditionBody, "rtConditionsHelp"); const conditions = conditionsEditor(conditionBody, value.conditions || [], () => { syncUi(); sync(); }); row.readConditions = conditions.read; const conditionCacheNote = text("p", "rtNotCachedHelp", "fine vh-wide"); conditionBody.append(conditionCacheNote); - const balancing = el("details", undefined, "vh-wide location-section location-balancing"), balancingBody = el("div", undefined, "vh-grid"); balancing.append(text("summary", "locationBalancing"), balancingBody); body.append(balancing); - balancing.open = Boolean(value.backend_ids?.length || value.load_balancing); + const balancingBody = backendPanel; balancingBody.classList.add("location-balancing"); const groupBox = el("div", undefined, "vh-wide location-group"); groupBox.append(text("span", "locationGroupMembers", "location-group-title")); const groupList = el("div", undefined, "location-group-list"); groupBox.append(groupList, text("p", "locationGroupHelp", "fine")); balancingBody.append(groupBox); const groupSelected = new Set(value.backend_ids || []); @@ -503,7 +586,7 @@ function locationsEditor(parent, values, onChange = changed) { })); }; row.groupIds = () => { const ids = balancingMembers().map(m => m.id).filter(id => groupSelected.has(id)); if (!ids.length) throw new Error(t("locationGroupEmpty").replace("{location}", str("location-id", row))); return ids; }; - backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) balancing.open = true; }); + backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) selectTab("backend"); }); const ownBalancing = field(balancingBody, "location-lb-custom", "lbLocationOwn", Boolean(value.load_balancing), "checkbox", { switch: true }); const balancingSlot = el("div", undefined, "vh-wide vh-grid"); balancingBody.append(balancingSlot); const balancingControl = balancingEditor(balancingSlot, { @@ -515,10 +598,9 @@ function locationsEditor(parent, values, onChange = changed) { row.readBalancing = () => { if (!ownBalancing.checked) return null; balancingControl.validate(); const hash = balancingControl.hash(); return { algorithm: balancingControl.algorithm(), ...(hash ? { hash } : {}), sticky: balancingControl.sticky() }; }; row.refreshBalancing = () => { renderGroup(); balancingControl.refresh(); }; renderGroup(); - const handling = el("details", undefined, "vh-wide location-section"), handlingBody = el("div", undefined, "vh-grid"); handling.append(text("summary", "locationHandling"), handlingBody); body.append(handling); - field(handlingBody, "location-error-target", "locationErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" }); - field(handlingBody, "location-error-statuses", "locationErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 }); - note(handlingBody, "locationErrorFallbackHelp"); + const handlingBody = whatGrid; + errorFallbackFields(errorsPanel, "location-error", value.error_fallback, { target: "locationErrorFallbackTarget", statuses: "locationErrorFallbackStatuses" }); + note(errorsPanel, "locationErrorFallbackHelp"); const rewriteMode = field(handlingBody, "location-rewrite-mode", "locationRewriteMode", value.rewrite?.mode || "preserve", "select", { values: [["preserve", "locationRewritePreserve"], ["strip_prefix", "locationRewriteStrip"], ["replace_prefix", "locationRewriteReplace"], ["regex", "locationRewriteRegex"]] }); const rewriteValue = field(handlingBody, "location-rewrite-value", "locationRewriteValue", value.rewrite?.value || "", "text", { maxLength: 2048 }); const returnBox = el("div", undefined, "vh-wide vh-grid location-return-box"); handlingBody.append(returnBox); @@ -531,9 +613,9 @@ function locationsEditor(parent, values, onChange = changed) { field(redirectBox, "location-redirect-pattern", "locationRedirectPattern", value.redirect?.rewrite_pattern || "", "text", { maxLength: 1024 }); field(redirectBox, "location-redirect-query", "locationRedirectQuery", value.redirect?.preserve_query !== false, "checkbox", { switch: true }); note(redirectBox, "locationRedirectHelp"); - note(handlingBody, "locationRewriteHelp"); + const rewriteHelp = note(handlingBody, "locationRewriteHelp"); - const extra = el("details", undefined, "vh-wide location-section"), accessBody = el("div", undefined, "vh-grid"); extra.append(text("summary", "locationAccess"), accessBody); body.append(extra); + const accessBody = accessPanel; const locationProfiles = subsection(accessBody, "vhAclProfile"); const locationProfile = field(locationProfiles, "location-acl-profile", "locationAclProfile", value.acl_profile_id || "", "select"); const locationNoProfile = text("option", "vhAclProfileNone"); locationNoProfile.value = ""; @@ -549,15 +631,14 @@ function locationsEditor(parent, values, onChange = changed) { note(locationCountries, "locationCountryHelp"); const locationAcl = subsection(accessBody, "vhLocationIpAclSection"); const acl = aclEditor(locationAcl, value.acl, sync); row.readAcl = () => acl.read(); - const headerBox = el("details", undefined, "vh-wide location-section location-header-editor"), headerBody = el("div", undefined, "vh-grid"); headerBox.append(text("summary", "locationHeaders"), headerBody); body.append(headerBox); + const headerBody = headersPanel; headerBody.classList.add("location-header-editor"); const headerToolbar = el("div", undefined, "vh-wide location-header-toolbar"), visualPane = el("div", undefined, "vh-wide vh-grid"), jsonPane = el("div", undefined, "vh-wide vh-grid"); jsonPane.hidden = true; const visualButton = button("headersVisualBuilder", () => { visualPane.hidden = false; jsonPane.hidden = true; }), jsonButton = button("headersAdvancedJson", () => { visualPane.hidden = true; jsonPane.hidden = false; }), docsButton = button("documentation", () => openLocationHelp("headers")); headerToolbar.append(visualButton, jsonButton, docsButton); headerBody.append(headerToolbar, visualPane, jsonPane); const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 }); const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read(); - const policyBox = el("details", undefined, "vh-wide location-section"), policyBody = el("div", undefined, "policy-detail-body"); - policyBox.append(text("summary", "policyTitle"), policyBody); body.append(policyBox); + const policyBody = policyPanel; policyBody.classList.add("policy-detail-body"); const policyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "location", onChange: sync }); policyBody.append(policyEditor.node); row.readPolicy = () => policyEditor.read(); @@ -576,46 +657,54 @@ function locationsEditor(parent, values, onChange = changed) { const moveDown = button("rtMoveDown", () => { if (row.nextElementSibling) { rows.insertBefore(row.nextElementSibling, row); sync(); } }); actions.append(moveUp, moveDown, dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions); + let policyCount = (value.policy?.rules || []).length; const syncUi = () => { const isReturn = action.value === "return", isRedirect = action.value === "redirect", isWeb = action.value === "web_server", isProxy = action.value === "proxy", isRegex = match.value === "regex" || match.value === "regex_insensitive"; match.disabled = internal.checked; path.disabled = internal.checked || match.value === "any"; + match.closest("label").hidden = internal.checked; path.closest("label").hidden = internal.checked || match.value === "any"; const conditional = !internal.checked && conditions.count() > 0; conditionBox.hidden = internal.checked; conditionCacheNote.hidden = !conditional; if (conditional) cache.value = ""; backend.disabled = !isProxy; cache.disabled = !isProxy || conditional; dedicated.disabled = !isProxy; const isGroup = isProxy && backend.value === LOCATION_GROUP, pinned = isProxy && !["", LOCATION_GROUP].includes(backend.value); - balancing.hidden = !isProxy || pinned; groupBox.hidden = !isGroup; + const balancingAvailable = isProxy && !pinned; setTabAvailable("backend", balancingAvailable); groupBox.hidden = !isGroup; ownBalancing.disabled = !isProxy || pinned; balancingSlot.hidden = !ownBalancing.checked; inheritNote.hidden = ownBalancing.checked; webService.disabled = !isWeb; webService.required = isWeb; + backend.closest("label").hidden = !isProxy; webService.closest("label").hidden = !isWeb; + rewriteMode.closest("label").hidden = isReturn || isRedirect; rewriteValue.closest("label").hidden = isReturn || isRedirect; rewriteHelp.hidden = isReturn || isRedirect; returnBox.hidden = !isReturn; redirectBox.hidden = !isRedirect; rewriteMode.disabled = isReturn || isRedirect; rewriteValue.disabled = isReturn || isRedirect || rewriteMode.value === "preserve" || rewriteMode.value === "strip_prefix"; for (const option of rewriteMode.options) if (option.value === "regex") option.disabled = !isRegex; if (!isRegex && rewriteMode.value === "regex") rewriteMode.value = "preserve"; path.placeholder = isRegex ? "^/api/v[0-9]+/" : "/api/"; const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : match.value === "any" ? "*" : (str("location-path", row) || "/"); const conditionNote = conditional ? ` · ${t("rtConditionCount").replace("{count}", String(conditions.count()))}` : ""; - summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}${conditionNote}`; + const enabledNow = yes("location-enabled", row); let actionText; + row.classList.toggle("is-disabled", !enabledNow); sumState.title = t(enabledNow ? "enabled" : "notEnabled"); sumState.setAttribute("aria-label", sumState.title); + sumId.textContent = id; sumMatch.textContent = internal.checked ? t("locationInternalShort") : t(`locationMatch_${match.value}`); sumMatch.classList.toggle("is-internal", internal.checked); + sumPath.textContent = `${pattern}${conditionNote}`; previewStatus.hidden = yes("location-enabled", row); previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}${conditionNote}`; if (isReturn) { const status = str("location-response-status", row) || "200", type = str("location-response-type", row) || "text/plain"; - previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`; + previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationReturnAction")} ${status}`; previewValues.rewrite.textContent = "-"; previewValues.cache.textContent = t("notEnabled"); } else if (isRedirect) { const status = str("location-redirect-status", row) || "302", target = str("location-redirect-target", row) || "-", capture = str("location-redirect-pattern", row); - previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`; + previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationRedirectAction")} ${status} → ${target}`; previewValues.rewrite.textContent = capture || "-"; previewValues.cache.textContent = t("notEnabled"); } else { if (isWeb) { const selected = webService.selectedOptions?.[0]?.textContent || t("webServiceSelect"); - previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`; + previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`; actionText = `${t("locationWebServerShort")} → ${selected}`; previewValues.cache.textContent = t("notEnabled"); } else { const selected = backend.value === LOCATION_GROUP ? `${t("locationBackendGroup")} (${[...groupSelected].join(", ") || "-"})` : backend.selectedOptions?.[0]?.textContent || t("locationPool"); - const algorithmLabel = ownBalancing.checked && !balancing.hidden ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : ""; - previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`; + const shortTarget = backend.value === LOCATION_GROUP ? [...groupSelected].join(", ") || "-" : selected; + const algorithmLabel = ownBalancing.checked && balancingAvailable ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : ""; + previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`; actionText = `${t("locationProxyShort")} → ${shortTarget}`; previewValues.cache.textContent = t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit"); } const rewriteLabels = { preserve: "locationRewritePreserve", strip_prefix: "locationRewriteStrip", replace_prefix: "locationRewriteReplace", regex: "locationRewriteRegex" }; @@ -628,21 +717,40 @@ function locationsEditor(parent, values, onChange = changed) { const countryMode = str("location-country-mode", row); if (countryMode !== "off") accessParts.push(`${t("locationCountryMode")}: ${t(countryMode === "allow" ? "vhCountryAllow" : "vhCountryBlock")} ${lines(str("location-country-list", row)).join(", ")}`); if (yes("acl-use", row)) accessParts.push(t("locationPreviewCustomAcl")); previewValues.access.textContent = accessParts.length ? accessParts.join(" · ") : t("locationPreviewVhostAcl"); + let headerCount = 0; try { const headerValue = editor.read(), requestRules = headerValue.request?.length || 0, responseRules = headerValue.response?.length || 0; - previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`; + previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`; headerCount = requestRules + responseRules; } catch { previewValues.headers.textContent = t("headersInvalid"); } + // Row summary, headline and option tab states. + sumAction.textContent = actionText || ""; + const fallbackTarget = str("location-error-target", row), fallbackStatuses = str("location-error-statuses", row).replace(/\s+/g, ""); + const visualRules = policyBody.querySelector(".policy-visual:not([hidden]) .policy-rules"); if (visualRules) policyCount = visualRules.querySelectorAll(":scope > .policy-rule").length; + const cacheLabel = isProxy && !conditional ? t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit") : "-"; + const ownLb = isProxy && balancingAvailable && (ownBalancing.checked || isGroup); + const states = { access: accessParts.length ? String(accessParts.length) : "", headers: headerCount ? String(headerCount) : "", cache: isProxy && cache.value ? cacheLabel : "", errors: fallbackTarget ? `@${fallbackTarget}` : "", backend: isGroup ? t("locationChipGroup").replace("{count}", String(groupSelected.size)) : ownLb ? t("locationChipBalancing") : "", policy: policyCount ? String(policyCount) : "" }; + for (const [name, item] of tabs) { item.state.textContent = states[name] ? ` · ${states[name]}` : ""; item.tab.classList.toggle("is-set", Boolean(states[name])); } + const chips = []; + if (accessParts.length) chips.push(t("locationTabAccess")); + if (headerCount) chips.push(`${t("locationTabHeaders")} ${headerCount}`); + if (isProxy && !conditional && cache.value) chips.push(`Cache: ${cacheLabel}`); + if (states.backend) chips.push(states.backend); + if (policyCount) chips.push(`${t("policyTitle")} ${policyCount}`); + sumChips.replaceChildren(...chips.map(label => el("span", label, "loc-chip"))); + if (fallbackTarget) { const chip = el("span", `${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}`, "loc-chip is-fallback"); sumChips.append(chip); } + headline.textContent = `${internal.checked ? `@${id} (${t("locationInternalShort")})` : pattern}${conditionNote} → ${actionText || "-"}${fallbackTarget ? ` · ${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}` : ""}${enabledNow ? "" : ` · ${t("notEnabled")}`}`; }; row.addEventListener("input", () => { syncUi(); sync(); }); row.addEventListener("change", () => { syncUi(); sync(); }); + selectTab(value.backend_ids?.length || value.load_balancing ? "backend" : "access"); rows.append(row); syncUi(); } - for (const value of values) add(value); + for (const value of values) add(value, false, false); const bottom = el("div", undefined, "vh-wide location-toolbar location-toolbar-bottom"); bottom.append(button("locationAdd", () => { add(); sync(); }, "primary")); parent.append(bottom); const refreshMembers = () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); for (const row of rows.children) row.refreshBalancing?.(); }; form.querySelector(".vh-members").addEventListener("input", refreshMembers); form.querySelector(".vh-members").addEventListener("change", refreshMembers); readRows.set = data => { validateLocations(data); const previous = [...rows.childNodes]; reloading = true; - try { rows.replaceChildren(); for (const value of data) add(value); readRows(); tester?.run(); } + try { rows.replaceChildren(); for (const value of data) add(value, false, false); renumber(); readRows(); tester?.run(); } catch (error) { rows.replaceChildren(...previous); throw error; } finally { reloading = false; } }; diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js index 88de8c7..817f5c3 100644 --- a/src/admin/web/vhosts/editor.js +++ b/src/admin/web/vhosts/editor.js @@ -365,9 +365,9 @@ function load(value = defaults(), migrationIds = [], show = true) { field(uaBlockingFields, "ua-block-patterns", "vhUaBlockPatterns", (uaBlock.patterns || []).join("\n"), "textarea", { rows: 4, maxLength: 32768 }); note(uaBlockingFields, "vhUaBlockHelp"); g = group("vhLocations"); - field(g, "main-error-target", "vhErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" }); - field(g, "main-error-statuses", "vhErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 }); - note(g, "vhErrorFallbackHelp"); + const fallbackFields = subsection(g, "vhErrorFallbackSection"); + errorFallbackFields(fallbackFields, "main-error", value.error_fallback, { target: "vhErrorFallbackTarget", statuses: "vhErrorFallbackStatuses" }); + note(fallbackFields, "vhErrorFallbackHelp"); const pathsJson = jsonDrawer(g, { name: "paths", titleKey: "vhLocationsJson", helpKey: "vhLocationsJsonHelp", value: value.routes || [], maxLength: 131072, validate: validateLocations, apply: data => locationsReader.set(data) }); locationsReader = locationsEditor(g, value.routes || [], () => { changed(); pathsJson.refresh(); }); g.append(pathsJson.node); diff --git a/src/web_server/fastcgi/protocol.rs b/src/web_server/fastcgi/protocol.rs index 4c4ef5f..344661a 100644 --- a/src/web_server/fastcgi/protocol.rs +++ b/src/web_server/fastcgi/protocol.rs @@ -17,7 +17,7 @@ use http::{ use http_body_util::BodyExt; use std::{collections::BTreeMap, io, path::Path, str::FromStr}; use tokio::{ - io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter}, sync::{mpsc, OwnedSemaphorePermit}, time::Instant, }; @@ -31,6 +31,13 @@ pub(super) const FCGI_STDOUT: u8 = 6; const FCGI_STDERR: u8 = 7; const FCGI_RESPONDER: u16 = 1; const FCGI_REQUEST_ID: u16 = 1; +const FCGI_HEADER_LEN: usize = 8; +/// Request records (BEGIN, PARAMS, STDIN) are coalesced into a few socket writes. +const FASTCGI_WRITE_BUFFER_BYTES: usize = 16 * 1024; +/// Response records are read through one buffer instead of 2-3 reads per record. +const FASTCGI_READ_BUFFER_BYTES: usize = 32 * 1024; +/// Already-received STDOUT records are merged into one body chunk up to this size. +const FASTCGI_BODY_CHUNK_BYTES: usize = 64 * 1024; pub(super) trait FastCgiIo: AsyncRead + AsyncWrite + Unpin + Send {} impl FastCgiIo for T where T: AsyncRead + AsyncWrite + Unpin + Send {} @@ -40,11 +47,27 @@ async fn connect_fastcgi(endpoint: &FastCgiEndpoint) -> io::Result Ok(Box::new(tokio::net::UnixStream::connect(path).await?)), FastCgiEndpoint::Tcp(address) => { - Ok(Box::new(tokio::net::TcpStream::connect(address).await?)) + let stream = tokio::net::TcpStream::connect(address).await?; + // FastCGI is a request/response exchange of small records; Nagle's + // algorithm would only delay the final record of a request. + stream.set_nodelay(true)?; + Ok(Box::new(stream)) } } } +/// Type of the next FastCGI record when it is already complete in the read +/// buffer, so it can be consumed without waiting for the socket. +fn buffered_fcgi_record(io: &BufReader>) -> Option { + let buffer = io.buffer(); + if buffer.len() < FCGI_HEADER_LEN { + return None; + } + let length = u16::from_be_bytes([buffer[4], buffer[5]]) as usize; + let padding = buffer[6] as usize; + (buffer.len() >= FCGI_HEADER_LEN + length + padding).then_some(buffer[1]) +} + pub(super) async fn write_fcgi_record( io: &mut dyn FastCgiIo, record_type: u8, @@ -338,7 +361,7 @@ pub(super) fn parse_cgi_headers(value: &[u8]) -> Result<(StatusCode, HeaderMap)> } async fn drain_fastcgi_body( - mut io: Box, + mut io: BufReader>, deadline: Instant, tx: mpsc::Sender>, initial: Vec, @@ -347,18 +370,29 @@ async fn drain_fastcgi_body( metrics: std::sync::Arc, _permit: OwnedSemaphorePermit, ) { - if send_body && !initial.is_empty() && tx.send(Ok(Bytes::from(initial))).await.is_err() { - return; - } + // Body bytes waiting to be sent. Records that have already arrived are + // merged into one chunk; nothing is held back while waiting for the socket, + // so flush() from the application still reaches the client immediately. + let mut pending = if send_body { initial } else { Vec::new() }; let mut stderr = Vec::new(); loop { - match read_fcgi_record(io.as_mut(), deadline).await { + if !pending.is_empty() + && (pending.len() >= FASTCGI_BODY_CHUNK_BYTES || buffered_fcgi_record(&io).is_none()) + && tx + .send(Ok(Bytes::from(std::mem::take(&mut pending)))) + .await + .is_err() + { + return; + } + match read_fcgi_record(&mut io, deadline).await { Ok((FCGI_STDOUT, content)) => { - if send_body - && !content.is_empty() - && tx.send(Ok(Bytes::from(content))).await.is_err() - { - return; + if send_body && !content.is_empty() { + if pending.is_empty() { + pending = content; + } else { + pending.extend_from_slice(&content); + } } } Ok((FCGI_STDERR, content)) => { @@ -370,12 +404,18 @@ async fn drain_fastcgi_body( Err(error) => { metrics.failure(8); if send_body { + if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() { + return; + } let _ = tx.send(Err(error)).await; } return; } } } + if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() { + return; + } if !stderr.is_empty() { tracing::warn!( stderr = %String::from_utf8_lossy(&stderr), diff --git a/src/web_server/fastcgi/response.rs b/src/web_server/fastcgi/response.rs index f0f3bbc..94d8515 100644 --- a/src/web_server/fastcgi/response.rs +++ b/src/web_server/fastcgi/response.rs @@ -68,7 +68,7 @@ async fn php_response_inner( return response; } }; - let mut io = + let io = match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await { Ok(Ok(io)) => io, Ok(Err(error)) => { @@ -100,16 +100,22 @@ async fn php_response_inner( } }; let deadline = Instant::now() + php.request_timeout; + let mut writer = BufWriter::with_capacity(FASTCGI_WRITE_BUFFER_BYTES, io); let exchange = async { let mut begin = [0u8; 8]; begin[..2].copy_from_slice(&FCGI_RESPONDER.to_be_bytes()); - write_fcgi_record(io.as_mut(), FCGI_BEGIN_REQUEST, &begin).await?; + write_fcgi_record(&mut writer, FCGI_BEGIN_REQUEST, &begin).await?; for chunk in params.chunks(u16::MAX as usize) { - write_fcgi_record(io.as_mut(), FCGI_PARAMS, chunk).await?; + write_fcgi_record(&mut writer, FCGI_PARAMS, chunk).await?; } - write_fcgi_record(io.as_mut(), FCGI_PARAMS, &[]).await?; + write_fcgi_record(&mut writer, FCGI_PARAMS, &[]).await?; let mut body = body; + // Requests without a body go out in one write. With a body, deliver the + // parameters first so the responder can start while the client uploads. + if !http_body::Body::is_end_stream(&body) { + writer.flush().await?; + } let mut body_bytes = 0u64; while let Some(frame) = body.frame().await { let frame = frame.map_err(|error| { @@ -121,12 +127,12 @@ async fn php_response_inner( return Err(FastCgiRequestWriteError::BodyTooLarge); } for chunk in data.chunks(u16::MAX as usize) { - write_fcgi_record(io.as_mut(), FCGI_STDIN, chunk).await?; + write_fcgi_record(&mut writer, FCGI_STDIN, chunk).await?; } } } - write_fcgi_record(io.as_mut(), FCGI_STDIN, &[]).await?; - io.flush().await?; + write_fcgi_record(&mut writer, FCGI_STDIN, &[]).await?; + writer.flush().await?; Ok::<(), FastCgiRequestWriteError>(()) }; match tokio::time::timeout_at(deadline, exchange).await { @@ -145,10 +151,12 @@ async fn php_response_inner( } } + // The request is fully flushed; from here on the connection is only read. + let mut io = BufReader::with_capacity(FASTCGI_READ_BUFFER_BYTES, writer.into_inner()); let mut stdout = Vec::new(); let mut stderr = Vec::new(); let (status, response_headers, initial_body) = loop { - let record = read_fcgi_record(io.as_mut(), deadline).await; + let record = read_fcgi_record(&mut io, deadline).await; let (record_type, content) = match record { Ok(value) => value, Err(error) if error.kind() == io::ErrorKind::TimedOut => { diff --git a/src/web_server/tests.rs b/src/web_server/tests.rs index e144ebf..27c8283 100644 --- a/src/web_server/tests.rs +++ b/src/web_server/tests.rs @@ -3250,3 +3250,188 @@ async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query() assert_eq!(params["QUERY_STRING"], "404"); assert_eq!(params["REQUEST_URI"], "/error.php?404"); } + +/// One encoded FastCGI record (request id 1), as a responder writes it. +fn fcgi_record_bytes(kind: u8, content: &[u8]) -> Vec { + let padding = (8 - content.len() % 8) % 8; + let mut record = vec![1, kind, 0, 1]; + record.extend_from_slice(&(content.len() as u16).to_be_bytes()); + record.extend_from_slice(&[padding as u8, 0]); + record.extend_from_slice(content); + record.resize(record.len() + padding, 0); + record +} + +fn php_fixture_service(root: &Path, address: std::net::SocketAddr) -> CompiledService { + std::fs::write(root.join("index.php"), b" (Vec, Vec) { + let deadline = Instant::now() + Duration::from_secs(5); + let (mut params, mut stdin) = (Vec::new(), Vec::new()); + loop { + let (kind, content) = read_fcgi_record(stream, deadline).await.unwrap(); + match kind { + FCGI_PARAMS => params.extend_from_slice(&content), + FCGI_STDIN if content.is_empty() => return (params, stdin), + FCGI_STDIN => stdin.extend_from_slice(&content), + _ => {} + } + } +} + +#[tokio::test] +async fn fastcgi_buffered_exchange_keeps_many_records_stderr_and_body_intact() { + const FCGI_STDERR: u8 = 7; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let upload: Vec = (0..200_000u32).map(|value| (value % 251) as u8).collect(); + let expected_upload = upload.clone(); + let (seen_tx, seen_rx) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let (params, stdin) = read_fastcgi_request(&mut stream).await; + let _ = seen_tx.send((decode_fastcgi_params(¶ms), stdin)); + // Headers split across records, interleaved STDERR, then many small + // body records written in one burst (as PHP output buffers do). + let mut burst = Vec::new(); + for record in [ + &b"Status: 200 OK\r\nContent-"[..], + &b"Type: text/plain\r\n\r\nA"[..], + ] { + burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, record)); + } + burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDERR, b"notice")); + for index in 0..3000u32 { + burst.extend_from_slice(&fcgi_record_bytes( + FCGI_STDOUT, + format!("{index:05}|").as_bytes(), + )); + } + burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, &[])); + burst.extend_from_slice(&fcgi_record_bytes(FCGI_END_REQUEST, &[0u8; 8])); + stream.write_all(&burst).await.unwrap(); + stream.flush().await.unwrap(); + }); + let tmp = TempDir::new().unwrap(); + let service = php_fixture_service(tmp.path(), address); + let mut post = request(Method::POST, "/index.php?x=1"); + post.headers_mut() + .insert(CONTENT_LENGTH, upload.len().to_string().parse().unwrap()); + let response = serve_body_request(&service, &post, "/index.php", Body::from(upload)).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[CONTENT_TYPE], "text/plain"); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let mut expected = b"A".to_vec(); + for index in 0..3000u32 { + expected.extend_from_slice(format!("{index:05}|").as_bytes()); + } + assert_eq!(body.as_ref(), expected.as_slice()); + let (params, stdin) = seen_rx.await.unwrap(); + assert_eq!(params["REQUEST_METHOD"], "POST"); + assert_eq!(params["QUERY_STRING"], "x=1"); + assert_eq!(stdin, expected_upload); +} + +#[tokio::test] +async fn fastcgi_streamed_output_is_not_held_back_for_coalescing() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + read_fastcgi_request(&mut stream).await; + write_fcgi_record( + &mut stream, + FCGI_STDOUT, + b"Content-Type: text/plain\r\n\r\nfirst", + ) + .await + .unwrap(); + stream.flush().await.unwrap(); + // The rest is produced only after the client has seen the first chunk, + // like an application calling flush() between slow steps. + release_rx.await.unwrap(); + write_fcgi_record(&mut stream, FCGI_STDOUT, b"-second") + .await + .unwrap(); + write_fcgi_record(&mut stream, FCGI_STDOUT, &[]) + .await + .unwrap(); + write_fcgi_record(&mut stream, FCGI_END_REQUEST, &[0u8; 8]) + .await + .unwrap(); + stream.flush().await.unwrap(); + }); + let tmp = TempDir::new().unwrap(); + let service = php_fixture_service(tmp.path(), address); + let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await; + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let first = tokio::time::timeout(Duration::from_secs(2), body.frame()) + .await + .expect("first chunk must be delivered before more output exists") + .unwrap() + .unwrap() + .into_data() + .unwrap(); + assert_eq!(first.as_ref(), b"first"); + release_tx.send(()).unwrap(); + let rest = body.collect().await.unwrap().to_bytes(); + assert_eq!(rest.as_ref(), b"-second"); +} + +#[tokio::test] +async fn fastcgi_truncated_stream_delivers_received_bytes_then_errors() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + read_fastcgi_request(&mut stream).await; + let mut burst = fcgi_record_bytes(FCGI_STDOUT, b"Content-Type: text/plain\r\n\r\nkept"); + burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, b"-also")); + stream.write_all(&burst).await.unwrap(); + // Half a record header, then the responder disappears. + stream.write_all(&[1, FCGI_STDOUT, 0]).await.unwrap(); + stream.flush().await.unwrap(); + }); + let tmp = TempDir::new().unwrap(); + let service = php_fixture_service(tmp.path(), address); + let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await; + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let mut received = Vec::new(); + let mut failed = false; + while let Some(frame) = body.frame().await { + match frame { + Ok(frame) => received.extend_from_slice(&frame.into_data().unwrap()), + Err(_) => { + failed = true; + break; + } + } + } + assert_eq!(received, b"kept-also"); + assert!( + failed, + "a truncated FastCGI stream must not look like a complete body" + ); +}