diff --git a/AGENTS.md b/AGENTS.md
index c399e93..02c70f2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# RustProxy source and documentation maintenance
-Current source version: **0.37.0**. The Cargo package and binary are named `rust-proxy`.
+Current source version: **0.37.1**. 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 db13322..6ecd659 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,28 @@
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.
-## Unreleased
+## 0.37.1 — Precise SNI certificate selection, OPNsense deploy script, Docker panel polish
+
+- **Cache rules (VCL-style):** new **Settings → Cache → Rules** tab and **Cache rules for this vhost** in the vhost editor. Rules are built graphically (*If … Then …*) for three stages: request (bypass, remove cookies, remove query parameters such as `utm_*`, add a header or cookie to the cache key), backend response (TTL, grace, do not store, ignore backend Cache-Control, remove Set-Cookie) and deliver (set or remove response headers), with conditions on host, URL, path, extension, method, query parameter, header, cookie, client IP, status, Content-Type and response header. Vhost rules run before global rules; the editors show when a vhost rule overrides a global one, and a vhost can ignore global rules. Includes templates (WordPress, static files, tracking parameters, API, language variants, 404, X-Powered-By), drag-and-drop ordering, a request tester (`POST /api/cache/rules/test`, also for unsaved edits), VCL import of a common subset with warnings for the rest (`POST /api/cache/rules/import-vcl`), a read-only VCL preview, in-memory match counters (`GET /api/cache/rules/stats`) and Prometheus `rust_proxy_cache_rule_matches_total`. Configuration: `cache.rules`, vhost `cache.rules` and `cache.ignore_global_rules`. Existing safeguards (Authorization, Basic Auth, login providers, sticky sessions, Set-Cookie) stay in force. See [docs](docs/CACHE.md#cache-rules-vcl-style).
+- **TLS certificate selection (fix):** a name such as `app.apps.example.com` no longer gets a `*.example.com` certificate. Wildcards now match exactly one label, and when no SNI name of a stored certificate matches, RustProxy checks the DNS SAN names each certificate really covers (the certificate with the fewest names wins) before falling back to the default certificate. This affects vhosts and Docker vhosts in *Automatic* / *Global SNI* certificate mode. See [docs](docs/CERTIFICATES.md#one-vhost-several-certificates-sni-selection).
+- **Docker certificate hint:** in *Automatic* mode the service editor shows which stored certificate SNI will pick, or warns which names no stored certificate covers. See [docs](docs/DOCKER_DISCOVERY.md#certificates).
+- **OPNsense ACME deploy script:** `integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh` rewritten for the current certificate API and the os-acme-client automation (*System or Plugin Command* → **Deploy certificates to RustProxy**, runs after every issue/renewal). Certificates are found by name (`--list` shows them; os-acme-client stores them under an internal id the GUI does not show) and mapped to RustProxy ids with `RUSTPROXY_CERTIFICATES='*.apps.example.com=apps-wildcard …'`; explicit `CERT_FILE`/`KEY_FILE` still work. Supports `https://` and loopback `http://` panels, `RUSTPROXY_TLS_VERIFY=no` for a self-signed or not yet valid panel certificate, `RUSTPROXY_PINNED_PUBKEY`, `RUSTPROXY_CACERT`, `RUSTPROXY_RESOLVE`, `--check` and `--config`. On failure it logs the RustProxy error code with a hint (for example `certificate_api.deploy_forbidden`: the key is reload-only, enable *Also allow deploy*). See [docs](integrations/opnsense-acme/README.md).
+- **Docker agent addresses:** agent 0.37.1 also reports container bridge addresses (`docker0`, `br-*`, `podman*`, `cni-*`, `virbr*`, source `bridge`). **Default backend IP** groups the detected addresses into *Recommended*, *Other host interfaces* and *Container bridges* and marks the primary address with ★. See [docs](docs/DOCKER_DISCOVERY.md#default-backend-ip).
+- **Docker Overview cards:** the layout editors and the dashboard settings list show each Docker card type once instead of four times; the agent is chosen in the list when adding the card, and further copies of the same type can be added until four are visible. Visible copies show the selected agent name instead of *#2–#4*. See [docs](docs/DOCKER_DISCOVERY.md#overview-cards).
+- **Docker vhosts:** container state, health, uptime, CPU, RAM (with a fill bar against the memory limit) and restarts are shown as separate coloured chips; the page description under the title was removed; the alias domain list no longer repeats the master domain. See [docs](docs/DOCKER_DISCOVERY.md#container-state-and-history).
+- **Settings → Docker agents:** *Test connection* sits next to *Remove* and shows its result in a bubble; *Publish from container labels* has a **?** button with the label reference and a `docker compose` example. See [docs](docs/DOCKER_DISCOVERY.md#test-connection-and-one-time-codes).
+- **Settings → Certificate API redesigned:** keys are listed first (permission badge, certificate chips, created / last used) with *Edit*, *Regenerate token* and *Revoke token*; **New key** and *Edit* open an editor (inline under the edited key) with *Reload only* / *Deploy and reload* as two clear choices and the certificates chosen in the same searchable picker as elsewhere in the panel, showing each certificate's host names; a new ID can be typed for a certificate that the first deploy will create, and RustProxy ACME certificates are marked reload-only. The custom token is an optional advanced field, the one-time token appears in a highlighted box with a copy button, and the curl example is collapsible. Keys migrated from older versions with access to all certificates (`*`) are marked and the editor explains that certificates must now be chosen; previously saving such a key failed with *Certificate API tokens require 1-32 valid certificate IDs*. See [docs](docs/CERTIFICATES.md#restricted-certificate-api).
+- **Settings, clearer layout:** See [docs](docs/CONFIGURATION.md#settings-pages).
+ - **API tokens (Security)** now work like Certificate API keys: list first (RO/RW badge, address chips, created / last used), **New token** opens an editor with *Read only* / *Read and write* as two choices and source addresses as chips (a single IP becomes /32 or /128, invalid entries are rejected before saving); the one-time token appears in a highlighted box with a copy button. The leftover "API tokens moved to Security" card in *Administration* was removed. See [docs](docs/API.md#api-tokens-in-the-panel).
+ - **Restart markers per field:** *Administration* and *Prometheus* mark exactly the fields that need a restart with a RESTART badge (the card shows LIVE + RESTART); everything else applies immediately.
+ - **Prometheus** is split into *Endpoint*, *Bearer token* (status badge, copy button) and *Metric groups*; allowed scraper addresses are chips and the scrape config is collapsible. See [docs](docs/MONITORING.md#prometheus-exporter).
+ - **Global block / allow:** a status bar at the top shows every rule (country, User-Agent, IP/CIDR, methods, Content-Type, rate limit) with its state and jumps to it; each section shows an on/off badge and hides its fields while off. Countries are chosen from a searchable list (ISO code and name) instead of typing codes. See [docs](docs/ACCESS.md#global-block--allow-policy).
+ - **Listeners** are compact cards (name, ID, addresses, Internal/Public, TLS, H1/H2/H3, disabled) that expand for editing; *Currently active* is shown at the top. A listener with an invalid field opens automatically when saving. See [docs](docs/TRANSPORT.md#frontend-listeners).
+ - **Long help texts** in Settings are shortened to two lines and expand on click; the save button of each settings form stays visible at the bottom of the screen and shows *Unsaved changes* when the form was edited.
+ - **System information** is rebuilt from the same blocks as Overview: a host card (OS, environment, kernel, CPUs, RAM, swap, host and RustProxy uptime, LIVE/MANUAL, *Copy diagnostics* for bug reports), tiles for system and RustProxy CPU with short history lines, load average, RAM and file descriptors, a *RustProxy process* card (RSS split into HOT/transient cache, anonymous and file-backed memory, cache/transform budgets, start time, swap, disk I/O, cgroup limit), a *Network* card (active interfaces, idle ones folded, RX/TX history), the certificate toolchain (Python → pip → Certbot) and data paths with *Copy*. The history lines live only in the browser tab. See [docs](docs/MONITORING.md#system-information).
+- **Interface scale (fix):** at a smaller interface scale (Settings → Appearance) dialogs such as logs, configuration history, vhost editors and About shrank together with their content and left the rest of the screen empty. Dialogs now keep their on-screen size at every scale (the content inside gets smaller, so more of it fits), and layout sizes based on the window width/height are corrected for the scale as well. See [docs](docs/DASHBOARD.md#interface-scale-and-dialogs).
+- **Corner style:** new and updated controls (keys, tokens, chips, status badges, container meters, listener cards, rule status bar) follow the *Corner style* appearance setting instead of fixed rounding. See [docs](docs/DASHBOARD.md#corner-style).
+- **Panel icons:** the ★ *make master domain* button in domain pickers is no longer replaced by a shield icon.
## 0.37.0 — Docker domains, certificate lists, agent provisioning and host diagnostics
@@ -238,7 +259,6 @@ Release history focused on **features, settings, default behavior, compatibility
- **Tinyauth compatibility patch:** the Nginx verifier now receives one consistent auth-request header set. RustProxy removes ForwardAuth module markers (`X-Forwarded-Host`, `X-Forwarded-URI`) while preserving the verified client IP and original request URL. This resolves the `conflicting auth module headers` rejection introduced in Tinyauth 5.2.0 without disabling anti-spoofing checks. Added regression tests for conflicting module headers and forged client identity. Use the internal `/api/auth/nginx` endpoint.
- **Tinyauth timeout:** a verifier request that exceeds the configured deadline returns a distinct **504 Tinyauth timeout** page. Invalid verifier responses, unexpected HTTP statuses and oversized identity/response data return **502 Tinyauth verification error**. All retain no-store and the authenticated-request isolation marker, so Vhost/global error-page overrides do not mask Tinyauth's diagnostic category.
-
## 0.34.13 — Global security, section-based configuration API and panel UX
- **GeoIP:** on-demand data refresh moved from the isolated `POST /api/geoip/update` to `POST /api/config/geoip/update`, colocated with the revisioned GeoIP settings. This action does not change the config revision; the UI and RO/RW token allowlist use the new URL. Section paths now consistently use kebab-case, including `not-found-hosts` (the JSON property remains `not_found_hosts`). Old action/section paths are removed.
@@ -355,7 +375,6 @@ Release history focused on **features, settings, default behavior, compatibility
- Web Server-generated errors now reuse the bundled application-style HTML pages (400/403/404/500 and other available templates), with the same styled fallback for statuses such as 405. Proxy-generated non-template errors continue to use ordinary HTTP status text; no implementation diagnostics are exposed publicly. Preserved HTTP statuses, `HEAD` behavior, `Allow`/`Retry-After`, existing custom pages, backend-origin responses and authentication behavior.
- Removed an unused forwarding accessor (`peer_header`) to avoid a Rust `dead_code` warning without changing forwarded header behavior.
-
## 0.34.1 — explicit configuration, hot reload and API tokens
- `--config /absolute/file.json` / `RUST_PROXY_CONFIG`: an existing JSON file becomes the authoritative configuration source. Panel edits and restored revisions are written atomically to that file, with revision history in SQLite. Manual edits are imported by an explicit reload. Fingerprints reject unexpected external changes.
@@ -365,10 +384,10 @@ Release history focused on **features, settings, default behavior, compatibility
- Settings supports generate/rotate/revoke for a standalone Prometheus scrape Bearer token. Only its hash is stored. An explicit revocation record overrides legacy environment credentials.
- Moved RO/RW API token management from **Settings → Administration** to **Settings → Security**; Administration now links directly to the token card.
-
## 0.34.0 — cache consistency, static delivery and proxy optimization
### Cache
+
- Improved HOT/COLD cache retention when saving operational Vhost settings such as backend keepalive, connection recycling and load-balancer diagnostics. Unrelated changes should no longer unnecessarily clear compatible cached content.
- Changes affecting served content invalidate the relevant Vhost cache scope and pending fills. Global changes to response representation may still invalidate content more broadly.
- Added protection against restoring obsolete persistent COLD responses after an interrupted scoped purge or restart. Previously stored objects may need to be populated again during compatibility checks.
@@ -376,12 +395,14 @@ Release history focused on **features, settings, default behavior, compatibility
- Improved cache HIT/LRU accounting, `Vary` handling and response-header isolation. Existing `private`/`no-store` rules, conditional requests, PURGE/BAN controls and authenticated-request protections remain in effect.
### Static content and backend traffic
+
- Added **`sendfile: off | auto`** in **Web Server → Delivery**, disabled by default. `auto` supports eligible full static GET responses of **64 KiB or more** on Linux over unencrypted HTTP/1.1; TLS, HTTP/2, HTTP/3, ranges, compression, transformations and other excluded requests use standard delivery.
- Increased the default HTTP/1.1 idle backend connection pool size for **new** Vhost/origin configurations from **4 to 64**. Existing explicitly saved values remain unchanged; a larger pool can use more file descriptors and connections.
- Reduced overhead in common reverse-proxy routing, upstream connection reuse, backend selection, request forwarding and streamed responses. Existing ACLs, trusted-proxy checks, request limits, load-balancer choices and retry rules are preserved.
- Optimized request forwarding for common HTTP/1.1 paths and forwarding headers without changing public path validation, IPv6 handling or the HTTP/2 and HTTP/3 security model.
### Metrics, logging and compatibility
+
- Improved traffic analytics, per-Vhost cache statistics, latency reporting and log handling under load. Analytics collection remains bounded and non-blocking; dropped samples are still counted when limits are reached.
- Reduced monitoring overhead without removing existing Prometheus, dashboard, cache or protocol metrics. Dashboard labels and reported cumulative latency values remain compatible.
- Preserved protected `X-Request-ID` formatting as **64 lowercase hexadecimal characters**; request IDs now use cryptographically secure 256-bit randomness combined with the process sequence.
@@ -645,7 +666,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.28.x — external certificates and GeoIP
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.28.2** | Safer external PEM/key access, including POSIX ACLs and Certbot symlinks; certificate API keys now default to limited reload-only permissions and explicit certificate grants. |
| **0.28.1** | Support externally managed absolute certificate/key paths and hot reload after Certbot renewal; keep external key files outside RustProxy backups. |
| **0.28.0** | Add manual GeoIP downloads, flexible CSV/MMDB source URLs and checksum validation; improve active listener/protocol display and cache Via controls. |
@@ -653,7 +674,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.27.x — compression and managed deployment
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.27.3** | Protect ownership during backup restore; enable scheduled GeoIP updates; fix listener overrides and valid WebSocket upgrade framing. |
| **0.27.2** | Fix managed Certbot issue/renew invocation without requiring operators to delete existing private Python environments. |
| **0.27.1** | Add application-managed Python/Certbot installation with system fallback and clearer runtime errors; extend sortable host lists and first-admin help. |
@@ -662,7 +683,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.26.x — cache, logs and interface operations
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.26.7** | Show HOT/COLD cache capacity and progress; improve HTTP `Age` diagnostics and safe compression behavior for eligible cached/static responses. |
| **0.26.6** | Store backend table preferences per administrator; correct combined IP/country ACL logic and clarify the ACL editor's allow/deny modes. |
| **0.26.5** | Align compact filters and streamline navigation from Streams into listener configuration; no configuration migration. |
@@ -675,7 +696,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.25.x — Web Server and recovery
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.25.7** | Add quick Vhost enable/disable and clearer active-state controls. |
| **0.25.6** | Show upstream connection age, reuse and recycle diagnostics in the backend panel. |
| **0.25.5** | Add configurable HTTP/1.1 upstream connection recycling by age/request count and expand connection telemetry. |
@@ -688,7 +709,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.24.x — monitoring, security and transport
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.24.10** | Persist separate error-file logging settings and keep compatibility with existing logs. |
| **0.24.9** | Introduce encrypted Secret Store for managed credentials, including migration of ACME DNS secrets. |
| **0.24.8** | Expand Cache diagnostics with memory breakdowns and HOT/COLD occupancy. |
@@ -704,7 +725,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.23.x — certificates and dashboard diagnostics
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.23.3** | Make external certificate deploy idempotent and self-reconciling; add opt-in legacy WebSocket compatibility. |
| **0.23.2** | Add configurable Cache/Transform chart history windows and fix live-log CLI connections to HTTPS administration. |
| **0.23.1** | Add live Cache and Transform activity charts with per-scope request and outcome rates. |
@@ -713,7 +734,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.22.x — cache controls and protocol handling
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.22.3** | Support guarded cleartext H2 upgrade; add hot reload and external deploy for manual certificate IDs from CLI/API. |
| **0.22.2** | Add bounded safe-method failover retry, per-backend concurrency/capacity limits and detailed upstream failure diagnostics. |
| **0.22.1** | Simplify WebSocket transport selection and add focused active-tunnel, protocol and selective cache-invalidation controls. |
@@ -722,7 +743,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.21.x–0.19.x — transformations and certificate workflows
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.21.0** | Add a dedicated Transform workspace, savings/error counters and cache diagnostics for transformed representations. |
| **0.20.0** | Reorganize Certificates into Installed, Renewal and Generate; expose managed ACME job and Certbot diagnostics. |
| **0.19.4** | Improve presentation of idle and very small backend traffic rates. |
@@ -734,7 +755,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.18.x — Docker discovery and UI
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.18.8** | Correct the explicitly disabled backend TLS verification path while retaining separate destination protection. |
| **0.18.7** | Make Response Time History collapsible by default. |
| **0.18.6** | Add live network-interface throughput and process diagnostics. |
@@ -748,7 +769,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.17.x–0.13.x — platform and routing improvements
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.17.0** | Add Debian package/service assets, a Grafana dashboard, broader Prometheus metrics and local-response/404 hostname support. |
| **0.16.1** | Hide internal configuration revision numbers from normal save feedback while retaining conflict protection. |
| **0.16.0** | Keep unmatched paths on the main backend when custom locations exist; improve guarded self-admin routing, WebSocket/H3 and resource diagnostics. |
@@ -762,7 +783,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.12.x–0.10.x — API, Streams and disk cache
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.12.1** | Add revisioned per-section configuration API, cache retention across unrelated settings saves and configurable COLD demotion behavior. |
| **0.12.0** | Move TCP/UDP Streams into a dedicated editor with session, traffic and active/pending listener views. |
| **0.11.5** | Add guarded TCP/UDP forwarding, Debian 13 source bootstrap and stricter-but-compatible URL path handling. |
@@ -776,7 +797,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.9.x–0.7.x — administration and access
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.9.0** | Add structured JSONL/Logstash/Loki access-log sinks, expanded Vhost cards, cache inspection and administration HTTPS. |
| **0.8.1** | Enable the shared RAM cache by default and improve conditional/cached static behavior; Vhost and privacy rules still apply. |
| **0.8.0** | Add static-cache extension defaults, per-Vhost rate limits and GeoIP country policies. |
@@ -788,7 +809,7 @@ Release history focused on **features, settings, default behavior, compatibility
## 0.6.x–0.0.x — initial proxy platform
| Version | Technical changes |
-|---|---|
+| --- | --- |
| **0.6.0** | Unify Vhost configuration, add HTTP-01 and Cloudflare/OVH DNS-01 ACME, and introduce protected Prometheus export. |
| **0.5.0** | Add cache inspection/purge dashboard and first HTTP/3/frontend controls. |
| **0.4.0** | Add validated forwarding identity, Tinyauth protection, named multi-address listeners and HTTP/3 (QUIC). |
diff --git a/Cargo.lock b/Cargo.lock
index e9cb84f..592e369 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1943,7 +1943,7 @@ dependencies = [
[[package]]
name = "rust-proxy"
-version = "0.37.0"
+version = "0.37.1"
dependencies = [
"anyhow",
"arc-swap",
diff --git a/Cargo.toml b/Cargo.toml
index adb7a79..5ecc934 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "rust-proxy"
-version = "0.37.0"
+version = "0.37.1"
edition = "2021"
rust-version = "1.99.1"
description = "RustProxy - independent reverse proxy with local administration"
diff --git a/SHA256SUMS b/SHA256SUMS
index 0881bfe..071234b 100644
--- a/SHA256SUMS
+++ b/SHA256SUMS
@@ -1,10 +1,10 @@
61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore
4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example
e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore
-c7a44d067d8190054e40f1aa78f6c3f532faec4b103295c1acab89b006fa26ea AGENTS.md
-f182587954f106aae81f05de0f4f2ae180420da37340853087cd55ab703fbba3 CHANGELOG.md
-3ff0c3825b95bbdfcaca324b1611132ff2fade7bcbfd20a490e8595cd9732094 Cargo.lock
-4b91597db4f479b381b50eb39ac58ae3e72e2cc563f7eb994a765b3ac8550977 Cargo.toml
+0399823bbfd64c0aeb1f95e918dccc0ec5b5b7c7e31bd6335cddefc8931f71f1 AGENTS.md
+25dfd1751635f1d0fc3842485a093a8d91355c60f15a3173ec2cc4a3483bac2d CHANGELOG.md
+8c288a1b0bac53654e017f39fc05e044d536eab53be9d3aadfc1929d56f6021d Cargo.lock
+59a8a0ce15f7f93d5933c2cfb6d7d7d2591a857705cec4da807b2e111f03b0ec Cargo.toml
788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile
0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE
82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md
@@ -13,7 +13,7 @@ c0df6b46bf795d49d00fcd9e2a9247aed0d3a99b6cae1dc5ab6614e8b3d30009 build.rs
95ececaba550a4bcfd6754073877ba0633373b1e1451521b9ac905a51e8ca6eb deploy/README.md
13d514de5042a230cacf8c10abe1ef183c94ac799a89b8e2c111152ac7c69b48 deploy/rustproxy.service
c111f5b20484707b80efb7dd9176acbaa27b63ac78db497261ac234821e1fade dev.sh
-e48ca1c5ec19b2a74d1bcccd98e803c220f839c553a03c7bd72fc1e6e30b95ae docker-agent/README.md
+7c4b7a8c87babefa1ba6c6065f922fbf7bdc5821d3628753fdcc8d394aedf7b1 docker-agent/README.md
e9f18b358a740f1fe16e369ed16ee37581b8ce4c94ddeb34a1a37b89a49b5a06 docker-agent/certificate.go
600d5aebc8557d6987158969d494bade1ba46ccf9d1cd573d357d0106db26b2b docker-agent/cli_test.go
7a8ca48aca82178a301b41dfb4f1997b27f09352394d844bb2b627fa1c8aab0f docker-agent/containers.go
@@ -28,28 +28,28 @@ e9f18b358a740f1fe16e369ed16ee37581b8ce4c94ddeb34a1a37b89a49b5a06 docker-agent/c
b849d39e94878c5a754c3d109d8e4b5e37609cfd2a0e05601a35271f4d95271e docker-agent/install.sh
56d6acd675c44c3a39538b321d2057cf251a6a27b0ad634d827eb7d6a20de8c0 docker-agent/main.go
d660f46f7ef8c539dd3f5486a31d5a1254b9737be8a278c7f9352c254558f8ac docker-agent/main_test.go
-ca7b438fe3ff486e633fa3b14642801a01b04fec33fc7ba6948ce980fb249638 docker-agent/model.go
-e52b31d0abf65ae3034f6cb367cca113633014ce8d1d799ad4dd5624d2c7b8bb docker-agent/network.go
+8712ed6963ab640c855a24b5d93913b7bdf38738dffc5cbf28e2d6a325ec58c3 docker-agent/model.go
+2161db6057d982057cb9417a3791a98598f36e337a8ca6083672816bc95a6b83 docker-agent/network.go
021e0799a95a7c76bc245ff464d94b4495ce0d22555ca202579bd5f45e4be794 docker-agent/provision.go
4a737e5922c2255492c85d5afc053cd15d9e5b83cada648369cfdeeecdbfaa92 docker-agent/runtime.go
24494010bb215c5ff7eda0a571272309eebb5c35fa4ed24430da87790e89e941 docker-agent/rustproxy-docker-agent.service
b0b19b5fa15fe589f10305a19b75894f5d5cee816348e831702c4e06186e73b0 docker-agent/server.go
afd5b425936acc4972e9054b31daffead5f39ea706b0c3e5ead54270e3d43979 docker-agent/system.go
-18e275e5fbe2d45cd4da0778bffdcec18eda475bb27e225a4b09bff9fc8a0a20 docker-agent/system_test.go
-60d108fd168064e4d6980ed7499f3219017f9878c743697e77f2efc592e4d629 docs/ACCESS.md
-e708fc937dba80ac311fb19e785deae4eed586923180bc2a6b1c1a21922b5c2f docs/API.md
+188b74ec4f58da1b46d86925a67b6a590c92fb4fd7516e8d03d43871bc3b4542 docker-agent/system_test.go
+a3bd06c6ae52c5f4669d4fa5b5db8b76048ee3a496b4fb2fb05c501619b0fead docs/ACCESS.md
+b7a6c5e643e5afb46b4c0d8bbf75fea3aeb0350a164680900f42265b55740f2f docs/API.md
728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md
-4fb55a549535f37467f14536cbf0db7be027ca8a019c2919a384af4f23655300 docs/CACHE.md
-5e7b6668be6bfec77755ae45b9d369aa14135fce7632de392c6b29a7b584245a docs/CERTIFICATES.md
-bfd185b3b16f8b9a95351c4be570c6491dd941f39799344110eea40d2ee1d185 docs/CONFIGURATION.md
+d710bad171d62349cee3512d0bb775c0b7f725e9046c9bc1e326ff42e82f4f92 docs/CACHE.md
+375241ef87cff34c0bda5b771ee474a402f24ae8fb00e97f601b1a5060690508 docs/CERTIFICATES.md
+9c9e6c56ae9d714a5a99bffd39cb2d506991af5e67f034d41fe45210c95ac5ca docs/CONFIGURATION.md
fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md
-ce6eca6389efb4d9343d6b219f071316b683bb1316fa9b41846a2d394d902fa2 docs/DASHBOARD.md
-a9b2f6f8cbfac567258989506ca3b03427a9722f13b0d56f82b1aa6d918136f0 docs/DOCKER_DISCOVERY.md
-763ad7bdabc61f027f08fc9dcab30d1930ae09862688e1be28a9310bd56d5ebf docs/FEATURES.md
+2f1a01120d10ce5cdc9ad81d4e65c545965a7006031093edba1919dea90b0a39 docs/DASHBOARD.md
+bc0d22786e420f2486eee855430bd29ebb7a6879552077859c7722f0d0904c26 docs/DOCKER_DISCOVERY.md
+bd0bb5583bf171dc2cf73b56492184f6d7a69bf33db5f25c5396ed6c3300b400 docs/FEATURES.md
2c5f97b12be53db32c7e2888d23c0ef1d82d1742df44f7e60ea818dc801a719a docs/INSTALL.md
6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md
0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md
-0972248b7062b37e61edcc34dab5fe73ee9bb50195a0aa475c72efa0dd311aa9 docs/MONITORING.md
+fcf6cfe8daee898e6f6ce8588e8d3e769169da11f599531e44d997f7730526df docs/MONITORING.md
364c1faf9e21849de0f7c4ae8c1e55c1fa4d3ae3a7167a33cb58651174b4bfda docs/PERFORMANCE.md
d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.md
954b1602c865e157c867f1c81dca615f2beaa33c34de0b0fa8a6069db2aae7d0 docs/README.md
@@ -57,7 +57,7 @@ d5894c07c68ec4230987767198434abee13b0e525842fea21bcbe752fa82742b docs/PHP_FPM.m
95ab4786792d5920a2e109b7d196838057f24b512a69d713fb5884dc75c84339 docs/SCREENSHOTS.md
3a48184b36d225757fc5e2d22c629f89bfe5d4007ff087f0be0ce02a5fb04c28 docs/SECURITY.md
bbef60ff1771da9f48af812987766e1e479408873ae2f079b13f1d5c62ecc6ff docs/STREAMS.md
-8cfcda59060106151f13e93ca25c1280b4390433b3fbe2921a6eb3c13bf9766d docs/TRANSPORT.md
+415f6c7da2e06017ede2161a26558eaefef42d6b05e350827d6b532457c486e9 docs/TRANSPORT.md
be6e8af62a7bf958b94ec15e9e3263263e511d1d33abae4e45d114833fa52b07 docs/TROUBLESHOOTING.md
b4abb86942f665230904fad570c1487bc173aa84633801e2999f2bfa197de4a7 docs/VHOSTS.md
e67928a9d044e71b681c3e52f9dd8b151d6b72f965d16d5da8b0eadde98b70e9 docs/WEB_SERVER.md
@@ -91,20 +91,20 @@ c720a4426d7b4dc52048077157dd05aefa427ae78ca811afc3b7b9cbbe875cae grafana/rustpr
1a041c505669625a7f0f8011484cf5b6d2ec69a7de859801312e4fcf4c8d3555 install-debian13.sh
909e9ab94617ace74a425f15084bf85f3086cc52ba5b28f2b441ff800abc6ef9 install.sh
42f9f1d18c021fc7734b5bd020844bf678725a0e539e2fcbe05ec676f6239eae integrations/README.md
-ba753f69557bd9fa990e56beabebccf39f93b5f6fb7e66a2e241c8c461dfd763 integrations/opnsense-acme/README.md
-3a1f8c326618a4613bb35f9e83428f6d1cf668b9e37b4731e5d38c3081fc94d8 integrations/opnsense-acme/actions_rustproxy_cert.conf
-de6550ab8f48d556d752c252212c38ba65491fd224f972c10fbe552f91ed7520 integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh
-73784ac652708b04ca6c91aeed4524f51f50d63715bbeefe7f5590b353e78943 integrations/opnsense-acme/rustproxy-acme.conf.example
+13482032666464b2583016144ddc98b036281b2253c8fd8bcbad28cb0ed53876 integrations/opnsense-acme/README.md
+7c4063388d1fc3849a2432131e098aac4f2a2008031781d624d5bd4162eb5220 integrations/opnsense-acme/actions_rustproxy_cert.conf
+3428dd574e00ab7c90afdfcaf61b9cecb291484b5974947bd336520116acfe9e integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh
+992e45bf5ba46320118c524d9aaf908e45fd6a19246a05aec57b5860d23c8e7b integrations/opnsense-acme/rustproxy-acme.conf.example
0a86cb2a4ed689a5fa70534cac3402ca8bd3bb87c37e8ce2f3774bc2f48ab6c4 integrations/routeros-oci-build/.env.routeros.example
e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/routeros-oci-build/.gitignore
14025f0cad10e1b89f366977123e4cebb68ae59df892d4eed29b6171e63ae908 integrations/routeros-oci-build/Dockerfile.routeros
7c7a3e51f43b43e1c962a4b0bb591f99c1f06977bf77f23719f7f867dfe7eb8e integrations/routeros-oci-build/Dockerfile.routeros.dockerignore
-040f975d3f415fa3c0d88a9a3482f7ee5c928a340a370450eb73f309283a5dd9 integrations/routeros-oci-build/README.md
+1c71a990ce725becc909092f36e3a266a46fae27c95f2c09b71da6dde5eec086 integrations/routeros-oci-build/README.md
3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh
3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh
13189fa546c3488dddd8efc80c47f6da5241e5fc28b79cbfe795414ea05c7a4f langs/README.md
-85bc9068e6ec2dbca2c668f8fb598fe963a57598157ae0e9dd3b0ceb084376fd langs/en_US.json
-c8a659de54951aa627997f47b2275f5ddae4726504694c9413ac3ad3b7b35ad8 langs/pl_pl.json
+2db8755e026681806b3ce45f9428db11967d001155f820aaf8b3fc026d62eb32 langs/en_US.json
+84eaa5d7d8b51f7368c2dc74158bfb8f54907f2ee3c4acf9595a5c981ab7a785 langs/pl_pl.json
8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py
e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql
20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql
@@ -161,6 +161,7 @@ cfc13a293c126bb511745859669719a14c72dd7ff6be197bc9e0d0e560deebbd src/acme/tests
b28a08ea996befe10949676f40fab5f1036a274c7d0ab1175cf5c43c59849dc3 src/admin/access.rs
3afefdc6640d35bd55f20981e842647573f1ba80248680f99ba79eec9a7c4ce5 src/admin/api_token_access.rs
5f5b150bb8f51f57462e519650093354ae7b40fcb80c4380fd3391a33f4b30f2 src/admin/api_tokens.rs
+e127a784ada334f2ac46fdc4d8081188d75bbf6113dc75cb62ddfcf5dabf6273 src/admin/cache_rules.rs
34e851f725e8605e3c5d9946e56ac035996f3bd9d608169cba3408060d229c9b src/admin/certificate_api.rs
4a8b6406a44508b8ba102fef0d8309e871dbe0cbdbee1e6c8721baaca0c1aee1 src/admin/certificate_inspection_tests.rs
aefbef9839f9914ba05ea62bceff1463da3042b52ee851181ee39d4fbf7b91c3 src/admin/certificates.rs
@@ -168,15 +169,15 @@ aefbef9839f9914ba05ea62bceff1463da3042b52ee851181ee39d4fbf7b91c3 src/admin/cert
b7b0d3f0df7683b031136c05b314e206f7864e70514fe25165e41fd7a9382854 src/admin/config_sections.rs
c51f725075b5c4fc3fb7fb8b8b5f73987bff698a400e8950e968068b97a77631 src/admin/dashboard_presets.rs
aae1ca0e70d987830bd63948d431f54302083148177c1b551565be12df7fe771 src/admin/documentation.rs
-928ba7aa54ea742877cf267ee7ede798f95fb75839f21492063ba53e5e989882 src/admin/documentation/documents.rs
+6f58f821ea9a1686fc5130336ac82f06d5914b3642088641b5d036df6304c671 src/admin/documentation/documents.rs
b9c2952e3fcfca540d0ad64f2d3acc5c1f5240e707f4f23ef4d452f46fcb520f src/admin/documentation/tests.rs
1ce779b84aa8f47bdb3c34f83593c1f2f06d2235f0319847096cfcd035434168 src/admin/file_log_search.rs
059218501907355b22bc84e7e0c41ec72565af283f5e97170ce7707ea5874009 src/admin/file_logs.rs
d58a2ed83319176de4e66790ed292447c9497ae031464ec55cfe27174acb639a src/admin/file_logs_io.rs
77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs
743bb7436f77e04015328a0e7e7d425e43ef8aa8d61467bde157e462c1dcdc2e src/admin/logging_api.rs
-243f4a9c3fa99781e19c3952354d2632c0ce65e1dafac729567cbe3c177f94cb src/admin/mod.rs
-a5c8202e419989ed443fdd7dce5567657aa645fee30109b05c165628cdd60aab src/admin/openapi.json
+e0bd3c83170006a23ea3e1b2148f588767466cba48309af429a6f76089ea181a src/admin/mod.rs
+45d473eece8b8399b1c03505b17287fb127dacc0f9b6db34d5c8a0e39e577ec1 src/admin/openapi.json
f7a356109786635dd58cba590c71c796dbf36b47f25845190c75ee5c6a9fcb86 src/admin/operations.rs
257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs
f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs
@@ -186,27 +187,27 @@ f3635b624cf48598d68274a470d84d15ef9f6070d56e437a0031afa724471d5e src/admin/pref
62ecbae5dee00aeeca3eb806e2605372471dfab971cde8f66f11e711df8fcea1 src/admin/public/mod.rs
7a00e4ab943f74d2b1bdcbfab7f9cd3f584e9f59536b4aca6c4c31f5f5508d12 src/admin/public/tests.rs
6930b4f4b45257772b321b20a9becdf9bc4610274852948ba38c2d0cdf02dfaf src/admin/refresh_preferences.rs
-f7cba11895741fcd54a85d483595fcd4487fa4d5ca9c6b9cc8a81f61af8c381a src/admin/router.rs
+71f329e9323fa04590cef9cbde6fbd3a9797cc21b87201660cebe9beba786eb6 src/admin/router.rs
fba52102e77ca8871a42f97c91be8f10a9aa4f997868652d550fff3fbd41b66e src/admin/session.rs
a3f834afb6fac6719fabb702eb574dc2634a3de0c2e54cb56e98fe5b87a91855 src/admin/status.rs
abb5cd89aac02745666b67da07de718ff70612aac370fbd49ca4d3340acad991 src/admin/status_live.rs
8315c856cd50f1072593ecb30c274d42d82f078b5fb93e7c68a8857cd81b0841 src/admin/status_system.rs
cadd7dca29b9aad8c77c7bc23dd249ea37a15adfa4d636a8ef00273a91ce35dc src/admin/tail.rs
176173da61950866c61ab46b272a1ad95de3407dc6ef68a41c23a033b7d82b04 src/admin/tests.rs
-cbe43a37d9239a6724d2d2a03daec1cf023e9e82c8a594043568eefc7a81deda src/admin/web/acl-picker.js
+8c4492b89980a57b63dd50eb88b56cf89160ebf14280c702465764c8433d771a src/admin/web/acl-picker.js
48fcd818c522fe80f2c7b2e218f87de6a7772ffd0a24e93502780b03ec78e335 src/admin/web/acme.js
30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html
-86abf50f39862d821cd2e43ca425671aa85289272915132c5a9a5dd1fc4182e2 src/admin/web/api-tokens.js
+aa33315bf8e11d281778cdf258444ad8f02c22ac4fb8fba02fd4ee8677595d1f src/admin/web/api-tokens.js
faa9735c2a02746b2954bc4955eb609f94afebb685cd5521d2629640cea2777a src/admin/web/app/backend-dashboard.js
aed3aea4eef0011c6b51d39736782e7d1ec52662e422f40e0c7b9ddfc19d0378 src/admin/web/app/certificate-inspection.js
f6b0533ffd6d0e6471519120c440619a7fb4b255854ba3dd23d81cb35cd21afb src/admin/web/app/chart-scales.js
dedda129e173a347ebca9445c8a313849d1d678c256deabeb18f9977559e021a src/admin/web/app/config-history.js
-bf295721a38761f88363eda856064f854e408cb9d7888a2e0d0f2eaf3d72d7ed src/admin/web/app/core.js
-c782cdf0e6a23a1fc4bb5804e2d63e17bdc1faf75dda9d5ccc09b7752b6a245f src/admin/web/app/dashboard-inline-layout.js
-92bd0567a2631b2b9441901dbaabf7a02ff71de1ddfee02930f6fe97128ec7c1 src/admin/web/app/dashboard-layout-editor.js
+616664802eb185b07ab7edbb41a3acbed15735c220444aef801f0370428da4b0 src/admin/web/app/core.js
+a2b9ac1e7873aa52167fbe6a30e36b51b87791928049b660eaa3f9a7804dc57a src/admin/web/app/dashboard-inline-layout.js
+ce6518e953908b302c034346ec13ddaec308950ca2af1d54d063a87ff03efab3 src/admin/web/app/dashboard-layout-editor.js
716d33249a52548f10153d8e2f5bea962a5f0427525272ddd3a1db636647672c src/admin/web/app/dashboard-presets.js
-12880f470ddc8cae97ac79e8da68bcfe8aa15cd5c9d701044f88a670250a2eee src/admin/web/app/docker-dashboard.js
-99c3e775b3a57d9a783ca9350f48132eecbb0471f10daa6961cb2bcc9de630db src/admin/web/app/icons.js
+fce1fe268749b28ab68ac41519ced05252c1193f11bc9a3851de45dae4c419ad src/admin/web/app/docker-dashboard.js
+57dff3445ed156cc62b16c24fdf3f08932f79fa4ff5412afd2c0abc909a60349 src/admin/web/app/icons.js
9fc3165febd83a6661b2827aacd612fbc0f834e99ef1585ec54e03e97fe54a72 src/admin/web/app/logo-animation.js
92ed982c3ac4bc4218a24a200d2a33f30fc6705b77b260db2be31b0ce91a7df9 src/admin/web/app/memory-breakdown.js
32aa11f041eafdf16e66adef6f5847a67413785224da2c19ecbf825996622aff src/admin/web/app/overview-extra-metrics.js
@@ -215,34 +216,35 @@ bbbbe153ff37aa4cac0a83319e5b56a6442cabd1ef819380ae76e95bf79c7628 src/admin/web/
6f10f3239aea505aa01796620981eed873930c129ed5a2fd7eb439e0e0d24558 src/admin/web/app/overview-samples.js
db9012546cae8c58fc2bcbee71c9a95956a13a6db9e6d126c6a3770d45a4e4d2 src/admin/web/app/overview-wide-metrics.js
e799e0406c7ff54cbf71faf704a20265bdf5180a8ed2f26388d0775231365410 src/admin/web/app/path-permissions.js
-eb2295ffa197c5700cf6913979443a4588f220bcc184013b243f534099bb2163 src/admin/web/app/preferences.js
+cadc85eef6bc5226c99d1273d92aefe2ff5448143ce0722eab83ba90f978610d src/admin/web/app/preferences.js
30ec0a7027215eae63946689af2c042de0cf468a6b1054535694da4dd4214cdb src/admin/web/app/rate-sampling.js
3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js
-399a52a076872fa031113d475794e029cb7eb3813a3471eb54cbbac5e765ce03 src/admin/web/app/runtime.js
+62571928e3c2dfb5348c2526c491ffdbd0f7be5c4a807e1e9cae1e913cd33490 src/admin/web/app/runtime.js
31201586925e6f4792071d7d03fb05dcc4a69a03c02a4e85eb0746f45af68074 src/admin/web/app/session-resume.js
-c7a18238ac426de4d1cf84a395ee4dc66410d60a57a3822695dc10adc668d956 src/admin/web/app/settings.js
+dcc51a9bebc5c23c21fca134b6ece663ff2b7be8d7a3124ff27a1ec75750e737 src/admin/web/app/settings.js
2281f06990f86acd3ff12fa368e1b73e4c83601e20245f24abbce389dfccb77f src/admin/web/app/sidebar.js
b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/app/stream-dashboard.js
7de070cc8cdde45d7e0932259299e341e25b32c9ffbd87e4fcce934d0f090de4 src/admin/web/app/web-overview.js
3563508f45f740f0cc0e84c72eb79045c0cb54d6fa06a50326a3a219221e0010 src/admin/web/cache-panel.js
-99ed8c37e4fee646b9b26c96edbba4d823175dc3354c17c6574a7fc9a3dcbb0e src/admin/web/certificate-api.js
-43d702b676cd4f9dbe42e2ca65d938afe19086e67ab6e24af0b81d6947bee215 src/admin/web/css/00-tokens.css
-fcaed873e1ab68b73b75e18edfb9b8efceaec7f336c1910599065dbb08930f10 src/admin/web/css/10-base.css
-e711163fb144e38c3c961c20c38be55ebbb2e75898ab0ac1e58762e9ab8ff005 src/admin/web/css/20-shell.css
-078473429e253e63b83778cc223daeb7f84445a98763621733413a306778cbf8 src/admin/web/css/30-overview.css
-1d61f2eb90e39c79c7055845df4a9497bc89c35fa67aafaf10e4bc245f0f69c7 src/admin/web/css/40-editors.css
-1b52de62fc2fd08f4c86acd3b9e16354370d27a7f4e5c72e50854e466fdc0cbb src/admin/web/css/50-settings.css
-31c927777bb844c40305b96b6771b4f3956590fc8346a6b9f08724bad676bce2 src/admin/web/css/60-monitoring.css
-e4f276e7ab5ada8342b0c34a95a0e55f3cd5e446c4620ad1a8e1f07e287793a2 src/admin/web/css/70-responsive.css
+60f512d7748ccf98cca7c0a04789d8a5da6415e5575a715380791cb13ea7c516 src/admin/web/cache-rules.js
+03dd9e45d3f7a69ec8f37a5d5a16f3d24d2feecfde1704be79ff5d81aa5f7ae1 src/admin/web/certificate-api.js
+f554ca7179fe4d97ae24aa004d4bc9ada5f84fc78257891933a7fed728006ef8 src/admin/web/css/00-tokens.css
+741a0cc0c122215d738b7cb62a032e6f1892486e3193083e1cc7a8d4cc90a540 src/admin/web/css/10-base.css
+e360478a3dc3a3b316cc94712480f8c5cb1f8e78e5240613deda240ac4c16abe src/admin/web/css/20-shell.css
+7c29e87273b3c639602753cd61ee3b9e86a75c693b4b474eab21948d491174e7 src/admin/web/css/30-overview.css
+0add07b86b25e0675ae0869561723663312067e10083fb6eb1609006429741d9 src/admin/web/css/40-editors.css
+5d304c39628f653a677fa390746f6747478338a11ebe448f3b55551fe18e2bb3 src/admin/web/css/50-settings.css
+a2941410b885ac4487c2dc9003fb1d1073c163d707b5d085a15d9e8a8a628e03 src/admin/web/css/60-monitoring.css
+cc9b22431e5e141930eccf7cf8afa1ee8b7fb0ce8fd59410d2c1b000636084a2 src/admin/web/css/70-responsive.css
8009afdb04d5170687816730cc930a22fead1fe0248835ca7e8de81d6907395d src/admin/web/css/README.md
8241bd9489dfed082863948829a44a49bf0a8e9cd63c55809655109e393e0918 src/admin/web/css/manifest.json
78bf6179f769b68d518028464697e50dea5d75e33ecb1b89d88e2c2b01e86bf2 src/admin/web/dashboard-defaults.json
355046ecb80ce6adb73ceabd29825b0cf79ca364771070cedd5eb44760fae890 src/admin/web/dashboard-widgets.json
50d1ebcbaf4d0b2968da23bb943fc3f67131c5d32df3f61d23ff37aad9da5b81 src/admin/web/demo.html
-a32ee25ac7b117cd29d3ee51441eaf09edfd410ae99077065150cf4a1ce592d4 src/admin/web/docker.js
-0ed78a8731beca8d5e67163b26804cdcc925b0ecfbbc4bf946f8ec68daa62357 src/admin/web/docs.css
+f85d7c46a9dcd8138feef8ec6fca7778cf3f06b02b9b91fbc17f7e1b14f0c593 src/admin/web/docker.js
+8bf5d1f4f06d6e87536d808a680bf3d3a0c90c1637df0e58da667fd22ad4782d src/admin/web/docs.css
aeffd403fa1823df7d9fa4c48280b4033b2d15e4cb9f66608caff89290de0a52 src/admin/web/docs.html
-fd8506a91f769b57b62d9d8e389fb67764599354bf702958a913be79f779707b src/admin/web/docs.js
+306db8db9e4d651a85e09dbc15464e7f920d7fe5bd9ec9d1d8068321eb0106ab src/admin/web/docs.js
8fbc2a837d6f20a7f96c856a91fcba967b40a33494fe27ec876ee1b3b685178f src/admin/web/drafts.js
007c24189ad7b497d4da024fc52e6c51393f91ee135f525a356e1f14882b7632 src/admin/web/error_400.html
232b766f278ae4424705af351910677fcd7ac9a20bb8320d9a12b763c91219a2 src/admin/web/error_401.html
@@ -260,23 +262,24 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/
0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg
dad1498b1dca57b4f0ad4e13e047332b66b59a8ce2f398b090bc952279b808cb src/admin/web/file-logs.js
882e99059bb2ff110c452eadc0b5779a16af1e34cb1b2536c80cf2056f8c3e8a src/admin/web/host404.js
-790e4068a8889ad1e4a784aed7383ce8513e30da73de3e39af94ab8b12c8f399 src/admin/web/index.html
-5746049029caa135646ebcefb3d419b07eda17b560a9c015c59d27f815df64d8 src/admin/web/integrations.js
+a994313290a4620a6070d12ce5a434ac39274b7bca04a26536ea54656d45be2e src/admin/web/index.html
+0d6a24d4d25ff43a5bbbfcc2b8930db68476c940f09799e6c37c8144007cc7ab src/admin/web/integrations.js
7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json
ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html
c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/login.js
44b44790341067304e15974afcbbc7cc99686e88c2e43f62979d285eca6f726e src/admin/web/management.js
1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html
1fcbe9017bd6f32cdbdcf65fcc6f4342daf9632a5e1a97c7a3a56d76cbe87095 src/admin/web/partials/overview-metrics.html
-3928afce2ed6d5f2d3e29475dd29e4c3bd3c6df180ad5119beaff0c7a58e3b3b src/admin/web/prometheus-token.js
+80d6eb03f204a90f7b140c5b053d0fd8facb350b1c96b74fa1402e2a35d4fb10 src/admin/web/prometheus-token.js
6f33915d33d3a8bbfaeec424651a63eda3d23b0f296ae028a59ea46463ba9fdf src/admin/web/redirects.js
-76a01f590d49649dcb1f554c221290919b2a8438e6001737f3c096fa6daec74d src/admin/web/settings.js
+a6bf1772b4cc4d4dd8a25165c7e0ec3fa9b39d2eda893e24d3beef814d760e85 src/admin/web/settings.js
8eadbada619b15087783dcfa0e889a81f88e78034d084c5ab616f7912b835940 src/admin/web/status_200.html
a5191e1272939014a21b8d16588704952e9a705b02bd87fd8f8baca0a64ca919 src/admin/web/streams.js
+9d9eb0c2395334836bb1c40f0a9cc946780d5ac7290770d6448628b7c4686140 src/admin/web/system-info.js
dd697c7c46e40da006b61220a90ed9579c3c08c1484a96dc746314d5b4c4f3ea src/admin/web/traffic-panel.js
675ea169d4cc55fda5e291af536338b882bede1eaa6c9d5cc7dfde0779c7c4d1 src/admin/web/transform-panel.js
-e95b6a582a61e2ac80cddf67558d8f92ff400f238f990a1e4e02054cb9798464 src/admin/web/vhosts/core.js
-dc0fc85c64eef983d575f1b220c53c28cf5d4944b77860a57f9f28c6fde2a386 src/admin/web/vhosts/editor.js
+952c82e5d656db19d68fef19c310941f4102b1900620486d26932a24195abd08 src/admin/web/vhosts/core.js
+c8e33e9401b49648098b59bc2c3f5542be35cf44c00c7d04050a6d7fe4525e51 src/admin/web/vhosts/editor.js
3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js
b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js
8c3da49973c62333559b0e3588c02beb0b425c025eac5cfa82a1bb968f70d9dd src/admin/web/vhosts/rates.js
@@ -333,25 +336,28 @@ dd2d3132d4a8d2f453021d27bd8c804159edd86d286d4c3ddf6b47aadca80a09 src/cache/look
4148106b9baf70e41eeba24233b1edbe8dd6f927c11f2c7647e89fbbfb60555e src/cache/lookup/hot_hit_034_tests.rs
e9c6ab0c2be9f96573f826e6a1b9e4c2b8b526f779e72e95a6463ae07e45ab55 src/cache/lookup/insert.rs
7f02dc8eeb6123cb22307b76985b606afda2d87b7f845894685cfe4a9aee8b2a src/cache/lookup/tiered.rs
-639d5be6258699ec7e9f260ec33bd2c366203b6655bf0e98f30517c2e12ceeeb src/cache/mod.rs
+46564e91dde4a3232a62ae56008ae9c6b45fe7c5520b19add5735c7a5a4c2d9d src/cache/mod.rs
0c8b0d550e94d4474dcdf991aa0340228dc5f2f904f39350e6e666a16f16fe87 src/cache/model.rs
b96e30ef2b12ad7647915457f087a4d11b6141847bc5e971a75c2739c88c3d8c src/cache/model/cache.rs
0ec4f6d0adea1ed80a3ca17c68c9c85502491da2904d9d690b4169ab9b025b21 src/cache/model/cold_metadata.rs
-a85b56cffe44d9ef4db43276f9c1ac76aa1661b578c389dad9c2294f2a391164 src/cache/model/entry.rs
+f9be7b0ed0e0e1998fc91f5b05d42220029a05927cb69ccd2ff1edbe4c3bba58 src/cache/model/entry.rs
ff1c3a1a3bc0d26218dcc943ef951c2a212c180bbf6e4bf1c542ffbf12a9f150 src/cache/model/http_invalidation.rs
ee9508498d420a726abee1d12ca21fd5117c1908ff53c2ce29f01de4380f26ac src/cache/model/maintenance.rs
-38acaba0131b32d2f2174dd708439df654934fe9106504917954a66d1d7e5e6d src/cache/model/settings.rs
+61fa507e0489edc0eee2777c93b8b61ee84cccd9da03ae9374ab61a9023cd32c src/cache/model/settings.rs
14f3f8ae5252a2dc13fcf9556523ffb945b77ee92a5fb4939cd27e113fc61660 src/cache/model/views.rs
e26dce02df9c043329ca164fed215d271781bce8fb03240f528331bf3df6b9d7 src/cache/policy.rs
70c255e15f2b8c030988a2263b0e07b5c16e7e26770c72becbcec6da4550fcd9 src/cache/policy/request.rs
-5ce9e2b6cc031b4aea533c4b7375417496e998b17e1ab3cd4f6058e8da503a4b src/cache/policy/response.rs
+b3b05b291922834dfe170c5961f6c395d9209c3904111834a70d8aca2468f803 src/cache/policy/response.rs
12a6d5d9d6711e956391b4b952e8149658b8bf64cfcc0a4c59c281f2630a6aac src/cache/policy/scope_tests.rs
c3a4300f7cdb6b2b7c16fbc489d49ba2451331bb4a55a2d9f618c684fd61eecb src/cache/range.rs
+b02744a7d310cebd2608db07e6ffaf43c20df564266cbefbff8181ec75b3eccc src/cache/rules.rs
+88f3f5acc88ae92a4a0695de791dade6186365c5a1b9a931f3f30cc039754691 src/cache/rules_tests.rs
ddbbf6565ef930dfb4cfa1dbfca7a58e36224382aae789f89b69a910a3b74866 src/cache/stats.rs
-8a300f5dad44815401eb23f4f5a157893761852ba4f3005041e0eb3f16892ce3 src/cache/tests.rs
-ce3d62de66b9dc73c81320478b3090408bbad94e7dbe2885576240fc9270dfed src/cache/tickets.rs
+2981e35a7fbbc2b36214b5518f4ba97d57c1d2e01f4f375175c4b2c6be955927 src/cache/tests.rs
+b969394b04859b269dcecd8958b1aab40b532709512714e9900f0ecad6b6d0c5 src/cache/tickets.rs
a1132b980833b1b4ce2bba9aa681ff255a0e2d61faaa65a316860da503ea1e27 src/cache/v022_cache_tests.rs
4ba0a2e1c21a79cf68bf34cca1f2c2a3d7b20aef38f3b9f510743e60bc1d425f src/cache/varnish_compatible_tests.rs
+3f56ef17d81b7dca532e5c66857119c7ee833788416e968dbbf464e562022be6 src/cache/vcl.rs
1a2eb6684d9ea4a7e90970d936c75f7c8bbec46a4181fdf273be9bdac8eec847 src/compression/mod.rs
8de82d9188c9c337690c6ec4afdad9fff20651c358e34602a93d8bb8c3d2489a src/compression/tests.rs
e695079333ebdc2a6e7b3337cfabef171b3a0a01da0597b77feff70d417f833e src/config.rs
@@ -360,7 +366,7 @@ e695079333ebdc2a6e7b3337cfabef171b3a0a01da0597b77feff70d417f833e src/config.rs
fbea01fea1213d98aea812c1b78d5db289e09200b98ae514d742235cd3fa70e1 src/config/internal_routing.rs
cc75698be2828000e88f2c482bd26f2fa4050e3432bec1b5a581dca17fef4a37 src/config/model.rs
75839458ddbc7480ec4492a95eeb67b617ba7d62f7b67e7a767a3453b74dbcbc src/config/route_policy_tests.rs
-e442c6561723e8dbf73d25912227cebf7aa84ac1523e8bda8e6b4bdad1b674df src/config/routing.rs
+b07abc119aac079f4bc4715a1e0dea735f84eb50f760b97ce429fbd8cee33106 src/config/routing.rs
b33c45184e6451e15ce238cc922d2116269a1bf1d72093c2cdc068c4386a35bd src/config/snapshot.rs
477cddaa1e1c0b9b605a2f550971a04cf30287519cba70cfbb2e1860e3a93ff2 src/config/tests.rs
f35de0ee1516ece6bbfd2b2a7db7d1e0f5048b0ec47cf2a3765dffb799abfd93 src/config/transport_tests.rs
@@ -425,7 +431,7 @@ eb95c68c8639ce3ae658eea3334795cdb5e129fb2ba10955f7dffe06d8909b57 src/pages/mod.
d09dc18863b0508a5e8d54a5305904170f3e8f12857b7a0d5393a11849541e50 src/pages/tests.rs
5650a3f70162abd97021e0a51a92cac2c4dd39004426ef99dff36cbb0741aeac src/prometheus.rs
b9d71633703469d1d14e89c4d8a7698f4d354e5111cfe6ed3b2587566d0e2333 src/prometheus/core.rs
-1fffe1540387632cd93f549025d69a13f39abccf86de376c3fe91b90c2f224c6 src/prometheus/docker_misc.rs
+8595f0a7d1b075ec825a4a4b55b71dabda3d7be450718e9d7e7f554b3ef1c695 src/prometheus/docker_misc.rs
cc909edf740a091f9057912f555dd888b644fa1cb49647fe0e2e1f5dba8ff5af src/prometheus/json.rs
f9aab3297fcf647295849f77cbf99197f4dd27efd6817e54c03451e04972430c src/prometheus/model.rs
f8a9541b568ade946dfc0b3353548a773a0126f705b537815ce0523439b07ef4 src/prometheus/tests.rs
@@ -441,15 +447,15 @@ df239d37b008691d54e257626009684310e6e3712e777094b8450579d56f732f src/proxy/cach
811a00b55b24638b4bf8a6bea9ed7c0ffe2a758f76bfe63a95e1d31bce1c2c9c src/proxy/cache_plan/tests.rs
d6bd4aafab7b1371c31b3d22ddf949a08ea942489649ca12c7615b3b2d5a109a src/proxy/error_fallback.rs
d0d64fd4dd89efd4a9fe089ff4551815cbeaf5b883ddcff803f1b13b5e918dc2 src/proxy/forward/cache_fast_path_tests.rs
-7611390a02341d5f9fd223626e57e0f2f129ab45e03fb1bc105be68d46b86a9a src/proxy/forward/cache_lookup.rs
+016bb2719511df1fc5c70256fd7d917b95e9b4ee6044c205537472737b1f6089 src/proxy/forward/cache_lookup.rs
287012c81144d8f15af4a148ce3ca911d431bc59adff44e697567561aa372bb3 src/proxy/forward/h3_navigation_tests.rs
-728576f7a42292386eca9cf450779364da87f94dc0031ba46c6f4d5302755949 src/proxy/forward/response.rs
-0ba6b62e8560d6f7b99ca7e387f058412fd44456f5874a8258c1c24595c435f4 src/proxy/forward/route_cache.rs
-28aecd57891ef67a618a0f8e4df0aee95d0cb6090facf37e531cd190331d06e7 src/proxy/forward/success_finish.rs
-ccc54869ffbcf1edae9ddb96f6dc2191739f8804ee0318b7a6844def6c4693e5 src/proxy/forward/success_prepare.rs
+a2a097852d126851fc7191c2fda65764dc842745ad657b970399c1f906caf114 src/proxy/forward/response.rs
+f8f07bfd98d52e2908b4dbfa85b3a37cf8ac699dd834e2aac2f95cf431966145 src/proxy/forward/route_cache.rs
+bb3c264772dd246521145a7d0fa538b1a34e1abe906cb69c7348e5d97c98ccae src/proxy/forward/success_finish.rs
+3c10a4a582d22bbc3ee9bbcfddc2d670cf20d97ad9394608afd4d4fc968af0e4 src/proxy/forward/success_prepare.rs
c965dba1d2639b338f3f3cfc17f760786a30abab708dfb7920ea3bc94d4d734b src/proxy/forward/upstream.rs
5d72200f3b5308215b7a3d7b1f910932eaa4712f9e2954afdfbe2f252e2a2d3c src/proxy/forward/web_source.rs
-5f243b21fd719a0c0bc6cdb359b0272c6c11cd9e7c7152d94787cae5476b61bd src/proxy/forward_entry.rs
+e41c2b327175374bfdcb78108bd4eb73e15830b669b2130b6d2edff6c40c2577 src/proxy/forward_entry.rs
9b25f5e3ea4443a63ee6f45d12e1957dd316fe8e85325fc00ea416faaab1025a src/proxy/h2_graceful.rs
30057732c35c369740a176f7da285e35a4157571a04328f6c6f1494d4ec8550b src/proxy/headers/authority_tests.rs
e87437ccf80e50e0159d204dfdd1f8dc0739b6e375be192fce0af749810258cf src/proxy/headers/mod.rs
@@ -459,7 +465,7 @@ a08ee061e146cb7a08311106f73a04468c89f77b6ad05a2c623621a2ae9faf2a src/proxy/mod.
92806ce1802da9b6771ece474d91a3458eba3f6ed19b0817b897e828a02e7e32 src/proxy/redirect_helpers.rs
de1763b89d98607e20f0f6e3c9b546483927cbe5450efc2e5634fe691fd52ad6 src/proxy/request_id/mod.rs
78bbc1263bcd600527bf71acdf5af92bf186267a9084b076d1f75ad6492df659 src/proxy/request_id/tests.rs
-9d7cc19e78f50c9b96e8ada076e12ba96d7a19a51975a13e554c4463e624ee92 src/proxy/types.rs
+6a00700dc04f30bb1134cce5e0b66347923f7c766f31b3d5e63159cd719e5f16 src/proxy/types.rs
e44430c54038a7dc26f327b5d7085e965241da2ffef42c1526ebfc5168981f72 src/proxy/upstream_helpers.rs
c3887e344249ce492862c365896731127b7b6fc51bbfda274d7e7aad3a70be0c src/proxy/web_cache_revalidation/mod.rs
5522456cc85948228250feac92308d53b130c4a7af98d24f669aca4dfe6999b6 src/proxy/web_cache_revalidation/tests.rs
@@ -514,9 +520,9 @@ df98becda799b6bf4ff5e2fec7d0e0a486e6b7eca6f9f5ad49ffdafd49a4f498 src/tls.rs
93e0576ac9077e645a72d164bad34cd75fe6032dd0516284d08bddd2fbda4b7c src/tls/certificates.rs
5703876c4697512f714e9813e56acb6f852c921140b16d135feee3d0dd21e520 src/tls/external_paths.rs
937b95bb8621ab98d7cad3d223e4dee305350fbd0149b7527396d3bdcc28a68b src/tls/external_paths_tests.rs
-1ff95e95d38eedeefcf8a931569d628763d5a328aa5573c73c928f06795037ba src/tls/server_config.rs
-688b929615ebc1d873461237c3de6dfa169984230266a59aad78d93f0eaa2cd6 src/tls/tests.rs
-f0981c883e7969362c69d71d03c55e2a57fc833a750609f08ae14a651529e5f9 src/tls/types.rs
+f168dcafa7452cea9291236905f5502bf0b9a5778f219b5b30d117368601f9d9 src/tls/server_config.rs
+2d46b183ea6ab0ef4827e7ceff4cd87c7fb5a3e987789e222a3a617b5e2bd7db src/tls/tests.rs
+90be472a03d0b1962b466afdd82b8935d98f77d2bb17bd437cbfc3a116ffa402 src/tls/types.rs
58f01b9a6dd1095877cc71445b3ccd651d8b2a1a9c0ad543547840834ec1d91b src/traffic/mod.rs
bd62b4ecdcf831d183c7720766a11703c8612d614e3abf38d2bff28df34710fd src/traffic/tests.rs
bfbbaa3b949ae946fa929bfbae3fd9a25f2ce792abbd0ed370ccf5683250bc4d src/transform/apply.rs
@@ -577,7 +583,7 @@ f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures
102b83171a6429b6375d8001d6c5294702385cd58ee55727cb657b1f3566e877 tests/panel_icons_browser.py
c4030b7d224553312012b1f25153dd3545e83de7bccff2894c0e8f7e0e84b721 tests/panel_icons_contract.js
886c89e8517f34af5e2aef9672a8de559f94c536b028f1b9cadf2a2a7220d826 tests/panel_interface_contract.py
-7402118f81f5ee55a8a38876359d20c8b001f94951618288970d4fe037da1352 tests/panel_refresh_contract.js
+6176c7a70ca692ba9879f74040a25e2e7520fd53bb501e991452aa0f1c02a7d3 tests/panel_refresh_contract.js
e24a0f84f1bfc46964df865ac387d651f7b384d781cbc8f3a9a5b0b60f3d69ca tests/vhost_auth_selection.js
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 third_party/swagger-ui-5.33.1/LICENSE
0d20d1adef18aee3f40dd258172155521ce702ac445cb5f7b7d60ed32dad2fb2 third_party/swagger-ui-5.33.1/NOTICE
diff --git a/docker-agent/README.md b/docker-agent/README.md
index d57c648..d2103d4 100644
--- a/docker-agent/README.md
+++ b/docker-agent/README.md
@@ -139,6 +139,6 @@ The API is `GET /v1/inventory` with `Authorization: Bearer `; `GET /healt
- `x509` or fingerprint mismatch in RustProxy: compare `sudo rustproxy-docker-agent print-fingerprint` with the pin configured in Settings.
- Cannot reach port `9876`: check `RUSTPROXY_DOCKER_AGENT_LISTEN`, listening socket, firewall, and that HTTPS is used.
-`RUSTPROXY_DOCKER_ADVERTISE_IP` adds a preferred host address without suppressing automatic address discovery. `RUSTPROXY_DOCKER_PUBLIC_IP_URL` controls the optional externally observed public IP. The agent's Docker socket access remains privileged; isolate the Docker host and network accordingly.
+`RUSTPROXY_DOCKER_ADVERTISE_IP` adds a preferred host address without suppressing automatic address discovery. Since 0.37.1 the agent also reports the addresses of container bridge interfaces (`docker0`, `br-*`, `podman*`, `cni-*`, `virbr*`) with source `bridge`, listed last; veth interfaces are never reported. `RUSTPROXY_DOCKER_PUBLIC_IP_URL` controls the optional externally observed public IP. The agent's Docker socket access remains privileged; isolate the Docker host and network accordingly.
Default `technical_name` uses the sanitized Docker container name (including Docker Compose container names), not the image or a port suffix. Each published TCP port still has an independent stable service key.
diff --git a/docker-agent/model.go b/docker-agent/model.go
index 74c422f..a0c2dc7 100644
--- a/docker-agent/model.go
+++ b/docker-agent/model.go
@@ -1,6 +1,6 @@
package main
-var version = "0.37.0" // overridden by the package builder using -ldflags -X main.version
+var version = "0.37.1" // overridden by the package builder using -ldflags -X main.version
type config struct {
Listen string
diff --git a/docker-agent/network.go b/docker-agent/network.go
index 6b51927..e17aca2 100644
--- a/docker-agent/network.go
+++ b/docker-agent/network.go
@@ -71,14 +71,37 @@ func skipInterface(name string) bool {
return name == "docker0" || strings.HasPrefix(name, "docker") || strings.HasPrefix(name, "veth") || strings.HasPrefix(name, "br-") || strings.HasPrefix(name, "virbr")
}
+func bridgeInterface(name string) bool {
+ name = strings.ToLower(strings.TrimSpace(name))
+ if strings.HasPrefix(name, "veth") {
+ return false
+ }
+ return skipInterface(name) || strings.HasPrefix(name, "podman") || strings.HasPrefix(name, "cni-")
+}
+
func localHostAddresses() []hostAddress {
+ return interfaceAddresses(false)
+}
+
+func bridgeHostAddresses() []hostAddress {
+ return interfaceAddresses(true)
+}
+
+func interfaceAddresses(bridges bool) []hostAddress {
interfaces, err := net.Interfaces()
if err != nil {
return nil
}
+ source := "interface"
+ if bridges {
+ source = "bridge"
+ }
out := make([]hostAddress, 0)
for _, iface := range interfaces {
- if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 || skipInterface(iface.Name) {
+ if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
+ continue
+ }
+ if bridges != bridgeInterface(iface.Name) || (!bridges && skipInterface(iface.Name)) {
continue
}
addrs, err := iface.Addrs()
@@ -97,7 +120,7 @@ func localHostAddresses() []hostAddress {
continue
}
ip := net.ParseIP(clean)
- out = append(out, hostAddress{IP: clean, Source: "interface", Interface: iface.Name, Scope: ipScope(ip)})
+ out = append(out, hostAddress{IP: clean, Source: source, Interface: iface.Name, Scope: ipScope(ip)})
}
}
sort.Slice(out, func(i, j int) bool {
@@ -176,6 +199,12 @@ func detectedAddresses(ctx context.Context, cfg config, detector *ipDetector) ([
if advertised != "" {
mergeHostAddress(&out, index, hostAddress{IP: advertised, Source: "override"})
}
+ for _, item := range bridgeHostAddresses() {
+ if len(out) >= 48 {
+ break
+ }
+ mergeHostAddress(&out, index, item)
+ }
switch {
case advertised != "":
diff --git a/docker-agent/system_test.go b/docker-agent/system_test.go
index 9fc87ea..3dc5ed6 100644
--- a/docker-agent/system_test.go
+++ b/docker-agent/system_test.go
@@ -188,3 +188,21 @@ func TestProvisionCodeRoundTrip(t *testing.T) {
t.Fatal("garbage accepted")
}
}
+
+func TestBridgeInterfacesAreReportedSeparately(t *testing.T) {
+ for name, want := range map[string]bool{"docker0": true, "br-1a2b": true, "virbr0": true, "podman0": true, "cni-podman0": true, "veth12": false, "eth0": false, "br0": false, "wg0": false} {
+ if got := bridgeInterface(name); got != want {
+ t.Fatalf("%s: %v", name, got)
+ }
+ }
+ for _, item := range localHostAddresses() {
+ if item.Source != "interface" || bridgeInterface(item.Interface) {
+ t.Fatalf("host address %#v", item)
+ }
+ }
+ for _, item := range bridgeHostAddresses() {
+ if item.Source != "bridge" || !bridgeInterface(item.Interface) {
+ t.Fatalf("bridge address %#v", item)
+ }
+ }
+}
diff --git a/docs/ACCESS.md b/docs/ACCESS.md
index 12b109b..6abd5a2 100644
--- a/docs/ACCESS.md
+++ b/docs/ACCESS.md
@@ -5,6 +5,8 @@ Access control can be configured globally, on a Vhost and on selected Custom loc
## Global block / allow policy
**Settings → Rules & headers → Global block / allow** applies to public HTTP traffic across all vhosts, redirects and not-found hosts before upstream access. In addition to the existing User-Agent deny patterns, use the global country block/allow list (ISO two-letter codes), client IP/CIDR and allow-only DNS ACL, HTTP method policy, request Content-Type denylist and shared per-IP rate limit. All are disabled by default except previously configured User-Agent blocking. An explicit IP allow does **not** bypass the country policy: both must permit a request. Missing GeoIP country is allowed for country block mode and denied for country allow mode.
+The page starts with a **status bar** listing every rule (country access, User-Agent blocklist, IP/CIDR and DDNS access, HTTP methods, Content-Type and shared rate limit) with its current state (*off*, *on*, *block list*, *allow list*); click an entry to jump to its section. Each section heading shows the same badge, and a section that is off hides its fields until it is switched on. **Countries** are chosen from a searchable list (ISO code and country name in the panel language); typing a name or a two-letter code and pressing Enter adds it.
+
Global restrictions add to per-vhost and path rules. Rate-limit requests are counted for each client IP **across** vhosts. Prefer a conservative shared ceiling to avoid blocking shared NAT clients. A global method denial returns 405, the content-type/ACL/UA policy returns 403, and the shared rate limiter returns 429 with `Retry-After`. Admin and TCP/UDP stream listeners are outside this HTTP scope. For global response headers, use the adjacent **Security headers** subtab; see [Security](SECURITY.md).
## IP, country and DDNS rules
diff --git a/docs/API.md b/docs/API.md
index 9aa58c8..348c5ae 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -21,6 +21,7 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot
| `GET /api/config/history` · `POST /api/config/history/restore` | Review/restore retained configuration snapshots. |
| `GET /api/status` · `GET /api/backends` | Operational status and backend observations. |
| `GET /api/cache` · `POST /api/cache/purge` · `POST /api/cache/invalidate` | Cache observations and authenticated invalidation. `GET` supports the lightweight `view=live` polling view. |
+| `GET /api/cache/rules/stats` · `POST /api/cache/rules/test` · `POST /api/cache/rules/import-vcl` | Cache rule match counters, simulation of saved or draft rules for a test request/response, and conversion of a VCL subset into rules (nothing is saved). See [Cache rules](CACHE.md#cache-rules-vcl-style). |
| `GET /api/transform` | Transform observations and resource usage. Supports the lightweight `view=live` polling view. |
| `GET /api/logs` · `GET /api/live-logs` | Recent and streaming request logs. |
| `GET /api/file-logs` · `GET /api/file-logs/query` | Stored-log exploration. |
@@ -47,12 +48,16 @@ The administration listener is HTTP on loopback (`127.0.0.1:9090`) by default an
| Credential | Scope |
|---|---|
| Browser session | Full administration. HttpOnly, SameSite=Strict cookie (Secure on HTTPS), absolute lifetime 7–30 days. Writes require matching Origin, `X-CSRF-Token` and `X-RustProxy-Request: 1`. |
-| General API token (`ro` / `rw`) | Created in **Settings → Security → API tokens**. Displayed once, stored as a hash, bound to a mandatory IP/CIDR allowlist. Sent as `Authorization: Bearer `. `ro` reads resources and sections; `rw` also writes configuration sections and selected operations. Cannot manage authentication, backups, tokens or certificate credentials. |
+| General API token (`ro` / `rw`) | Created in **Settings → Security → API tokens** (see [API tokens in the panel](#api-tokens-in-the-panel)). Displayed once, stored as a hash, bound to a mandatory IP/CIDR allowlist. Sent as `Authorization: Bearer `. `ro` reads resources and sections; `rw` also writes configuration sections and selected operations. Cannot manage authentication, backups, tokens or certificate credentials. |
| Certificate API key | Key ID + Bearer token limited to specific certificate IDs and actions (reload by default, deploy opt-in). |
| Prometheus token | Scrape-only credential for the separate exporter; see [Monitoring](MONITORING.md). |
IP checks use the transport peer, never forwarded headers. Outside loopback, Bearer credentials require administration HTTPS.
+### API tokens in the panel
+
+**Settings → Security → API tokens** lists the tokens first (ID, RO/RW badge, description, allowed addresses, created / last used, **Revoke token**). **New token** opens an editor with a description, the permission as two choices (*Read only* / *Read and write*) and **Allowed source addresses** entered as chips: type an IP or CIDR and press Enter; a single address becomes `/32` or `/128`, invalid entries are rejected before saving (at most 32). The token is shown once in a highlighted box with **Copy**; RustProxy stores only its hash. Tokens cannot be edited — revoke and create a new one to change the permission or addresses.
+
### `/docs` Reader and Swagger
The authenticated `/docs` page has two tabs: **Reader** with the guides embedded at build time, and **API** with the bundled OpenAPI schema rendered by Swagger UI. All assets are served locally; no CDN is used. Swagger uses the current session, executes read calls directly and asks for confirmation before any write.
@@ -145,7 +150,9 @@ Run CLI commands as an authorized local operator with the correct private data d
## Restricted Certificate API credentials
-**Settings → Certificate API** can create credentials containing a **Key ID + Bearer token** with explicit certificate-ID grants. New keys default to reload-only; deploy permission is separate. The clear token is displayed at creation/rotation and is not a general admin API token.
+For the panel workflow (permissions, certificate picker, legacy `*` keys) see [Certificates → Restricted certificate API](CERTIFICATES.md#restricted-certificate-api); for an OPNsense example see the [OPNsense ACME client integration](../integrations/opnsense-acme/README.md).
+
+**Settings → Certificate API** can create credentials containing a **Key ID + Bearer token** with explicit certificate-ID grants. New keys default to reload-only; deploy permission is separate. The clear token is displayed at creation/rotation and is not a general admin API token. In the panel, **New key** opens an editor with *Reload only* or *Deploy and reload* and a searchable certificate picker; for deploy keys a not yet stored certificate ID can be typed in, and the first deploy creates it. `*` (all certificates) cannot be saved; keys migrated with `*` keep working until edited, and the editor then asks for explicit certificates.
An authorized client sends:
diff --git a/docs/CACHE.md b/docs/CACHE.md
index df045e8..a24343a 100644
--- a/docs/CACHE.md
+++ b/docs/CACHE.md
@@ -3,6 +3,8 @@
RustProxy provides an optional shared HTTP response cache with a bounded in-memory **HOT** tier and optional persistent-disk **COLD** tier. Both the global cache and a Vhost's effective policy must permit caching. **COLD storage is disabled by default**, and newly created Vhosts do not automatically cache dynamic content.
### Cache controls in Settings
+
+The **Rules** subtab holds the conditional cache rules described in [Cache rules (VCL-style)](#cache-rules-vcl-style).
The static-extension cookie-bypass warning sits with its extension list, separate from **Cache response headers** options. Only enable this optimization for files whose bytes do not depend on the user's session. `Cookie` can then be omitted from the shared cache key for the configured extensions; responses with `Set-Cookie`, `private`, `no-store` or `Vary: Cookie` remain uncacheable.
## Enable caching safely
@@ -51,6 +53,24 @@ With the policy enabled, the middle request stays `HIT` if the entry is fresh. C
In **Vhosts → Cache**, overrides for static extensions, bypass path prefixes and unsafe force targets each place the enable/override checkbox immediately above the associated multiline list. The fields are disabled while their individual override is off; their saved values and cache policy are unchanged. Never enable unsafe forced caching for personalized responses.
+## Cache rules (VCL-style)
+
+**Settings → Cache → Rules** holds global rules; **Vhosts → Cache → Cache rules for this vhost** holds rules for one vhost. They are built graphically ("If … Then …") and replace the most common Varnish VCL snippets without a scripting language.
+
+| Stage | VCL equivalent | Conditions | Actions |
+|---|---|---|---|
+| Request | `vcl_recv`, `vcl_hash` | host, URL, path, extension, method, query parameter, request header, cookie, client IP | bypass cache (`pass`), remove cookies (all or all except listed), remove query parameters (list with `*`, or keep only listed), add a header or cookie value to the cache key |
+| Backend response | `vcl_backend_response` | the request conditions plus status (`200`, `4xx`, `500-599`), Content-Type, response header | set TTL, set grace, do not store, ignore backend `Cache-Control`/`Expires`, remove `Set-Cookie` |
+| Deliver | `vcl_deliver` | the request and response conditions | set or remove a response header |
+
+- Rules run top to bottom (drag to reorder). Each rule matches when all (or any) of its conditions match; a rule without conditions matches every request. *Stop evaluating later rules* ends the stage, like `return` in VCL.
+- Vhost rules run before global rules. A global rule can be limited to selected vhosts. For TTL, grace, bypass and *do not store*, the first matching rule wins: the vhost editor and the global list show which rules override others, and the tester lists every overridden action. *Ignore global cache rules* switches global rules off for that vhost.
+- Request rules change the request like VCL does: removed cookies and query parameters are also not sent to the backend. Values added to the cache key create separate variants (for example one per `lang` cookie).
+- Safeguards stay in place: only GET/HEAD without a body are cached, `Authorization`, Basic Auth, login providers and sticky sessions still bypass the cache, and a response with `Set-Cookie` is never stored unless a rule removes it. *Ignore backend Cache-Control* keeps the original header for the browser; it only changes what RustProxy stores.
+- **Test a request** checks the rules on screen (including unsaved edits) against a sample URL, headers, client IP and backend response, and shows the decision, cache key, TTL/grace, matched and overridden rules. **Import VCL** converts supported statements from `vcl_recv`, `vcl_hash`, `vcl_backend_response`/`vcl_fetch` and `vcl_deliver` (`if`/`elsif`/`else`, `~`, `!~`, `==`, `!=`, status comparisons, `return (pass)`, `unset req.http.Cookie`, query-parameter `regsuball` on `req.url`, `hash_data(req.http.X)`, `beresp.ttl`, `beresp.grace`, `beresp.uncacheable`, `unset beresp.http.Set-Cookie`, `set/unset resp.http.X`); everything else is listed as a warning. **Copy as VCL** shows the equivalent VCL (read-only).
+- Limits: 128 rules per list, 16 conditions and 16 actions per rule, regular expressions with linear-time matching. Match counters live in memory (reset on restart) and are exported as `rust_proxy_cache_rule_matches_total{origin,vhost,rule}` when the *Domains and effectiveness* metric group is enabled.
+- Rules apply to Reverse Proxy vhosts (including Docker vhosts) while the cache is active for the route; built-in web server sources are not affected.
+
## Stored object rules
- Reuse is scoped by frontend scheme, Host, exact client URL, Vhost/content policy and eligible `Vary` dimensions. HTTP and HTTPS objects do not cross-share.
diff --git a/docs/CERTIFICATES.md b/docs/CERTIFICATES.md
index c5288b8..229fbd9 100644
--- a/docs/CERTIFICATES.md
+++ b/docs/CERTIFICATES.md
@@ -63,7 +63,7 @@ When another service owns the certificate, add a manual certificate with the act
### One vhost, several certificates (SNI selection)
-A vhost normally uses one certificate for all of its names. When a single vhost serves domains that have **different** certificates (for example several `autodiscover.` names, each with its own certificate), leave the vhost certificate on **Global SNI / default certificate**. RustProxy then picks the certificate for every TLS connection by the requested server name (SNI) from the stored certificates whose **SNI names** include it. Wildcard names match one label (`*.example.com` matches `a.example.com`, not `a.b.example.com`).
+A vhost normally uses one certificate for all of its names. When a single vhost serves domains that have **different** certificates (for example several `autodiscover.` names, each with its own certificate), leave the vhost certificate on **Global SNI / default certificate**. RustProxy then picks the certificate for every TLS connection by the requested server name (SNI) from the stored certificates whose **SNI names** include it. Wildcard names match one label (`*.example.com` matches `a.example.com`, not `a.b.example.com`). When no SNI name matches, RustProxy also checks the names each stored certificate really covers (its DNS SAN entries), preferring the certificate with the fewest names, before it falls back to the default certificate; so `app.apps.example.com` gets a `*.apps.example.com` certificate even when only `*.example.com` is listed in SNI names.
1. Open **Certificates**, edit the certificate and open **Existing files / advanced**.
2. Check **SNI names**: it is filled automatically from the certificate's SAN entries and can be edited.
@@ -88,7 +88,15 @@ Keep the original Certbot renewal system and use the RustProxy certificate reloa
### Restricted certificate API
-Create an appropriately scoped credential in **Settings → Certificate API**. Its allowed certificate IDs and action permissions control **reload** or **deploy**; it is not a general administration token. A caller supplies both a Bearer credential and its configured `X-RustProxy-Certificate-Key` ID. Use HTTPS outside local/trusted transport and never store the clear token in the repository. See [Administration API](API.md).
+Create an appropriately scoped credential in **Settings → Certificate API**. Its allowed certificate IDs and action permissions control **reload** or **deploy**; it is not a general administration token. A caller supplies both a Bearer credential and its configured `X-RustProxy-Certificate-Key` ID. Use HTTPS outside local/trusted transport and never store the clear token in the repository. See [Administration API](API.md#restricted-certificate-api-credentials).
+
+The tab lists the existing keys first: permission badge (*reload only* or *deploy + reload*), the allowed certificates as chips (a dashed chip is an ID that is not stored yet), creation and last-use time, and the actions **Edit**, **Regenerate token** and **Revoke token**.
+
+- **New key** opens the editor: Key ID, comment, the permission as two choices — **Reload only** for Certbot/acme.sh hooks that write the PEM files themselves, **Deploy and reload** for automation that uploads certificate and key (for example the [OPNsense ACME client integration](../integrations/opnsense-acme/README.md)) — and **Allowed certificates**, chosen in the same searchable picker as elsewhere in the panel (it shows the host names of every stored certificate).
+- For deploy keys, type a new ID in the picker and press Enter: the first deploy creates that certificate. Certificates managed by RustProxy ACME are marked *reload only*; a deploy to them is refused (409).
+- A custom token is optional (*Custom token*); otherwise a strong token is generated. The token appears once in a highlighted box with **Copy**. **Edit** never changes the token.
+- `*` (all certificates) can no longer be saved. Keys migrated from versions before 0.28.2 may still carry `*`; they keep working, are marked in the list, and the editor asks for explicit certificates when the key is edited. Saving an empty list, more than 32 IDs, `*` or an ID with characters other than letters, digits, `-` and `_` is rejected with *Certificate API keys need 1-32 explicit certificate IDs*.
+- The collapsible *Usage example (curl)* shows the reload and deploy calls for the key being edited.
## Problems to check
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 74c7720..f068a85 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -86,10 +86,21 @@ On upgrade, older JSON, database rows, backups and revision history containing a
## Cache and transforms
+Global cache rules are stored in `cache.rules`, vhost rules in the vhost `cache.rules` with `cache.ignore_global_rules`; see [Cache rules](CACHE.md#cache-rules-vcl-style).
+
Caching is opt-in. HOT holds bounded memory entries; COLD is an optional disk tier (off by default). Freshness follows eligible HTTP policy and `Vary`; private/no-store responses and protected requests are not shared. Configuration saves selectively invalidate only the affected cached responses. HTTP BAN/PURGE is **disabled by default** and uses an explicit source-IP allowlist. See [Cache](CACHE.md).
Response transformations are optional and apply only to configured eligible MIME types and scopes. See [Response delivery](RESPONSE_DELIVERY.md) for codec defaults, transformation limits and header precedence. Content rewriting can affect validators, compression and cache entries; test actual representations after configuration changes.
+## Settings pages
+
+- Cards that mix live and restart-only settings (*Administration*, *Prometheus*) show **LIVE + RESTART** in the header and a **RESTART** badge on exactly the fields that need a restart; everything else applies when saved.
+- Long help texts are shortened to two lines; click (or press Enter on) a help text to expand it.
+- The save button of every settings form stays visible at the bottom of the window while you scroll and shows *Unsaved changes* after an edit; the settings tab is marked as well.
+- Lists of credentials (Certificate API keys, API tokens) and addresses (API tokens, Prometheus scrapers) use the same list-first layout and chip inputs; see [Certificates](CERTIFICATES.md#restricted-certificate-api) and [API](API.md#api-tokens-in-the-panel).
+- Global block / allow and listener pages are described in [Access](ACCESS.md#global-block--allow-policy) and [Transport](TRANSPORT.md#frontend-listeners); conditional cache rules in [Cache](CACHE.md#cache-rules-vcl-style).
+- **System information** is a read-only diagnostic page (host, CPU/load/RAM/descriptors, RustProxy process memory and budgets, network interfaces, certificate toolchain, data paths, *Copy diagnostics*); see [Monitoring](MONITORING.md#system-information).
+
## Administration preferences
Appearance settings, Dashboard Presets and Overview cards belong to the administrator profile. **Settings → Appearance → Interface** also includes the default-on stable dialog position option, which keeps editor dialogs anchored near the top while tab content changes height; disabling it restores vertical centering. **Settings → Appearance → Data refresh** keeps the automatic-refresh toggle separate from four intervals arranged in two equal columns (one on narrow screens). The saved corner style (Square, Subtle, Rounded or Extra) applies to controls and surfaces in the main panel and the authenticated Reader/OpenAPI page. **Original** keeps the legacy appearance. Up to 16 named presets can store card visibility, order, widths, density and sample count. Changing the dashboard does not restart proxy listeners or rewrite routing rules. Source sections under `config` have a revision guard to prevent accidental overwrite by a stale editor.
diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md
index 5f93af6..6887ae5 100644
--- a/docs/DASHBOARD.md
+++ b/docs/DASHBOARD.md
@@ -25,7 +25,7 @@ Optional quick-health tiles (since 0.35.2, hidden by default; enable them in the
Enabled tiles are added at the end of the Overview, so the standard block layout does not change.
-Optional Docker cards (since 0.37.0, hidden by default): **Docker agents**, **Docker apps**, **Docker app requests**, **Docker hosts network**, **Docker hosts load** and **Containers**. They summarize agent connectivity, published Docker vhost health and traffic, and the host diagnostics reported by Docker/Podman agents 0.37.0+; With several agents each card can show all agents or one selected agent; see [Docker discovery](DOCKER_DISCOVERY.md#overview-cards).
+Optional Docker cards (since 0.37.0, hidden by default): **Docker agents**, **Docker apps**, **Docker app requests**, **Docker hosts network**, **Docker hosts load** and **Containers**. They summarize agent connectivity, published Docker vhost health and traffic, and the host diagnostics reported by Docker/Podman agents 0.37.0+. The hidden-cards lists show each Docker card type once; with several agents choose the agent next to it before adding, and add the same type again (up to four copies) for other agents. A visible copy shows the selected agent in its title; see [Docker discovery](DOCKER_DISCOVERY.md#overview-cards).
In the **Backends** table with **Table density: Ultra compact**, the backend name line under each vhost is hidden to save space; hover the vhost name (dotted underline) to see the vhost and backend names in a tooltip.
@@ -57,6 +57,14 @@ Controls whose label is already a single symbol (`×`, `−`, `+`, `←`, `→`,
Under **Settings → Appearance → Interface**, enable **Animate logo** to let the sidebar `r/p` logo play a short, subtle effect (rotating slash, letter flip, wave, glow, sheen, glitch or wobble) at random intervals of roughly 10–25 seconds and when the pointer moves over it. The preference is stored per administrator as `logo_animation: true|false` in `/api/preferences` and is **off by default**. Animations pause while the browser tab is hidden and are suppressed entirely when the operating system or browser requests reduced motion.
+### Interface scale and dialogs
+
+**Settings → Appearance → Interface scale** shrinks or enlarges the whole panel. Dialogs (vhost and redirect editors, logs, configuration history, About, help) keep their on-screen size at every scale and only their content is scaled, so a smaller scale shows more content instead of a smaller window. Layout sizes based on the browser window are corrected for the scale as well.
+
+### Corner style
+
+The **Corner style** setting (Original, Square, Subtle, Rounded, Extra) also applies to newer controls such as key and token lists, chips, status badges, container meters, listener cards, the rule status bar and cache-rule cards.
+
### Stable dialog position
Under **Settings → Appearance → Interface**, **Keep dialogs at a stable top position** is **on by default**. It anchors primary panel dialogs near the top of the viewport, so switching between editor tabs whose contents have different heights does not make the dialog jump vertically. The account preference is `stable_dialog_position: true|false` in `/api/preferences`; turning it off restores the browser's vertically centered dialog behavior. The setting changes only panel presentation and does not affect proxy configuration or editor data.
diff --git a/docs/DOCKER_DISCOVERY.md b/docs/DOCKER_DISCOVERY.md
index cbb40a2..2c49c75 100644
--- a/docs/DOCKER_DISCOVERY.md
+++ b/docs/DOCKER_DISCOVERY.md
@@ -46,7 +46,7 @@ Go 1.22+ is required only for the manual build, not for a DEB/RPM installation.
### Domains
-An agent has a list of DNS suffixes (`domains`, up to 16), picked in the same searchable multi-select as ACL profiles; type a new domain in the search box and press Enter to add it. Suggestions come from other agents and from wildcard certificates. Every published Docker vhost selects its **master domain** from this list (default: the first domain), so a newly published service is reachable immediately as `.`. **Aliases** may be short labels (expanded below the master domain, or below another agent domain chosen next to the alias input) or full names, which the panel only accepts inside one of the agent domains. Configurations from before 0.37.0 with a single `base_domain` are migrated to `domains: [base_domain]` on the next save; nothing else changes.
+An agent has a list of DNS suffixes (`domains`, up to 16), picked in the same searchable multi-select as ACL profiles; type a new domain in the search box and press Enter to add it. Suggestions come from other agents and from wildcard certificates. Every published Docker vhost selects its **master domain** from this list (default: the first domain), so a newly published service is reachable immediately as `.`. The ★ button on a domain in the picker makes it the master domain. **Aliases** may be short labels (expanded below the master domain, or below another agent domain chosen next to the alias input, which lists the master domain only once) or full names, which the panel only accepts inside one of the agent domains. Configurations from before 0.37.0 with a single `base_domain` are migrated to `domains: [base_domain]` on the next save; nothing else changes.
### Certificates
@@ -57,7 +57,7 @@ A previously selected single `certificate_id` is migrated to `certificate_ids: [
### Default backend IP
-The agent default backend IP is chosen from the **addresses the agent detected** (interface, scope and source are shown) or entered as **Custom address…**. *Automatic* keeps the per-service choice (bind address, primary IP, detected addresses). The list fills after the first successful poll.
+The agent default backend IP is chosen from the **addresses the agent detected** or entered as **Custom address…**. The list is grouped into *Recommended* (primary route, public address or `RUSTPROXY_DOCKER_ADVERTISE_IP` override, the primary one marked ★), *Other host interfaces* and, from agent 0.37.1, *Container bridges* (`docker0`, `br-*`, `podman*`, `cni-*`, `virbr*`), which are reachable only when RustProxy runs on the same host. *Automatic* keeps the per-service choice (bind address, primary IP, detected addresses). The list fills after the first successful poll.
### Host diagnostics
@@ -86,19 +86,19 @@ services:
rustproxy.force_ssl: "true"
```
-Also supported: `rustproxy.websockets`, `rustproxy.cache`, `rustproxy.compression` and `rustproxy.preserve_host` (`true`/`false`). Labels never leave the agent domains, never take a name already used by a vhost, redirect, 404 host or another Docker service and never override a manual setting for the same service. Invalid labels produce a **LABEL ERROR** badge and an alert instead of a vhost. Label publications use the agent defaults (listeners, certificates, ACL profiles, default backend IP). To customise one, open it and press **Apply changes** (it becomes a manual setting); switching **Publish** off stores a disabled manual override. Labels are read only from agents 0.37.0+. The option is off by default because anyone who can start containers on that host can then publish names inside the agent domains.
+Also supported: `rustproxy.websockets`, `rustproxy.cache`, `rustproxy.compression` and `rustproxy.preserve_host` (`true`/`false`). Labels never leave the agent domains, never take a name already used by a vhost, redirect, 404 host or another Docker service and never override a manual setting for the same service. Invalid labels produce a **LABEL ERROR** badge and an alert instead of a vhost. Label publications use the agent defaults (listeners, certificates, ACL profiles, default backend IP). To customise one, open it and press **Apply changes** (it becomes a manual setting); switching **Publish** off stores a disabled manual override. Labels are read only from agents 0.37.0+. The **?** button next to the option opens the label reference with a `docker compose` example. The option is off by default because anyone who can start containers on that host can then publish names inside the agent domains.
### Container state and history
-Agents 0.37.0+ report per published container its state and health check, CPU usage, memory (without page cache) with its limit and restart count; the service row shows them and Prometheus exports `rust_proxy_docker_container_*`. Containers whose image defines no `HEALTHCHECK` are shown as *no health check* (`health: "none"`) and are judged only by their state (running is fine; restarting, exited or dead raise an alert). The small CPU, memory, load and network charts in **Agent details** are sampled in the browser from the agent polls while the page is open, like the other panel charts; RustProxy does not store history.
+Agents 0.37.0+ report per published container its state and health check, CPU usage, memory (without page cache) with its limit and restart count; the service row shows them as separate chips — state with uptime (green when running), health check, CPU and RAM with a fill bar against the memory limit (amber from 75 %, red from 90 %) and restarts (amber above zero) — and Prometheus exports `rust_proxy_docker_container_*`. Containers whose image defines no `HEALTHCHECK` are shown as *no health check* (`health: "none"`) and are judged only by their state (running is fine; restarting, exited or dead raise an alert). The small CPU, memory, load and network charts in **Agent details** are sampled in the browser from the agent polls while the page is open, like the other panel charts; RustProxy does not store history.
### Test connection and one-time codes
-**Test connection** in each agent runs one inventory request with the values in the form, before saving. `sudo rustproxy-docker-agent provision-code` prints a **one-time code** by default: it holds the endpoint, the certificate pin and a single-use enrollment secret valid for 15 minutes (`--ttl 1h` to change), not the token. When you paste it, RustProxy connects to the agent over the pinned HTTPS connection, redeems the secret and fills in the permanent token; the code cannot be used again. The agent service must be running. `provision-code --static` prints the previous reusable code that contains the token (also needed for plain-HTTP agents).
+**Test connection** (next to *Remove* in each agent) runs one inventory request with the values in the form, before saving, and shows the result in a bubble below the button. `sudo rustproxy-docker-agent provision-code` prints a **one-time code** by default: it holds the endpoint, the certificate pin and a single-use enrollment secret valid for 15 minutes (`--ttl 1h` to change), not the token. When you paste it, RustProxy connects to the agent over the pinned HTTPS connection, redeems the secret and fills in the permanent token; the code cannot be used again. The agent service must be running. `provision-code --static` prints the previous reusable code that contains the token (also needed for plain-HTTP agents).
### Overview cards
-Six optional Overview cards (hidden by default; enable them in the Overview layout editor or **Settings → Appearance → Dashboard layout**): **Docker agents** (connected/enabled), **Docker apps** (published vhosts with a healthy backend, down, checking, missing and discovered services), **Docker app requests** (request rate across all Docker vhosts with a chart), **Docker hosts network** (combined host RX/TX rate with a chart), **Docker hosts load** (CPU/memory bars and load per host) and **Containers** (running/total, images, Docker/Podman host count). They read the compact `docker` object in `/api/status` and the live view. Every card exists four times (*Docker hosts load*, *Docker hosts load #2* … *#4*, likewise for the others), so you can place the same card once per agent next to each other. With two or more agents each card has an agent selector — **All agents** or a single agent — so you can monitor agents separately or together. The selector is shown in the card and next to the card in the hidden-cards list of the layout editors, so the agent can be chosen when the card is added. The choice is stored per administrator (`docker_widget_agents` in `/api/preferences`); a card whose agent was removed falls back to all agents.
+Six optional Overview cards (hidden by default; enable them in the Overview layout editor or **Settings → Appearance → Dashboard layout**): **Docker agents** (connected/enabled), **Docker apps** (published vhosts with a healthy backend, down, checking, missing and discovered services), **Docker app requests** (request rate across all Docker vhosts with a chart), **Docker hosts network** (combined host RX/TX rate with a chart), **Docker hosts load** (CPU/memory bars and load per host) and **Containers** (running/total, images, Docker/Podman host count). They read the compact `docker` object in `/api/status` and the live view. Every card type can be added up to four times, so you can place the same card once per agent next to each other. The hidden-cards lists (layout editors and **Settings → Appearance**) show each type once: with two or more agents choose **All agents** or one agent next to it and add it; the next free copy is used. A visible card keeps its agent selector, and its title shows the selected agent instead of *#2–#4*. The choice is stored per administrator (`docker_widget_agents` in `/api/preferences`); a card whose agent was removed falls back to all agents.
The self-signed certificate is persistent. RustProxy pins its exact fingerprint; if replaced, update the pin. A trusted CA-issued certificate can use normal CA and hostname verification instead. Plain HTTP is available only by explicit opt-out and exposes the token in transit.
diff --git a/docs/FEATURES.md b/docs/FEATURES.md
index a53a50a..81681ed 100644
--- a/docs/FEATURES.md
+++ b/docs/FEATURES.md
@@ -66,6 +66,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
- Shared HTTP cache with a memory tier (HOT) and an optional disk tier (COLD).
- RFC 9111 freshness, validators and `Vary`; stale-while-revalidate, stale-if-error and request coalescing.
- Varnish-compatible policy option, forced caching rules and per-location cache switches.
+- Graphical [cache rules](CACHE.md#cache-rules-vcl-style) in the spirit of VCL (bypass, cookies, query parameters, cache-key variants, TTL/grace, headers) per vhost and globally, with a request tester and VCL import.
- RFC 9211 `Cache-Status` and optional `X-Cache` diagnostics.
- Purge and ban from the panel, the API or HTTP PURGE/BAN from allowlisted addresses.
- Live compression with gzip, Brotli, Zstandard and deflate.
@@ -103,7 +104,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
- Panel served on a separate, loopback-only listener by default; optional HTTPS for remote administration.
- Single administrator with Argon2 password, session revocation and CSRF/Origin protection.
- Complete REST API described by a bundled OpenAPI schema with Swagger UI at `/docs`.
-- Scoped `ro`/`rw` API tokens bound to IP allowlists.
+- Scoped `ro`/`rw` API tokens bound to IP allowlists, and certificate-only API keys for ACME automation (for example the [OPNsense ACME client](../integrations/opnsense-acme/README.md)).
- Command-line tools for setup, configuration, certificates, backups and live logs.
See the [screenshots](SCREENSHOTS.md) for a visual tour and the [documentation index](README.md) for detailed guides.
diff --git a/docs/MONITORING.md b/docs/MONITORING.md
index c60a776..f8d0997 100644
--- a/docs/MONITORING.md
+++ b/docs/MONITORING.md
@@ -18,18 +18,31 @@ Vhost and Docker Vhost live request-rate charts use a **recent-traffic adaptive
Overview allows account-specific card layout and history controls; see [Dashboard](DASHBOARD.md). GeoIP/country analytics depend on the installed/update database and whether country capture is enabled.
-**Settings → System information** shows the operating-system/hardware snapshot and **Statistics source**. The old dedicated process-information block is no longer displayed there; this is a panel presentation change only. Process CPU/RAM and related measurements continue to be available in the Overview and authenticated metrics APIs where supported. **Settings → Appearance → Data refresh** stores the per-account refresh intervals; switching off automatic refresh does not disable manual refresh.
+### System information
+
+**Settings → System information** is a read-only diagnostic page built from `GET /api/system-info`:
+
+| Block | Contents |
+|---|---|
+| Host card | Operating system as the title, environment (for example Docker), architecture, kernel, logical CPUs, RAM, swap, host uptime and RustProxy uptime. **LIVE** / **MANUAL** shows whether automatic refresh is on; **Copy diagnostics** copies a plain-text report (host, process, budgets, network, certificate tools, paths) for bug reports, and **Refresh now** fetches a new sample. |
+| Tiles | System CPU and RustProxy CPU with short history lines, load average (1/5/15 min against the number of CPUs), RAM used/total with the RustProxy share, and file descriptors/limit with the OS thread count. |
+| RustProxy process | Resident memory (RSS) split into HOT cache, transient cache buffers, anonymous and file-backed memory; HOT/transient/transform budgets with usage bars; process start, virtual memory, swap, disk read/written and the cgroup limit. |
+| Network | Active interfaces with RX/TX per second and totals, idle interfaces folded away, and an RX/TX history line. |
+| Certificate toolchain | Python → pip → Certbot versions (green when available, red when missing), the managed/system mode and the managed environment path with **Copy**. |
+| Data locations | Data directory and SQLite database path with **Copy**, and the metric sources used on this platform. |
+
+Unavailable values are shown as N/A and never estimated. The short history lines are kept only in the open browser tab (they reuse Overview samples when available) and are not stored by RustProxy, so the page adds no server memory. **Settings → Appearance → Data refresh** stores the per-account refresh intervals; switching off automatic refresh does not disable manual refresh. Overview keeps the full process and network charts; see [Dashboard](DASHBOARD.md).
## Prometheus exporter
-The exporter is **disabled by default** and uses a separate HTTP listener, normally `127.0.0.1:9191`, at `/metrics`. It is not protected by the admin browser cookie; it has its **own** client-network and bearer-token policy. In **Settings → Prometheus** enable the endpoint and configure:
+The exporter is **disabled by default** and uses a separate HTTP listener, normally `127.0.0.1:9191`, at `/metrics`. It is not protected by the admin browser cookie; it has its **own** client-network and bearer-token policy. **Settings → Prometheus** is split into **Endpoint** (enable switch, bind address and path — both marked *RESTART* —, metrics path and **allowed scraper addresses** entered as IP/CIDR chips), **Prometheus bearer token** (status badge, generate/rotate, revoke, one-time token box with **Copy**, token-free trusted networks) and **Metric groups**; the generated `scrape_configs` example is collapsible. Fields without the RESTART badge apply immediately. Configure:
Use the separate **Prometheus token** controls in Settings to generate, rotate or revoke a 32+ character Bearer credential. Its clear value appears only once; copy it directly into your monitoring secrets store. The database keeps only its hash, and rotation/revocation takes effect without reprinting the previous secret. The older environment-variable credential remains supported as a fallback *only until* a generated credential or explicit revocation entry exists. Setting a new token does not reconfigure the exporter listener or its enable switch.
- `listen`, `path`, `allowed_cidrs` and an optional environment-variable **name** `bearer_token_env` (the secret value is supplied separately to the service).
- `allow_trusted_network_without_token` only for a deliberately restricted monitoring subnet. `/0` CIDRs are not accepted in this mode.
-- Collector switches for process/system, Vhosts, traffic, backends, Docker, cache domains, Streams and logging.
+- Collector switches for process/system, Vhosts, traffic, backends, Docker, cache domains, Streams and logging. The *Domains and effectiveness* group also exports `rust_proxy_cache_rule_matches_total{origin,vhost,rule}` — matches of [cache rules](CACHE.md#cache-rules-vcl-style) since process start.
A non-loopback exporter requires a valid generated or environment Bearer token at scrape time, or an explicit token-free trusted-network exception; otherwise requests return 401. The exporter uses plain HTTP; keep it on loopback, trusted network or a protected TLS tunnel. `Forwarded`/`X-Forwarded-For` headers cannot grant exporter access because network restrictions apply to the transport peer.
diff --git a/docs/TRANSPORT.md b/docs/TRANSPORT.md
index e6b6e19..30b113a 100644
--- a/docs/TRANSPORT.md
+++ b/docs/TRANSPORT.md
@@ -9,6 +9,8 @@ RustProxy distinguishes **frontend** client protocols from the **upstream** prot
- **HTTP/3 (QUIC):** optional UDP transport on an enabled TLS frontend, using the listener certificate and supported H3 settings. The host firewall/NAT must pass UDP on the actual HTTPS port, not only TCP/443. Browsers can fall back to H2/H1 when H3 is unavailable.
- **H2C:** explicit cleartext HTTP/2 capability only where the listener or upstream policy enables it; it is not ordinary browser HTTPS.
+In **Settings → Listeners** the *Currently active* bindings are shown at the top, and every listener is a compact card with its name, ID, bind addresses and badges (Internal/Public, TLS, H1, H2 or h2c, H3, disabled). Click a card to expand its editor; new listeners open expanded, and a listener with an invalid field opens automatically when saving. Listener changes need a restart (the card shows *RESTART*).
+
Transport settings attach to **named listeners**, and a Vhost must select the appropriate listener IDs. Addresses locked by CLI/systemd startup cannot be rewritten from the panel. Changing a listener bind or startup-owned TLS option may require a restart.
### Saving HTTP/3 settings
diff --git a/integrations/opnsense-acme/README.md b/integrations/opnsense-acme/README.md
index 25befab..3e5d73f 100644
--- a/integrations/opnsense-acme/README.md
+++ b/integrations/opnsense-acme/README.md
@@ -1,109 +1,134 @@
# OPNsense os-acme-client -> RustProxy
-A simple mechanism for automatically sending a certificate generated by `os-acme-client` on OPNsense to RustProxy via API.
+Deploys certificates issued by the OPNsense **os-acme-client** plugin (Services -> ACME Client) to RustProxy through `POST /api/certificates/deploy`. The script runs as an ACME Client **automation** ("System or Plugin Command"), so every issued or renewed certificate is sent to RustProxy right away. Works with RustProxy 0.28.2 or newer; error hints match RustProxy 0.37.
## Files
-- `opnsense-rustproxy-cert-deploy.sh` - sends the certificate and private key to RustProxy.
-- `rustproxy-acme.conf.example` - example connection settings, API token, and certificate file paths.
-- `actions_rustproxy_cert.conf` - optional `configd` action that allows the script to be executed from Cron in OPNsense.
+- `opnsense-rustproxy-cert-deploy.sh` - finds the os-acme-client certificates, checks them and uploads them.
+- `rustproxy-acme.conf.example` - RustProxy URL, certificate API credential and the certificate mapping.
+- `actions_rustproxy_cert.conf` - `configd` action **Deploy certificates to RustProxy**, offered by the ACME Client automation and by Cron.
-## 1. Installation
+## 1. RustProxy credential
+
+In RustProxy open **Settings -> Certificate API** and create (or edit) a key:
+
+- **Allowed certificate IDs**: every RustProxy certificate id used below (the right side of `RUSTPROXY_CERTIFICATES`), one per line. `*` is not accepted; a key migrated from an older version with `*` must get the explicit list when it is edited. The ids do not have to exist yet: the first deploy creates them.
+- **Also allow deploy**: enabled. Keys created before 0.28.2 were migrated as reload-only and get `HTTP 403 certificate_api.deploy_forbidden`.
+
+Copy the key id and the token (the token is shown only once; regenerate it if lost).
+
+## 2. Installation (OPNsense root shell, SSH or console option 8)
```sh
-cp opnsense-rustproxy-cert-deploy.sh /usr/local/sbin/
+cat > /usr/local/sbin/opnsense-rustproxy-cert-deploy.sh <<'RUSTPROXY_EOF'
+
+RUSTPROXY_EOF
chmod 750 /usr/local/sbin/opnsense-rustproxy-cert-deploy.sh
-cp rustproxy-acme.conf.example /usr/local/etc/rustproxy-acme.conf
+cat > /usr/local/etc/rustproxy-acme.conf <<'RUSTPROXY_EOF'
+
+RUSTPROXY_EOF
chmod 600 /usr/local/etc/rustproxy-acme.conf
-```
-## 2. Configuration
-
-Edit:
-
-```sh
-vi /usr/local/etc/rustproxy-acme.conf
-```
-
-Important parameters:
-
-```sh
-RUSTPROXY_URL='https://127.0.0.1:9090'
-RUSTPROXY_KEY_ID='opnsense-acme'
-RUSTPROXY_TOKEN='RUSTPROXY_TOKEN'
-
-CERTIFICATE_ID='shared-cert'
-
-CERT_FILE='/var/etc/acme-client/certs/CERT_UUID/fullchain.pem'
-KEY_FILE='/var/etc/acme-client/keys/CERT_UUID/private.key'
-```
-
-If `os-acme-client` exports the certificate to a custom directory, simply set the correct paths:
-
-```sh
-CERT_FILE='/path/to/fullchain.pem'
-KEY_FILE='/path/to/private.key'
-```
-
-`CERTIFICATE_ID` is the stable external certificate id. If it does not exist, RustProxy creates a manual certificate entry. If it already exists as a manual certificate, RustProxy rotates it in place. RustProxy-managed ACME ids are rejected to prevent two renewal owners for one lineage.
-
-## 3. RustProxy API
-
-Create a certificate API key in **Settings -> Certificate API** and enter its values in the configuration:
-
-```text
-RUSTPROXY_KEY_ID
-RUSTPROXY_TOKEN
-```
-
-The credential must explicitly allow `CERTIFICATE_ID` and **Also allow deploy** (`allow_deploy`) must be enabled. A reload-only credential will be rejected with HTTP 403.
-
-The script sends the certificate to:
-
-```text
-POST /api/certificates/deploy
-```
-
-The connection from OPNsense to RustProxy should use HTTPS.
-
-## 4. Test
-
-Run the certificate reconciliation:
-
-```sh
-/usr/local/sbin/opnsense-rustproxy-cert-deploy.sh
-```
-
-On success, you should see a message similar to:
-
-```text
-RustProxy certificate reconcile succeeded (HTTP 200, id=shared-cert)
-```
-
-## 5. OPNsense Automation
-
-Optionally install the `configd` action:
-
-```sh
-cp actions_rustproxy_cert.conf /usr/local/opnsense/service/conf/actions.d/
+cat > /usr/local/opnsense/service/conf/actions.d/actions_rustproxy_cert.conf <<'RUSTPROXY_EOF'
+
+RUSTPROXY_EOF
service configd restart
```
-Verify the action first with `configctl rustproxy_cert deploy`. Then go to **System -> Settings -> Cron** and add a scheduled execution of the `Deploy ACME certificate to RustProxy` action.
+Alternatively copy the three files with `scp`.
-The script deliberately reconciles on every run instead of trusting a local cache. The server is the source of truth: an identical RustProxy-owned certificate generation is a no-op, a missing id is created, and changed material is rotated atomically. This also repairs drift when a certificate entry or generation was removed outside OPNsense.
+## 3. Which certificates are sent
-## Additional Options
-
-If RustProxy uses a private CA:
+os-acme-client keeps the files in `/var/etc/acme-client/certs//fullchain.pem` and `/var/etc/acme-client/keys//private.key`. The `` is an internal id that the GUI does not show, so the script finds the certificate by **name** (the *Common Name* or any *Alt Name* of the ACME certificate):
```sh
-RUSTPROXY_CACERT='/usr/local/etc/ssl/rustproxy-ca.pem'
+/usr/local/sbin/opnsense-rustproxy-cert-deploy.sh --list
```
-If you want to connect to a specific LAN address while keeping proper TLS hostname verification:
+```text
+66a1b2c3d4e5f *.apps.example.com apps.example.com (valid until Dec 14 13:43:31 2026 GMT)
+```
+
+Map each name to a RustProxy certificate id (`A-Z a-z 0-9 _ -`, max 64), separated by spaces:
```sh
-RUSTPROXY_RESOLVE='rustproxy.lan:8443:192.168.1.20'
+RUSTPROXY_CERTIFICATES='*.apps.example.com=apps-wildcard example.com=example-com'
```
+
+Every run sends all mapped certificates. A certificate that did not change is a no-op in RustProxy, a missing id is created as a manual certificate and changed material is rotated atomically. RustProxy-managed ACME ids are rejected (409). When several ACME certificates carry the same name, the one valid longest is used.
+
+A single certificate can also be set with `CERTIFICATE_ID` plus `ACME_CERT_NAME`, or with explicit `CERT_FILE` and `KEY_FILE`.
+
+## 4. Connection settings
+
+| Setting | Meaning |
+|---|---|
+| `RUSTPROXY_URL` | Panel origin only: `https://name:port` (no path). |
+| `RUSTPROXY_KEY_ID`, `RUSTPROXY_TOKEN` | Certificate API credential. |
+| `RUSTPROXY_TLS_VERIFY` | `yes` (default) verifies the panel certificate; `no` accepts a self-signed or not yet valid panel certificate. |
+| `RUSTPROXY_CACERT` | PEM file of a private CA that signed the panel certificate (keeps verification on). |
+| `RUSTPROXY_PINNED_PUBKEY` | `sha256//BASE64` pin of the panel key. Recommended together with `RUSTPROXY_TLS_VERIFY='no'`. |
+| `RUSTPROXY_RESOLVE` | `name:port:address` - connect to a fixed IP while using the panel name for TLS and the Host header. |
+| `RUSTPROXY_ALLOW_HTTP` | `yes` allows `http://` to a remote host. Only for a trusted reverse proxy that terminates HTTPS in front of RustProxy; otherwise RustProxy answers `403 certificate_api.https_required`. `http://127.0.0.1` always works. |
+
+### Panel without a valid certificate
+
+Pin of a self-signed panel certificate (recommended):
+
+```sh
+echo | openssl s_client -connect rustproxy.lan:9090 -servername rustproxy.lan 2>/dev/null \
+ | openssl x509 -pubkey -noout | openssl pkey -pubin -outform DER \
+ | openssl dgst -sha256 -binary | openssl enc -base64
+```
+
+```sh
+RUSTPROXY_TLS_VERIFY='no'
+RUSTPROXY_PINNED_PUBKEY='sha256//'
+```
+
+Without the pin only `RUSTPROXY_TLS_VERIFY='no'` is needed; the script then logs a warning on every run.
+
+### Host name
+
+RustProxy accepts only the host names listed in **Settings -> Administration** (public panel HTTPS origin and additional allowed DNS hostnames) or an IP literal. Another DNS name gives `403 auth.invalid_host`. When the panel name does not resolve on OPNsense, keep the name in `RUSTPROXY_URL` and add `RUSTPROXY_RESOLVE='name:port:IP'`.
+
+## 5. Test
+
+```sh
+/usr/local/sbin/opnsense-rustproxy-cert-deploy.sh --check
+configctl rustproxy_cert deploy
+```
+
+`--check` finds the mapped certificates and validates key match and expiry without contacting RustProxy. `configctl` runs exactly what the automation runs. A successful upload prints:
+
+```text
+RustProxy certificate reconcile succeeded (HTTP 200, id=apps-wildcard)
+```
+
+Every run is also written to the system log (tag `rustproxy-acme`, **System -> Log Files -> General**).
+
+## 6. ACME Client automation
+
+1. **Services -> ACME Client -> Automations -> +**: *Run Command* = **System or Plugin Command**, *System Command* = **Deploy certificates to RustProxy**, give it a name and save.
+2. **Services -> ACME Client -> Certificates**: edit each mapped certificate and add the automation under **Automations**.
+3. Click **Run automations** (paper plane icon) on the certificate to test it.
+
+From now on the deploy runs after every issue or renewal. The ACME Client log shows `running automation (configd)`, the result is in the system log.
+
+Optionally also schedule **Deploy certificates to RustProxy** in **System -> Settings -> Cron** (for example daily) to repair drift when a certificate was changed or removed on the RustProxy side.
+
+## Errors
+
+On failure the script prints the HTTP status, the RustProxy error code and a hint.
+
+| Response | Cause |
+|---|---|
+| `403 certificate_api.deploy_forbidden` | Key is reload-only: enable **Also allow deploy**. |
+| `403 certificate_api.certificate_forbidden` | Key does not include that certificate id. |
+| `403 certificate_api.https_required` | `http://` used from a non-loopback address. |
+| `403 auth.invalid_host` | Host name in `RUSTPROXY_URL` is not allowed by the panel. |
+| `403 auth.invalid_origin` | Scheme/host does not match the pinned public panel origin or trusted proxy settings. |
+| `401 certificate_api.invalid_token` | Wrong key id or token, or the token was regenerated. |
+| `409` | The id belongs to a RustProxy-managed ACME certificate. |
+| `no os-acme-client certificate for NAME` | Name not found: compare with `--list`. |
diff --git a/integrations/opnsense-acme/actions_rustproxy_cert.conf b/integrations/opnsense-acme/actions_rustproxy_cert.conf
index 56fb0dd..3e8ffde 100644
--- a/integrations/opnsense-acme/actions_rustproxy_cert.conf
+++ b/integrations/opnsense-acme/actions_rustproxy_cert.conf
@@ -2,5 +2,5 @@
command:/usr/local/sbin/opnsense-rustproxy-cert-deploy.sh
parameters:
type:script_output
-message:deploy ACME certificate to RustProxy
-description:Deploy ACME certificate to RustProxy
+message:deploying certificates to RustProxy
+description:Deploy certificates to RustProxy
diff --git a/integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh b/integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh
index 7896e4a..bf4a6a2 100755
--- a/integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh
+++ b/integrations/opnsense-acme/opnsense-rustproxy-cert-deploy.sh
@@ -1,9 +1,37 @@
#!/bin/sh
set -eu
+umask 077
+PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
+export PATH
-# Deploy an OPNsense os-acme-client certificate to RustProxy; settings live in a separate file.
+RUSTPROXY_URL="${RUSTPROXY_URL:-}"
+RUSTPROXY_KEY_ID="${RUSTPROXY_KEY_ID:-}"
+RUSTPROXY_TOKEN="${RUSTPROXY_TOKEN:-}"
+RUSTPROXY_CERTIFICATES="${RUSTPROXY_CERTIFICATES:-}"
+CERTIFICATE_ID="${CERTIFICATE_ID:-}"
+ACME_CERT_NAME="${ACME_CERT_NAME:-}"
+CERT_FILE="${CERT_FILE:-}"
+KEY_FILE="${KEY_FILE:-}"
+RUSTPROXY_TLS_VERIFY="${RUSTPROXY_TLS_VERIFY:-yes}"
+RUSTPROXY_CACERT="${RUSTPROXY_CACERT:-}"
+RUSTPROXY_PINNED_PUBKEY="${RUSTPROXY_PINNED_PUBKEY:-}"
+RUSTPROXY_RESOLVE="${RUSTPROXY_RESOLVE:-}"
+RUSTPROXY_ALLOW_HTTP="${RUSTPROXY_ALLOW_HTTP:-no}"
+ACME_CERTS_DIR="${ACME_CERTS_DIR:-/var/etc/acme-client/certs}"
+ACME_KEYS_DIR="${ACME_KEYS_DIR:-/var/etc/acme-client/keys}"
CONFIG_FILE="${RUSTPROXY_ACME_CONFIG:-/usr/local/etc/rustproxy-acme.conf}"
+MODE=deploy
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --check) MODE=check ;;
+ --list) MODE=list ;;
+ --config) shift; CONFIG_FILE="${1:?--config needs a file}" ;;
+ -h|--help) printf 'Usage: %s [--check|--list] [--config FILE]\n' "$0"; exit 0 ;;
+ *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;;
+ esac
+ shift
+done
log() {
logger -t rustproxy-acme -- "$*" 2>/dev/null || true
@@ -15,61 +43,128 @@ fail() {
exit 1
}
-[ -r "$CONFIG_FILE" ] || fail "Cannot read config: $CONFIG_FILE"
-# shellcheck disable=SC1090
-. "$CONFIG_FILE"
+case "$CONFIG_FILE" in
+ */*) ;;
+ *) CONFIG_FILE="./$CONFIG_FILE" ;;
+esac
+if [ -r "$CONFIG_FILE" ]; then
+ . "$CONFIG_FILE"
+elif [ -e "$CONFIG_FILE" ]; then
+ fail "Cannot read config: $CONFIG_FILE"
+fi
-: "${RUSTPROXY_URL:?Set RUSTPROXY_URL in $CONFIG_FILE}"
-: "${RUSTPROXY_KEY_ID:?Set RUSTPROXY_KEY_ID in $CONFIG_FILE}"
-: "${RUSTPROXY_TOKEN:?Set RUSTPROXY_TOKEN in $CONFIG_FILE}"
-: "${CERTIFICATE_ID:?Set CERTIFICATE_ID in $CONFIG_FILE}"
-: "${CERT_FILE:?Set CERT_FILE in $CONFIG_FILE}"
-: "${KEY_FILE:?Set KEY_FILE in $CONFIG_FILE}"
-
-CURL="${CURL:-$(command -v curl || true)}"
OPENSSL="${OPENSSL:-$(command -v openssl || true)}"
-[ -n "$CURL" ] || fail "curl not found"
[ -n "$OPENSSL" ] || fail "openssl not found"
-case "$CERTIFICATE_ID" in
- ''|*[!A-Za-z0-9_-]*) fail "CERTIFICATE_ID may contain only A-Z, a-z, 0-9, _ and -" ;;
+cert_names() {
+ "$OPENSSL" x509 -in "$1" -noout -text 2>/dev/null \
+ | tr ',' '\n' | sed -n 's/^[[:space:]]*DNS:\([^[:space:]]*\).*/\1/p' \
+ | tr 'A-Z' 'a-z'
+ "$OPENSSL" x509 -in "$1" -noout -subject 2>/dev/null \
+ | sed -n 's/.*CN[[:space:]]*=[[:space:]]*\([^,/]*\).*/\1/p' | tr 'A-Z' 'a-z'
+}
+
+cert_end() {
+ end=$("$OPENSSL" x509 -in "$1" -noout -enddate 2>/dev/null | sed 's/^notAfter=//')
+ date -j -f '%b %e %T %Y %Z' "$end" +%s 2>/dev/null \
+ || date -d "$end" +%s 2>/dev/null \
+ || echo 0
+}
+
+if [ "$MODE" = list ]; then
+ found=no
+ for cert in "$ACME_CERTS_DIR"/*/cert.pem; do
+ [ -r "$cert" ] || continue
+ found=yes
+ id=$(basename "$(dirname "$cert")")
+ names=$(cert_names "$cert" | sort -u | tr '\n' ' ')
+ until=$("$OPENSSL" x509 -in "$cert" -noout -enddate 2>/dev/null | sed 's/^notAfter=//')
+ printf '%s %s (valid until %s)\n' "$id" "$names" "$until"
+ done
+ [ "$found" = yes ] || printf 'No os-acme-client certificates in %s\n' "$ACME_CERTS_DIR"
+ exit 0
+fi
+
+[ -n "$RUSTPROXY_URL" ] || fail "Set RUSTPROXY_URL (in $CONFIG_FILE or at the top of this script)"
+[ -n "$RUSTPROXY_KEY_ID" ] || fail "Set RUSTPROXY_KEY_ID (Settings -> Certificate API key id)"
+[ -n "$RUSTPROXY_TOKEN" ] || fail "Set RUSTPROXY_TOKEN (Settings -> Certificate API token)"
+
+CURL="${CURL:-$(command -v curl || true)}"
+[ -n "$CURL" ] || fail "curl not found"
+
+case "$RUSTPROXY_KEY_ID" in
+ *[!A-Za-z0-9_-]*) fail "RUSTPROXY_KEY_ID may contain only A-Z, a-z, 0-9, _ and -" ;;
esac
-[ "${#CERTIFICATE_ID}" -le 64 ] || fail "CERTIFICATE_ID is longer than 64 characters"
+case "$RUSTPROXY_TOKEN" in
+ *[!A-Za-z0-9._~-]*) fail "RUSTPROXY_TOKEN contains unexpected characters (copy it again from RustProxy, without quotes or spaces)" ;;
+esac
+[ "${#RUSTPROXY_TOKEN}" -ge 32 ] && [ "${#RUSTPROXY_TOKEN}" -le 128 ] \
+ || fail "RUSTPROXY_TOKEN must be 32-128 characters long"
-[ -r "$CERT_FILE" ] || fail "Certificate not readable: $CERT_FILE"
-[ -r "$KEY_FILE" ] || fail "Private key not readable: $KEY_FILE"
+BASE_URL="${RUSTPROXY_URL%/}"
+case "$BASE_URL" in
+ https://*) SCHEME=https ;;
+ http://*) SCHEME=http ;;
+ *) fail "RUSTPROXY_URL must start with https:// or http://" ;;
+esac
+case "$BASE_URL" in
+ *://*/*) fail "RUSTPROXY_URL must be the panel origin only, e.g. https://rustproxy.lan:9090" ;;
+esac
+HOST_PORT="${BASE_URL#*://}"
+HOST_ONLY="${HOST_PORT%:*}"
+case "$HOST_ONLY" in
+ \[*) HOST_ONLY="${HOST_PORT%%]*}]" ;;
+esac
-# Validate certificate syntax and make sure the certificate and private key belong together.
-"$OPENSSL" x509 -in "$CERT_FILE" -noout >/dev/null 2>&1 \
- || fail "Invalid certificate PEM: $CERT_FILE"
-"$OPENSSL" pkey -in "$KEY_FILE" -noout >/dev/null 2>&1 \
- || fail "Invalid private key PEM: $KEY_FILE"
+if [ "$SCHEME" = http ]; then
+ case "$HOST_ONLY" in
+ 127.*|localhost|\[::1\]) ;;
+ *)
+ [ "$RUSTPROXY_ALLOW_HTTP" = yes ] || fail "RUSTPROXY_URL uses http:// to a remote host. RustProxy accepts certificate API calls over plain HTTP only from loopback (HTTP 403 certificate_api.https_required) and the token would travel unencrypted. Use https:// (for a self-signed panel RUSTPROXY_TLS_VERIFY=no, ideally with RUSTPROXY_PINNED_PUBKEY), or set RUSTPROXY_ALLOW_HTTP=yes when a trusted reverse proxy in front of RustProxy terminates HTTPS."
+ log "WARNING: sending the certificate API token over plain HTTP"
+ ;;
+ esac
+fi
-CERT_PUB=$(
- "$OPENSSL" x509 -in "$CERT_FILE" -pubkey -noout 2>/dev/null \
- | "$OPENSSL" pkey -pubin -outform DER 2>/dev/null \
- | "$OPENSSL" dgst -sha256 2>/dev/null
-)
-KEY_PUB=$(
- "$OPENSSL" pkey -in "$KEY_FILE" -pubout -outform DER 2>/dev/null \
- | "$OPENSSL" dgst -sha256 2>/dev/null
-)
-[ -n "$CERT_PUB" ] && [ "$CERT_PUB" = "$KEY_PUB" ] \
- || fail "Certificate and private key do not match"
+case "$RUSTPROXY_TLS_VERIFY" in
+ yes|no) ;;
+ *) fail "RUSTPROXY_TLS_VERIFY must be yes or no" ;;
+esac
+if [ -n "$RUSTPROXY_CACERT" ]; then
+ [ -r "$RUSTPROXY_CACERT" ] || fail "CA file not readable: $RUSTPROXY_CACERT"
+fi
+if [ -n "$RUSTPROXY_PINNED_PUBKEY" ]; then
+ case "$RUSTPROXY_PINNED_PUBKEY" in
+ sha256//*) ;;
+ *) fail "RUSTPROXY_PINNED_PUBKEY must look like sha256//BASE64 (see the README for the openssl command)" ;;
+ esac
+fi
+if [ "$SCHEME" = https ] && [ "$RUSTPROXY_TLS_VERIFY" = no ] && [ -z "$RUSTPROXY_PINNED_PUBKEY" ]; then
+ log "WARNING: TLS certificate of $BASE_URL is not verified; set RUSTPROXY_PINNED_PUBKEY to pin it"
+fi
-# Do not publish an already-expired certificate.
-"$OPENSSL" x509 -in "$CERT_FILE" -checkend 0 -noout >/dev/null 2>&1 \
- || fail "Certificate is already expired"
+TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/rustproxy-acme.XXXXXX") || fail "mktemp failed"
+trap 'rm -rf "$TMP_DIR"' EXIT HUP INT TERM
-# The deploy endpoint is idempotent, so always reconcile instead of trusting local state.
+find_acme_cert() {
+ wanted=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
+ best=""
+ best_end=0
+ for cert in "$ACME_CERTS_DIR"/*/cert.pem; do
+ [ -r "$cert" ] || continue
+ cert_names "$cert" | grep -Fqx -- "$wanted" || continue
+ id=$(basename "$(dirname "$cert")")
+ [ -r "$ACME_KEYS_DIR/$id/private.key" ] || continue
+ end=$(cert_end "$cert")
+ if [ -z "$best" ] || [ "$end" -gt "$best_end" ]; then
+ best="$id"
+ best_end="$end"
+ fi
+ done
+ [ -n "$best" ] || return 1
+ printf '%s\n' "$best"
+}
-umask 077
-TMP_JSON=$(mktemp "${TMPDIR:-/tmp}/rustproxy-cert.XXXXXX") || fail "mktemp failed"
-TMP_CURL=$(mktemp "${TMPDIR:-/tmp}/rustproxy-curl.XXXXXX") || { rm -f "$TMP_JSON"; fail "mktemp failed"; }
-TMP_RESPONSE=$(mktemp "${TMPDIR:-/tmp}/rustproxy-response.XXXXXX") || { rm -f "$TMP_JSON" "$TMP_CURL"; fail "mktemp failed"; }
-trap 'rm -f "$TMP_JSON" "$TMP_CURL" "$TMP_RESPONSE"' EXIT HUP INT TERM
-
-# Escape PEM as a JSON string without jq/python.
pem_json() {
awk '{
gsub(/\\/, "\\\\");
@@ -79,53 +174,142 @@ pem_json() {
}' "$1"
}
-{
- printf '{"certificate_id":"%s","cert_pem":"' "$CERTIFICATE_ID"
- pem_json "$CERT_FILE"
- printf '","key_pem":"'
- pem_json "$KEY_FILE"
- printf '"}\n'
-} > "$TMP_JSON"
+hint() {
+ case "$1" in
+ certificate_api.deploy_forbidden) echo "The key may only reload certificates. In RustProxy Settings -> Certificate API edit key $RUSTPROXY_KEY_ID and enable 'Also allow deploy' (keys created before 0.28.2 were migrated as reload-only)." ;;
+ certificate_api.certificate_forbidden) echo "Key $RUSTPROXY_KEY_ID is not allowed to use certificate id $2. Add the id to the key's allowed certificate IDs in Settings -> Certificate API (* is not accepted when saving a key)." ;;
+ certificate_api.https_required) echo "RustProxy accepts certificate API calls over plain HTTP only from loopback. Use https:// in RUSTPROXY_URL." ;;
+ certificate_api.invalid_token|api_token.invalid_token) echo "Key id or token is wrong, revoked or regenerated. Copy both again from Settings -> Certificate API." ;;
+ certificate_api.invalid_route) echo "Wrong URL path: RUSTPROXY_URL must be the panel origin only." ;;
+ auth.invalid_host) echo "Use a name from Settings -> Administration (public panel HTTPS origin or additional allowed DNS hostnames), with RUSTPROXY_RESOLVE=name:port:address to reach it by IP." ;;
+ auth.invalid_origin) echo "The scheme or host does not match the public panel HTTPS origin or the trusted proxy settings. Use exactly that origin (https://name:port) from Settings -> Administration." ;;
+ *) echo "See the RustProxy audit log and the response above." ;;
+ esac
+}
-# Keep the Bearer token out of curl's process arguments by using a mode-0600 config file.
-cat > "$TMP_CURL" </dev/null 2>&1 || { log "ERROR: invalid certificate PEM: $cert_file"; return 1; }
+ "$OPENSSL" pkey -in "$key_file" -noout >/dev/null 2>&1 || { log "ERROR: invalid private key PEM: $key_file"; return 1; }
+ cert_pub=$("$OPENSSL" x509 -in "$cert_file" -pubkey -noout 2>/dev/null | "$OPENSSL" pkey -pubin -outform DER 2>/dev/null | "$OPENSSL" dgst -sha256 2>/dev/null)
+ key_pub=$("$OPENSSL" pkey -in "$key_file" -pubout -outform DER 2>/dev/null | "$OPENSSL" dgst -sha256 2>/dev/null)
+ [ -n "$cert_pub" ] && [ "$cert_pub" = "$key_pub" ] || { log "ERROR: certificate and private key do not match: $cert_file"; return 1; }
+ "$OPENSSL" x509 -in "$cert_file" -checkend 0 -noout >/dev/null 2>&1 || { log "ERROR: certificate is already expired: $cert_file"; return 1; }
+ [ "$(wc -c < "$cert_file" | tr -d ' ')" -le 131072 ] && [ "$(wc -c < "$key_file" | tr -d ' ')" -le 131072 ] \
+ || { log "ERROR: certificate and key must each be at most 128 KiB"; return 1; }
+
+ if [ "$MODE" = check ]; then
+ log "Check OK: id=$certificate_id cert=$cert_file names=$(cert_names "$cert_file" | sort -u | tr '\n' ' ')"
+ return 0
+ fi
+
+ json="$TMP_DIR/body.json"
+ curl_config="$TMP_DIR/curl.conf"
+ response="$TMP_DIR/response"
+ {
+ printf '{"certificate_id":"%s","cert_pem":"' "$certificate_id"
+ pem_json "$cert_file"
+ printf '","key_pem":"'
+ pem_json "$key_file"
+ printf '"}\n'
+ } > "$json"
+ cat > "$curl_config" <> "$curl_config"
+ [ -z "$RUSTPROXY_CACERT" ] || printf 'cacert = "%s"\n' "$RUSTPROXY_CACERT" >> "$curl_config"
+ [ -z "$RUSTPROXY_PINNED_PUBKEY" ] || printf 'pinnedpubkey = "%s"\n' "$RUSTPROXY_PINNED_PUBKEY" >> "$curl_config"
+ fi
+ [ -z "$RUSTPROXY_RESOLVE" ] || printf 'resolve = "%s"\n' "$RUSTPROXY_RESOLVE" >> "$curl_config"
-# Optional trust anchor for an internal/self-signed administration certificate.
-if [ -n "${RUSTPROXY_CACERT:-}" ]; then
- [ -r "$RUSTPROXY_CACERT" ] || fail "CA file not readable: $RUSTPROXY_CACERT"
- printf 'cacert = "%s"\n' "$RUSTPROXY_CACERT" >> "$TMP_CURL"
+ curl_exit=0
+ http_code=$("$CURL" --config "$curl_config") || curl_exit=$?
+ rm -f "$json"
+ if [ "$curl_exit" -ne 0 ]; then
+ case "$curl_exit" in
+ 6) log "ERROR: cannot resolve the host in RUSTPROXY_URL (use RUSTPROXY_RESOLVE=host:port:address)" ;;
+ 7|28) log "ERROR: cannot connect to $BASE_URL (curl exit $curl_exit): check address, port and firewall" ;;
+ 35) log "ERROR: TLS handshake failed with $BASE_URL (curl exit 35): check that the panel listens with https://" ;;
+ 60|77) log "ERROR: TLS certificate of $BASE_URL is not trusted (curl exit $curl_exit): set RUSTPROXY_CACERT, RUSTPROXY_PINNED_PUBKEY or RUSTPROXY_TLS_VERIFY=no" ;;
+ 51) log "ERROR: TLS certificate of $BASE_URL does not match the host name (curl exit 51): use the name from the certificate with RUSTPROXY_RESOLVE, or RUSTPROXY_TLS_VERIFY=no with RUSTPROXY_PINNED_PUBKEY" ;;
+ 90) log "ERROR: TLS public key of $BASE_URL does not match RUSTPROXY_PINNED_PUBKEY (curl exit 90)" ;;
+ *) log "ERROR: request to $BASE_URL failed (curl exit $curl_exit)" ;;
+ esac
+ return 1
+ fi
+ error_code=$(sed -n 's/.*"error"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$response" | head -n 1)
+ case "$http_code" in
+ 2??)
+ log "RustProxy certificate reconcile succeeded (HTTP $http_code, id=$certificate_id)"
+ cat "$response"
+ printf '\n'
+ ;;
+ *)
+ log "RustProxy certificate deploy failed (HTTP $http_code${error_code:+, $error_code}, id=$certificate_id)"
+ cat "$response" >&2
+ printf '\n' >&2
+ log "Hint: $(hint "$error_code" "$certificate_id")"
+ return 1
+ ;;
+ esac
+}
+
+deploy_named() {
+ name="$1"
+ certificate_id="$2"
+ if ! id=$(find_acme_cert "$name"); then
+ log "ERROR: no os-acme-client certificate for $name in $ACME_CERTS_DIR (run with --list to see the available ones)"
+ return 1
+ fi
+ deploy "$certificate_id" "$ACME_CERTS_DIR/$id/fullchain.pem" "$ACME_KEYS_DIR/$id/private.key"
+}
+
+status=0
+count=0
+if [ -n "$RUSTPROXY_CERTIFICATES" ]; then
+ set -f
+ set -- $RUSTPROXY_CERTIFICATES
+ set +f
+ for entry in "$@"; do
+ case "$entry" in
+ *=*) ;;
+ *) log "ERROR: RUSTPROXY_CERTIFICATES entry '$entry' must be acme-name=rustproxy-id"; status=1; continue ;;
+ esac
+ count=$((count + 1))
+ deploy_named "${entry%%=*}" "${entry#*=}" || status=1
+ done
fi
-
-# Optional curl --resolve value, e.g. rustproxy.lan:8443:10.10.10.20.
-if [ -n "${RUSTPROXY_RESOLVE:-}" ]; then
- printf 'resolve = "%s"\n' "$RUSTPROXY_RESOLVE" >> "$TMP_CURL"
+if [ -n "$CERTIFICATE_ID" ]; then
+ count=$((count + 1))
+ if [ -n "$CERT_FILE" ] || [ -n "$KEY_FILE" ]; then
+ [ -n "$CERT_FILE" ] && [ -n "$KEY_FILE" ] || fail "Set both CERT_FILE and KEY_FILE, or ACME_CERT_NAME instead"
+ deploy "$CERTIFICATE_ID" "$CERT_FILE" "$KEY_FILE" || status=1
+ elif [ -n "$ACME_CERT_NAME" ]; then
+ deploy_named "$ACME_CERT_NAME" "$CERTIFICATE_ID" || status=1
+ else
+ fail "Set ACME_CERT_NAME (or CERT_FILE and KEY_FILE) for CERTIFICATE_ID=$CERTIFICATE_ID"
+ fi
fi
-
-HTTP_CODE=$("$CURL" --config "$TMP_CURL") || fail "HTTPS request to RustProxy failed"
-
-case "$HTTP_CODE" in
- 2??)
- log "RustProxy certificate reconcile succeeded (HTTP $HTTP_CODE, id=$CERTIFICATE_ID)"
- cat "$TMP_RESPONSE"
- printf '\n'
- ;;
- *)
- log "RustProxy certificate deploy failed (HTTP $HTTP_CODE)"
- cat "$TMP_RESPONSE" >&2
- printf '\n' >&2
- exit 1
- ;;
-esac
+[ "$count" -gt 0 ] || fail "Nothing to deploy: set RUSTPROXY_CERTIFICATES, or CERTIFICATE_ID with ACME_CERT_NAME"
+exit "$status"
diff --git a/integrations/opnsense-acme/rustproxy-acme.conf.example b/integrations/opnsense-acme/rustproxy-acme.conf.example
index 9df5513..9256cc6 100644
--- a/integrations/opnsense-acme/rustproxy-acme.conf.example
+++ b/integrations/opnsense-acme/rustproxy-acme.conf.example
@@ -1,21 +1,12 @@
-# RustProxy administration endpoint reachable from OPNsense.
RUSTPROXY_URL='https://rustproxy.example.lan:9090'
-# Certificate API credential created in RustProxy Settings -> Certificate API.
-# The credential must allow this CERTIFICATE_ID and have deploy permission enabled.
RUSTPROXY_KEY_ID='opnsense-acme'
RUSTPROXY_TOKEN='REPLACE_WITH_CERTIFICATE_API_TOKEN'
-# Stable RustProxy certificate id to create/update.
-CERTIFICATE_ID='shared-cert'
+RUSTPROXY_CERTIFICATES='*.apps.example.com=apps-wildcard example.com=example-com'
-# os-acme-client certificate material. Replace CERT_UUID with the actual UUID.
-CERT_FILE='/var/etc/acme-client/certs/CERT_UUID/fullchain.pem'
-KEY_FILE='/var/etc/acme-client/keys/CERT_UUID/private.key'
-
-# Optional: trust a private CA used by the RustProxy administration listener.
-# RUSTPROXY_CACERT='/usr/local/etc/ssl/rustproxy-ca.pem'
-
-# Optional: connect to a fixed address while keeping TLS verification for the URL hostname.
-# Format: hostname:port:address
-# RUSTPROXY_RESOLVE='rustproxy.example.lan:9090:192.0.2.20'
+RUSTPROXY_TLS_VERIFY='yes'
+RUSTPROXY_CACERT=''
+RUSTPROXY_PINNED_PUBKEY=''
+RUSTPROXY_RESOLVE=''
+RUSTPROXY_ALLOW_HTTP='no'
diff --git a/integrations/routeros-oci-build/README.md b/integrations/routeros-oci-build/README.md
index f66a201..cbebe1e 100644
--- a/integrations/routeros-oci-build/README.md
+++ b/integrations/routeros-oci-build/README.md
@@ -77,10 +77,10 @@ ENV_FILE=integrations/routeros-oci-build/.env \
bash integrations/routeros-oci-build/build-routeros-oci.sh push
```
-For example, with RustProxy version `0.37.0` and the defaults this publishes:
+For example, with RustProxy version `0.37.1` and the defaults this publishes:
```text
-oci.example.net/network/rustproxy:0.37.0
+oci.example.net/network/rustproxy:0.37.1
oci.example.net/network/rustproxy:latest
oci.example.net/network/rustproxy:routeros
```
diff --git a/langs/en_US.json b/langs/en_US.json
index 2dbff43..1c212c9 100644
--- a/langs/en_US.json
+++ b/langs/en_US.json
@@ -25,7 +25,7 @@
"globalCountryTitle": "Country access",
"globalCountryHelp": "Block listed countries or allow only listed countries (ISO 3166-1 alpha-2). Unknown countries are denied in allow mode. Configure GeoIP updates under Settings.",
"globalCountryMode": "Country policy",
- "globalCountryList": "Country codes (one per line or comma separated)",
+ "globalCountryList": "Countries",
"globalUaTitle": "User-Agent blocklist",
"globalUaEnabled": "Enable global User-Agent blocking",
"globalIpTitle": "IP / CIDR and dynamic DNS access",
@@ -794,11 +794,11 @@
"cacheResidentLabel": "Cache memory",
"certificateFuture": "ACME providers: HTTP-01, Cloudflare, OVH and RFC2136. Renewal is manual.",
"prometheusTitle": "Prometheus",
- "prometheusHelp": "A dedicated read-only HTTP listener, separate from admin sessions. Binding, enabling or changing the token variable requires a restart; CIDRs, path and collectors apply live.",
+ "prometheusHelp": "Dedicated read-only HTTP endpoint for Prometheus, separate from the panel. Fields marked RESTART apply after a restart; the rest applies immediately.",
"prometheusEnable": "Enable the scrape endpoint",
"prometheusListen": "Exporter bind IP and port",
"prometheusPath": "Metrics path",
- "prometheusCidrs": "Allowed scraper IPs (CIDR, one per line)",
+ "prometheusCidrs": "Allowed scraper addresses (IP or CIDR)",
"prometheusTokenEnv": "Environment variable holding the bearer token (optional on loopback)",
"prometheusTokenHelp": "Enter a variable NAME, not the secret. Set its value to a random 32+ character token in the service environment. Non-loopback binding requires it. This endpoint is HTTP: use a private network or a TLS tunnel. The Prometheus credential file must contain the same token.",
"prometheusCollectors": "Metric groups",
@@ -1022,7 +1022,7 @@
"administrationActiveHttps": "Active HTTPS administration",
"administrationCertificate": "Certificate",
"administrationGeneratedCertificate": "Application-generated default certificate",
- "administrationHelp": "HTTPS allows the administration listener to bind beyond loopback. Plain HTTP on the HTTPS port is redirected automatically. Listener and certificate changes take effect after restart.",
+ "administrationHelp": "HTTPS allows the panel to listen beyond loopback; plain HTTP on the HTTPS port is redirected. Fields marked RESTART apply after a restart.",
"administrationHosts": "Additional allowed DNS hostnames",
"administrationHttps": "Enable HTTPS for administration",
"administrationListen": "Listen address",
@@ -1564,7 +1564,6 @@
"prometheusTrustedNoTokenHelp": "Clients still must match Allowed client CIDRs. Enable only on a private, trusted monitoring network; forwarded headers are never trusted for this check.",
"docker-vhosts": "Docker vhosts",
"docker-vhostsTitle": "Docker services, named.",
- "docker-vhostsDescription": "Discover published Docker and Podman ports and map services to names under the agent domains, with aliases, without copying observed state into SQLite.",
"dockerVhosts": "Docker vhosts",
"dockerVhostsIntro": "Published TCP ports discovered by configured Docker/Podman agents. Map each service to a name under one of the agent domains (its master domain), add aliases, choose the Docker host IP, and inspect or tune live backend health for every published service.",
"dockerDiscovery": "DOCKER DISCOVERY",
@@ -1923,27 +1922,27 @@
"cacheTabCold": "Cold cache",
"cacheTabDiagnostics": "Static & diagnostics",
"certificateApiTitle": "Certificate API",
- "certificateApiHelp": "Create separate Key ID + Bearer Token credentials for certificate automation. New tokens are reload-only by default and are restricted to the listed certificate IDs. Enable deploy only for automation that must upload certificate material.",
+ "certificateApiHelp": "Keys let external automation (Certbot, acme.sh, the OPNsense ACME client) reload or upload certificates. Each key works only for the certificates chosen for it and cannot read the configuration or use other administration APIs.",
"certificateApiKeyId": "Key ID",
"certificateApiToken": "Bearer token (optional custom value)",
- "certificateApiTokenHelp": "Leave the field empty to generate a strong token. Each cleartext token is shown only once; RustProxy stores only its hash.",
+ "certificateApiTokenHelp": "Leave empty to generate a strong token (recommended). A custom token must be 32-128 characters: letters, digits, '.', '_', '-' or '~'. The token is shown only once; RustProxy stores only its hash.",
"certificateApiRotate": "Generate / rotate token",
"certificateApiView": "View settings",
"certificateApiHide": "Hide settings",
- "certificateApiEdit": "Edit settings",
- "certificateApiSave": "Save settings",
+ "certificateApiEdit": "Edit",
+ "certificateApiSave": "Save changes",
"certificateApiSaved": "Certificate API settings saved. The current token is unchanged.",
- "certificateApiCancelEdit": "Cancel edit",
- "certificateApiEditNote": "Edit comment, permissions and allowed certificate IDs without changing the token. The Key ID cannot be changed.",
+ "certificateApiCancelEdit": "Cancel",
+ "certificateApiEditNote": "The token does not change. Use Regenerate token to issue a new one.",
"certificateApiRegenerate": "Regenerate token",
"certificateApiRegenerateConfirm": "Regenerate the token for {key}? The current token will immediately stop working. Copy the new token after regenerating.",
"certificateApiRegenerated": "Token regenerated. Copy the new token now; the previous token is no longer valid.",
- "certificateApiCreatedAt": "Created / last rotated",
+ "certificateApiCreatedAt": "created",
"certificateApiPermissions": "Permissions",
"certificateApiTokenLabel": "Bearer token",
"certificateApiTokenHidden": "Unavailable (stored as a hash). Regenerate to obtain a new token.",
"certificateApiRevoke": "Revoke token",
- "certificateApiOneTimeToken": "Copy this token now",
+ "certificateApiOneTimeToken": "Copy the token now and store it in the automation (for example RUSTPROXY_TOKEN). It will not be shown again.",
"certificateApiCurlHelp": "External automation sends the Key ID header and Bearer token over HTTPS (or loopback HTTP). Reload tokens must use the targeted /api/certificates/{id}/reload endpoint; a token cannot call the global reload endpoint.",
"certificateApiUnknown": "Loading certificate API status…",
"certificateApiConfigured": "Certificate API enabled",
@@ -1961,16 +1960,15 @@
"vhWebsocketLegacyBadge": "WebSocket legacy",
"runtimeInformation": "Runtime information",
"runtimeInformationHelp": "Reported by the running RustProxy process and available only from the authenticated administrator status API.",
- "runtimePlatform": "Platform",
"statisticsSource": "Statistics source",
"dataDirectory": "Data directory",
"databaseLocation": "Database",
"connectionActivity": "Connection activity",
"reloadCertificate": "Reload certificate",
"certificateApiComment": "Comment",
- "certificateApiCertificateIds": "Allowed certificate IDs",
+ "certificateApiCertificateIds": "Allowed certificates",
"certificateApiCertificateIdsHelp": "One or more certificate IDs separated by commas or new lines. The token is rejected for every other certificate ID.",
- "certificateApiCertificateIdsRequired": "Enter at least one certificate ID for this token.",
+ "certificateApiCertificateIdsRequired": "Choose at least one certificate for this key.",
"certificateApiAllowDeploy": "Also allow deploy",
"certificateApiAllowDeployHelp": "Leave disabled for Certbot/acme.sh renewal hooks. Reload-only is the recommended least-privilege mode.",
"certificateApiScopeReloadOnly": "reload only",
@@ -1984,7 +1982,7 @@
"certificate_api.invalid_comment": "Certificate API comments must be at most 256 characters and contain no control characters.",
"certificate_api.limit_reached": "The Certificate API token limit has been reached.",
"certificate_api.not_found": "Certificate API token not found.",
- "certificate_api.invalid_certificate_ids": "Certificate API tokens require 1-32 valid certificate IDs.",
+ "certificate_api.invalid_certificate_ids": "Certificate API keys need 1-32 explicit certificate IDs (letters, digits, - and _); * is not allowed.",
"certificate_api.target_required": "Certificate API tokens cannot reload every certificate at once; use the targeted certificate reload endpoint.",
"certificate_api.certificate_forbidden": "This Certificate API token is not allowed to operate on that certificate ID.",
"certificate_api.deploy_forbidden": "This Certificate API token is reload-only. Rotate it with deploy permission only if upload/deploy automation is required.",
@@ -2287,7 +2285,6 @@
"runtimePython": "Python",
"runtimePip": "pip",
"runtimeCertbot": "Certbot",
- "runtimeAcmeMode": "ACME mode",
"runtimeAvailable": "Available",
"runtimeUnavailable": "Unavailable",
"vhPoolRecycleRequests": "Recycle upstream pool after requests (0 = off)",
@@ -2635,22 +2632,17 @@
"vhostInterceptOriginErrorsHelp": "Example: 404, 500, 502, 503, 504. For selected codes, RustProxy keeps the HTTP error status and returns the vhost/global custom error page, or a built-in one. Application content/cookies are removed; the replacement is no-store. Off by default. Internal named-location fallbacks take precedence. Applies to reverse proxy and Web Server (including PHP).",
"vhostInterceptOriginInvalid": "Select one or more unique supported HTTP codes: 400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504.",
"systemInformation": "System information",
- "systemInformationHelp": "Live, read-only information from the authenticated status API. Unavailable metrics are not estimated.",
- "systemHostHeading": "Operating system and hardware",
- "systemOsVersion": "Operating system",
+ "systemInformationHelp": "Read-only information from the authenticated system-info API. Unavailable metrics are not estimated; the charts keep a short history in this browser only.",
"systemKernel": "Kernel",
"systemArchitecture": "Architecture",
"systemLogicalCpus": "Logical CPUs",
- "systemCpuLoad": "CPU usage",
"systemProcessHeading": "RustProxy process",
"systemAppVersion": "RustProxy version",
"systemProcessUptime": "Process uptime",
"systemProcessMemory": "Process RAM (RSS)",
"systemProcessThreads": "Process threads",
"systemOpenFds": "Open file descriptors",
- "systemCertificateHeading": "ACME / Python environment",
- "systemCertificateHelp": "Versions are detected from the interpreter and tools actually selected for certificate management.",
- "systemAcmeStatus": "ACME status",
+ "systemCertificateHeading": "Certificate toolchain",
"systemPathsHeading": "Data locations",
"refreshSection": "REFRESH",
"refreshTitle": "Data refresh",
@@ -3033,20 +3025,18 @@
"certAssignVhosts": "Assign vhosts",
"certAssignHelp": "Select the vhosts to bind to this certificate. Unchecking an already bound vhost clears its assignment. Other certificates remain unchanged.",
"certAssignApply": "Save vhost assignments",
- "apiTokensMovedHelp": "API token management is now in Settings → Security.",
- "apiTokensOpenSecurity": "Open API tokens in Security",
"generalApiTokensTitle": "API tokens (RO/RW)",
- "generalApiTokensHelp": "Create separate tokens for external API clients. Each token is IP/CIDR restricted. Only approved operational API routes are available; browser credentials remain supported. Remote access requires HTTPS.",
+ "generalApiTokensHelp": "Tokens for external API clients (scripts, monitoring, CI). Each token is limited to its source addresses and to the approved API routes; it cannot manage tokens or sessions.",
"apiTokenComment": "Description",
"apiTokenPermission": "Permission",
"apiTokenReadOnly": "Read only (RO)",
"apiTokenReadWrite": "Read and write (RW)",
- "apiTokenIpAllow": "Allowed source IP/CIDR (one per line)",
+ "apiTokenIpAllow": "Allowed source addresses",
"apiTokenCreate": "Generate API token",
- "apiTokenCopyNow": "Copy this token now — it will not be shown again",
+ "apiTokenCopyNow": "Copy the token now and store it in the client (for example RUSTPROXY_API_TOKEN). It will not be shown again.",
"apiTokenLastUsed": "Last used",
"apiTokenRevoke": "Revoke token",
- "apiTokenEmpty": "No API tokens",
+ "apiTokenEmpty": "No API tokens yet. Create one with New token.",
"promTokenTitle": "Prometheus bearer token",
"promTokenHelp": "Generate a bearer token in the panel. Only its hash is stored. Rotation or revocation takes effect immediately. Set the token in the Prometheus credentials_file.",
"promTokenGenerate": "Generate / rotate token",
@@ -3209,7 +3199,7 @@
"dockerContainerStarted": "Started",
"dockerLabelIssue": "LABEL ERROR",
"dockerLabelPublish": "Publish from container labels",
- "dockerLabelPublishHelp": "Containers with rustproxy.enable=true are published automatically (rustproxy.host, .domain, .aliases, .scheme, .port, .force_ssl, .websockets, .cache, .compression, .preserve_host). Names must stay inside the agent domains; a manual setting always wins.",
+ "dockerLabelPublishHelp": "Containers with the label rustproxy.enable=true are published automatically. Names must stay inside the agent domains; a manual setting always wins.",
"dockerLabelPublished": "LABELS",
"dockerLabelPublishedHelp": "Published automatically from rustproxy.* container labels. Apply changes to take it over as a manual setting; switching Publish off stores a manual override.",
"dockerProvisionEnrolling": "Redeeming the one-time code at the agent…",
@@ -3223,6 +3213,293 @@
"dockerContainerUnhealthy": "unhealthy",
"dockerContainerHealthStarting": "health check starting",
"dockerContainerNoHealthcheck": "no health check",
- "dockerContainerNoHealthcheckHelp": "The image defines no HEALTHCHECK; only the container state is known. Add a healthcheck to the container to get health alerts."
+ "dockerContainerNoHealthcheckHelp": "The image defines no HEALTHCHECK; only the container state is known. Add a healthcheck to the container to get health alerts.",
+ "dockerTargetGroupRecommended": "Recommended (primary route / public / override)",
+ "dockerTargetGroupHost": "Other host interfaces",
+ "dockerTargetGroupBridge": "Container bridges (docker0, br-*, podman*)",
+ "dockerTargetBridgeHint": "Bridge address: reachable only when RustProxy runs on the same host as the agent.",
+ "dockerCertificateHintAutoMatched": "Certificate: automatic (SNI) → {id}",
+ "dockerCertificateHintAutoMissing": "No stored certificate covers {hosts}: the default certificate will be served and browsers will warn",
+ "dockerLabelHelpTitle": "Container labels (rustproxy.*)",
+ "dockerLabelHelpIntro": "With label publishing enabled, the agent reads rustproxy.* labels of running containers with published ports, and RustProxy creates the virtual host without manual setup. Unknown or invalid labels are reported next to the service.",
+ "dockerLabelHelpEnable": "Required. true/yes/1/on publishes the container.",
+ "dockerLabelHelpHost": "Host name: a short name (shop → shop.) or a full name inside the agent domains. Default: the service name.",
+ "dockerLabelHelpDomain": "One of the agent domains used for short names. Default: the master domain.",
+ "dockerLabelHelpAliases": "Extra names, separated by commas or spaces; short names use the selected domain.",
+ "dockerLabelHelpPort": "Container (private) port to publish when the container exposes several ports. The port must also be published (ports:).",
+ "dockerLabelHelpScheme": "Backend protocol: http (default) or https.",
+ "dockerLabelHelpForceSsl": "Redirect HTTP to HTTPS (true/false). Default: false.",
+ "dockerLabelHelpWebsockets": "Allow WebSocket upgrades. Default: true.",
+ "dockerLabelHelpCache": "Enable the response cache. Default: false.",
+ "dockerLabelHelpCompression": "Enable response compression. Default: the global setting.",
+ "dockerLabelHelpPreserveHost": "Send the original Host header to the backend. Default: true.",
+ "dockerLabelHelpExample": "Example: docker compose",
+ "dockerLabelHelpNote": "Labels are applied on the next agent poll. A service edited and applied in the panel becomes a manual setting and labels no longer change it; Podman uses the same labels.",
+ "certificateApiLegacyWildcard": "This key was migrated from an older version with access to all certificates (*). Choose the certificates it needs; * cannot be saved any more.",
+ "certificateApiWildcardNotAllowed": "* (all certificates) is no longer allowed. List the certificate IDs explicitly.",
+ "certificateApiCertificateIdInvalid": "Invalid certificate ID: {id}. Use 1-64 letters, digits, - or _.",
+ "certificateApiCertificateIdsTooMany": "A key can list at most 32 certificate IDs.",
+ "certificateApiNewKey": "New key",
+ "certificateApiNewTitle": "New Certificate API key",
+ "certificateApiEditTitle": "Edit key {key}",
+ "certificateApiCreate": "Create key and token",
+ "certificateApiEmpty": "No keys yet. Create one with New key.",
+ "certificateApiModeReload": "Reload only",
+ "certificateApiModeReloadHelp": "Recommended for Certbot / acme.sh hooks that write the PEM files themselves; the key can only ask RustProxy to reload the chosen certificates.",
+ "certificateApiModeDeploy": "Deploy and reload",
+ "certificateApiModeDeployHelp": "For automation that uploads the certificate and key (OPNsense ACME client script, CI). The key can create or replace the chosen manual certificates.",
+ "certificateApiCertificatesReloadHelp": "Choose the stored certificates this key may reload.",
+ "certificateApiCertificatesDeployHelp": "Choose stored certificates, or type a new ID and press Enter: a deploy creates it on first upload. Certificates managed by RustProxy ACME can only be reloaded.",
+ "certificateApiManagedWarning": "Deploy is refused for {ids} (managed by RustProxy ACME).",
+ "certificateApiManagedReloadOnly": "RustProxy ACME: reload only",
+ "certificateApiCertificateNew": "not stored yet: created by the first deploy",
+ "certificateApiPickerChoose": "Choose certificates",
+ "certificateApiPickerSelected": "Selected certificates: {count}",
+ "certificateApiPickerNone": "No certificate selected",
+ "certificateApiPickerSearch": "Search by ID or host name, or type a new ID",
+ "certificateApiPickerAddHint": "Press Enter to add ID {value}",
+ "certificateApiPickerEmpty": "No stored certificates. Type a new ID to allow deploying it.",
+ "certificateApiCustomToken": "Custom token (optional)",
+ "certificateApiSecretTitle": "Token for key {key}",
+ "certificateApiExampleTitle": "Usage example (curl)",
+ "certificateApiLegacyWildcardShort": "Legacy access to all certificates (*): edit the key to choose certificates.",
+ "invalidValue": "Invalid value",
+ "apiTokenNew": "New token",
+ "apiTokenNewTitle": "New API token",
+ "apiTokenReadOnlyHelp": "Read status, metrics and configuration sections through the allowed API routes.",
+ "apiTokenReadWriteHelp": "Also save configuration sections. Use only for trusted automation.",
+ "apiTokenIpAllowHelp": "IP address or CIDR of the client, Enter after each (a single IP becomes /32 or /128). Requests from other addresses are rejected; remote access requires HTTPS.",
+ "apiTokenCidrInvalid": "Enter an IP address or CIDR, for example 192.0.2.10 or 10.0.0.0/24.",
+ "apiTokenCidrLimit": "At most 32 addresses per token.",
+ "apiTokenCidrRequired": "Add at least one allowed source address.",
+ "apiTokenCount": "API tokens: {count} / {max}",
+ "apiTokenRevokeConfirm": "Revoke API token {id}? Clients using it stop working immediately.",
+ "apiTokenRevoked": "API token revoked.",
+ "apiTokenSecretTitle": "Token {id}",
+ "apiTokenCreated": "API token created. Copy it now.",
+ "restartPartialLabel": "LIVE + RESTART",
+ "restartFieldBadge": "restart",
+ "restartFieldHelp": "This setting takes effect after RustProxy is restarted.",
+ "prometheusEndpoint": "Endpoint",
+ "prometheusScrapeExample": "Prometheus scrape config",
+ "promTokenSecretTitle": "Prometheus token",
+ "promTokenCopyNow": "Copy the token now into the Prometheus credentials_file. It will not be shown again.",
+ "promTokenMissingShort": "No token",
+ "promTokenRevokeConfirm": "Revoke the Prometheus token? Scrapes using it fail immediately.",
+ "administrationAccessTitle": "Address and HTTPS",
+ "administrationSessionsTitle": "Sessions",
+ "countryPickerChoose": "Choose countries",
+ "countryPickerSelected": "Selected countries: {count}",
+ "countryPickerNone": "No country selected",
+ "countryPickerSearch": "Search by name or ISO code",
+ "countryPickerAddHint": "Press Enter to add {value}",
+ "countryPickerEmpty": "No countries",
+ "globalPolicyOff": "off",
+ "globalPolicyOn": "on",
+ "globalPolicyBlockMode": "block list",
+ "globalPolicyAllowMode": "allow list",
+ "globalPolicySummary": "Rule status",
+ "cancel": "Cancel",
+ "cacheTabRules": "Rules",
+ "cacheRulesHelp": "Conditional rules in the spirit of Varnish VCL: decide what is cached, how the cache key is built, how long objects live and which headers clients get. Request rules run before the cache lookup, response rules on a backend response, deliver rules on every response. Vhost rules (vhost editor → Cache) run before these global rules. Saved with Save cache settings.",
+ "vhCacheRulesTitle": "Cache rules for this vhost",
+ "vhCacheRulesHelp": "Run before the global rules from Settings → Cache → Rules. When both set the same thing (TTL, grace, pass, no store) the vhost rule wins.",
+ "cacheRulesTemplates": "Add from template…",
+ "cacheRulesImportVcl": "Import VCL",
+ "cacheRulesExportVcl": "Copy as VCL",
+ "cacheRulesAdd": "New rule",
+ "cacheRulesIgnoreGlobal": "Ignore global cache rules for this vhost",
+ "cacheRulesEmpty": "No cache rules yet. Add one or start from a template.",
+ "cacheRulesEmptyVhost": "No vhost-specific cache rules. Global rules still apply unless ignored.",
+ "cacheRulesImportHelp": "Paste VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Supported statements become rules; everything else is listed as a warning. Imported rules are added below and saved with the form.",
+ "cacheRulesImportRun": "Convert to rules",
+ "cacheRulesImportDone": "Imported {count} rules. Review them and save.",
+ "cacheRulesImportWarnings": "Not imported:",
+ "cacheRulesVclPreview": "VCL preview (read-only)",
+ "cacheRulesGlobalApply": "{count} global rules also apply to this vhost: {names}.",
+ "cacheRulesGlobalSkipped": "{count} global rules are ignored for this vhost.",
+ "cacheRulesOverrideNotice": "Vhost rule “{vhost}” takes precedence over global rule “{global}” for {aspects} when both match.",
+ "cacheRulesOverriddenIn": "Overridden by vhost rules in: {vhosts}",
+ "cacheRulesIgnoredIn": "Ignored in vhosts: {vhosts}",
+ "cacheRulesHits": "{count} matches",
+ "cacheRulesDrag": "Drag to reorder (rules run top to bottom)",
+ "cacheRulesMoveUp": "Move up",
+ "cacheRulesMoveDown": "Move down",
+ "cacheRulesDuplicate": "Duplicate",
+ "cacheRulesCopySuffix": "copy",
+ "cacheRulesLimit": "At most 128 rules.",
+ "cacheRulesTemplateAdded": "Added {count} rules from the template.",
+ "cacheRulesTester": "Test a request",
+ "cacheRulesTesterHelp": "Checks the rules shown above (including unsaved changes) against a sample request and backend response. Nothing is sent to backends and match counters do not change.",
+ "cacheRulesTesterUrl": "URL or path",
+ "cacheRulesTesterVhost": "Vhost",
+ "cacheRulesTesterNoVhost": "Global rules only",
+ "cacheRulesTesterHeaders": "Request headers (Name: value)",
+ "cacheRulesTesterResponseHeaders": "Backend response headers",
+ "cacheRulesTesterRun": "Test",
+ "cacheRulesTesterRunning": "Testing…",
+ "cacheRulesResultDecision": "Decision",
+ "cacheRulesResultHit": "Cached: TTL {ttl}, grace {grace}",
+ "cacheRulesResultNotStored": "Not stored ({reason})",
+ "cacheRulesResultPass": "Bypass ({reason})",
+ "cacheRulesResultRequest": "Request rules",
+ "cacheRulesResultResponse": "Response rules",
+ "cacheRulesResultDeliver": "Deliver headers",
+ "cacheRulesResultKey": "Cache key",
+ "cacheRulesResultCookie": "Cookie after rules",
+ "cacheRulesResultOverridden": "Overridden",
+ "cacheRulesResultOverriddenText": "{winner} wins over {ignored} ({aspect})",
+ "cacheRulesOriginVhost": "vhost",
+ "cacheRulesOriginGlobal": "global",
+ "cacheRuleNewName": "New rule",
+ "cacheRuleName": "Name",
+ "cacheRuleNamePlaceholder": "Bypass admin pages",
+ "cacheRuleId": "ID",
+ "cacheRuleIdInvalid": "The ID must be unique and use 1-64 letters, digits, - or _.",
+ "cacheRuleStage": "When",
+ "cacheRuleStageRequest": "request",
+ "cacheRuleStageResponse": "backend response",
+ "cacheRuleStageDeliver": "deliver",
+ "cacheRuleStageHelpRequest": "Before the cache lookup (vcl_recv / vcl_hash): bypass, cookies, query, cache key.",
+ "cacheRuleStageHelpResponse": "When the backend answers (vcl_backend_response): TTL, grace, store or not.",
+ "cacheRuleStageHelpDeliver": "Before sending any response to the client (vcl_deliver): headers.",
+ "cacheRuleMatch": "Conditions",
+ "cacheRuleMatchAll": "All must match",
+ "cacheRuleMatchAny": "Any can match",
+ "cacheRuleStop": "Stop evaluating later rules of this stage",
+ "cacheRuleVhosts": "Vhosts",
+ "cacheRuleVhostsHelp": "Leave empty to apply to all vhosts.",
+ "cacheRuleVhostsAll": "All vhosts",
+ "cacheRuleVhostsSelected": "Vhosts: {count}",
+ "cacheRuleVhostsNone": "—",
+ "cacheRuleVhostsEmpty": "No vhosts",
+ "cacheRuleConditions": "If",
+ "cacheRuleActions": "Then",
+ "cacheRuleNoConditions": "No conditions: the rule matches every request.",
+ "cacheRuleAddCondition": "Add condition",
+ "cacheRuleAddAction": "Add action",
+ "cacheRuleVcl": "VCL equivalent",
+ "cacheRuleField": "Field",
+ "cacheRuleOperator": "Operator",
+ "cacheRuleNegate": "not",
+ "cacheRuleNamePlaceholderField": "name",
+ "cacheRuleValuesPlaceholder": "values, comma separated",
+ "cacheRuleValuesPlaceholderStatus": "200, 4xx, 500-599",
+ "cacheRuleValuesPlaceholderCidr": "10.0.0.0/8, 192.0.2.10",
+ "cacheRuleValuesPlaceholderExtension": "css, js, png",
+ "cacheRuleValuesPlaceholderMethod": "GET, HEAD",
+ "cacheRuleFieldHost": "Host",
+ "cacheRuleFieldUrl": "URL (path + query)",
+ "cacheRuleFieldPath": "Path",
+ "cacheRuleFieldExtension": "File extension",
+ "cacheRuleFieldMethod": "Method",
+ "cacheRuleFieldQuery": "Query parameter",
+ "cacheRuleFieldHeader": "Request header",
+ "cacheRuleFieldCookie": "Cookie",
+ "cacheRuleFieldClientIp": "Client IP",
+ "cacheRuleFieldStatus": "Response status",
+ "cacheRuleFieldContentType": "Content-Type",
+ "cacheRuleFieldResponseHeader": "Response header",
+ "cacheRuleOpEquals": "is",
+ "cacheRuleOpPrefix": "starts with",
+ "cacheRuleOpSuffix": "ends with",
+ "cacheRuleOpContains": "contains",
+ "cacheRuleOpGlob": "matches pattern (*)",
+ "cacheRuleOpRegex": "matches regex",
+ "cacheRuleOpExists": "is present",
+ "cacheRuleOpCidr": "is in",
+ "cacheRuleAction": "Action",
+ "cacheRuleActionPass": "Bypass cache (pass)",
+ "cacheRuleActionStripCookies": "Remove cookies",
+ "cacheRuleActionStripQuery": "Remove query parameters",
+ "cacheRuleActionHashHeader": "Add header to cache key",
+ "cacheRuleActionHashCookie": "Add cookie to cache key",
+ "cacheRuleActionTtl": "Set TTL",
+ "cacheRuleActionGrace": "Set grace",
+ "cacheRuleActionNoStore": "Do not store",
+ "cacheRuleActionIgnoreCacheControl": "Ignore backend Cache-Control",
+ "cacheRuleActionStripSetCookie": "Remove Set-Cookie",
+ "cacheRuleActionSetHeader": "Set response header",
+ "cacheRuleActionRemoveHeader": "Remove response header",
+ "cacheRuleActionHelpPass": "The request goes straight to the backend; nothing is read from or written to the cache.",
+ "cacheRuleActionHelpNoStore": "The response is delivered but not cached.",
+ "cacheRuleActionHelpIgnoreCacheControl": "Caches even with no-cache, private or no-store from the backend (uses the TTL action or the default TTL). Responses with Set-Cookie still need Remove Set-Cookie.",
+ "cacheRuleActionHelpStripSetCookie": "Removes Set-Cookie from the backend response (stored and delivered), like unset beresp.http.Set-Cookie.",
+ "cacheRuleKeepCookies": "keep cookies (empty = remove all)",
+ "cacheRuleKeepOnly": "keep only these",
+ "cacheRuleQueryParams": "utm_*, fbclid (empty = all)",
+ "cacheRuleHeaderValue": "value",
+ "cacheRuleDurationUnit": "Unit",
+ "cacheRuleUnitS": "seconds",
+ "cacheRuleUnitM": "minutes",
+ "cacheRuleUnitH": "hours",
+ "cacheRuleUnitD": "days",
+ "cacheRuleAspectPass": "bypass",
+ "cacheRuleAspectTtl": "TTL",
+ "cacheRuleAspectGrace": "grace",
+ "cacheRuleAspectStore": "storing",
+ "cacheRuleNeedsAction": "Rule “{rule}” needs at least one action.",
+ "cacheRuleNeedsName": "Rule “{rule}”: enter the header, cookie or parameter name.",
+ "cacheRuleNeedsValue": "Rule “{rule}”: a condition has no value.",
+ "cacheRuleTplWordpress": "WordPress: bypass admin and logged-in users",
+ "cacheRuleTplStatic": "Static files: no cookies, 30 days",
+ "cacheRuleTplStaticCookies": "Static files: remove cookies",
+ "cacheRuleTplStaticTtl": "Static files: TTL 30 days",
+ "cacheRuleTplTracking": "Ignore tracking parameters (utm_*, fbclid, gclid)",
+ "cacheRuleTplApi": "API: bypass cache",
+ "cacheRuleTplLanguage": "Separate cache per language cookie",
+ "cacheRuleTplNotfound": "Short TTL for 404",
+ "cacheRuleTplNotFound": "Short TTL for 404",
+ "cacheRuleTplHeaders": "Hide X-Powered-By",
+ "cacheRulesDocs": "Cache rules documentation",
+ "certificateApiDocs": "Certificate API documentation",
+ "certificateApiOpnsenseDocs": "OPNsense ACME client integration",
+ "apiTokensDocs": "API tokens documentation",
+ "dockerLabelHelpDocs": "Container labels documentation",
+ "systemInfoCopyDiagnostics": "Copy diagnostics",
+ "systemInfoCopyFailed": "Could not copy to the clipboard.",
+ "systemInfoCopy": "Copy",
+ "systemInfoRam": "RAM",
+ "systemInfoSwap": "Swap",
+ "systemInfoProcessUptime": "RustProxy uptime",
+ "systemInfoSystemCpu": "System CPU",
+ "systemInfoProcessCpu": "RustProxy CPU",
+ "systemInfoCoreNote": "100% = 1 core",
+ "systemInfoCores": "{count} logical CPUs",
+ "systemInfoLoad": "Load average",
+ "systemInfoLoadUnavailable": "Not reported on this platform",
+ "systemInfoOf": "of",
+ "systemInfoProcessHeading": "RustProxy process",
+ "systemInfoResidentMemory": "Resident memory (RSS)",
+ "systemInfoHotCache": "HOT cache",
+ "systemInfoTransient": "Transient",
+ "systemInfoAnonymous": "Anonymous",
+ "systemInfoFileBacked": "File-backed",
+ "systemInfoBudgets": "Budgets",
+ "systemInfoHotLimit": "HOT cache / limit",
+ "systemInfoTransientLimit": "Transient / limit",
+ "systemInfoTransforms": "Transforms in flight / budget",
+ "systemInfoProcessDetails": "Process",
+ "systemInfoVirtual": "Virtual memory",
+ "systemInfoProcessSwap": "Swap",
+ "systemInfoDiskIo": "Disk read / written",
+ "systemInfoNoLimit": "No limit",
+ "systemInfoNone": "None",
+ "systemInfoNetworkHeading": "Network",
+ "systemInfoInterface": "Interface",
+ "systemInfoRxRate": "RX/s",
+ "systemInfoTxRate": "TX/s",
+ "systemInfoTotals": "RX / TX total",
+ "systemInfoNoInterfaces": "No active interfaces reported.",
+ "systemInfoIdleInterfaces": "Idle interfaces ({count})",
+ "systemInfoNetworkHistory": "RX / TX history",
+ "systemInfoEnvironment": "Environment",
+ "systemInfoLive": "LIVE",
+ "systemInfoManual": "MANUAL",
+ "systemInfoSampledAgo": "sampled {seconds} s ago",
+ "systemInfoSource": "Source",
+ "systemInfoFooter": "Read-only · unavailable metrics are not estimated",
+ "systemInfoDocs": "Documentation",
+ "systemInfoFdsNote": "limit {limit} · {count} OS threads"
}
}
diff --git a/langs/pl_pl.json b/langs/pl_pl.json
index ddafda3..91be312 100644
--- a/langs/pl_pl.json
+++ b/langs/pl_pl.json
@@ -25,7 +25,7 @@
"globalCountryTitle": "Dostęp według kraju",
"globalCountryHelp": "Blokuj wskazane kraje albo zezwalaj tylko na nie (dwuliterowe kody ISO 3166-1 alpha-2). W trybie zezwalania nierozpoznany kraj jest blokowany. Aktualizacje GeoIP ustawisz w Settings.",
"globalCountryMode": "Polityka krajów",
- "globalCountryList": "Kody krajów (każdy w nowym wierszu lub po przecinku)",
+ "globalCountryList": "Kraje",
"globalUaTitle": "Blokada User-Agent",
"globalUaEnabled": "Włącz globalną blokadę User-Agent",
"globalIpTitle": "Dostęp według IP / CIDR / DNS",
@@ -794,11 +794,11 @@
"cacheResidentLabel": "Pamięć cache",
"certificateFuture": "Dostawcy ACME: HTTP-01, Cloudflare, OVH i RFC2136. Odnawianie jest ręczne.",
"prometheusTitle": "Prometheus",
- "prometheusHelp": "Osobny endpoint metryk, niezależny od sesji administratora. Domyślnie wyłączony.",
+ "prometheusHelp": "Osobny endpoint HTTP tylko do odczytu dla Prometheusa, niezależny od panelu. Pola oznaczone RESTART działają po restarcie; pozostałe od razu.",
"prometheusEnable": "Włącz endpoint Prometheusa",
"prometheusListen": "IP i port eksportera",
"prometheusPath": "Ścieżka metryk",
- "prometheusCidrs": "Dozwolone adresy kolektora (CIDR, po jednym w wierszu)",
+ "prometheusCidrs": "Dozwolone adresy scraperów (IP lub CIDR)",
"prometheusTokenEnv": "Nazwa zmiennej środowiskowej z tokenem",
"prometheusTokenHelp": "Podaj nazwę zmiennej, nie sekret. Token musi mieć co najmniej 32 znaki. Zmiana adresu lub tokenu wymaga restartu.",
"prometheusCollectors": "Grupy metryk",
@@ -1022,7 +1022,7 @@
"administrationActiveHttps": "Aktywny panel HTTPS",
"administrationCertificate": "Certyfikat",
"administrationGeneratedCertificate": "Domyślny certyfikat wygenerowany przez aplikację",
- "administrationHelp": "HTTPS pozwala wystawić panel administracyjny poza loopback. Zwykły HTTP na porcie HTTPS jest automatycznie przekierowywany. Zmiany listenera i certyfikatu działają po restarcie.",
+ "administrationHelp": "HTTPS pozwala panelowi nasłuchiwać poza loopbackiem; zwykłe HTTP na porcie HTTPS jest przekierowywane. Pola oznaczone RESTART działają po restarcie.",
"administrationHosts": "Dodatkowe dozwolone hosty DNS",
"administrationHttps": "Włącz HTTPS dla panelu administracyjnego",
"administrationListen": "Adres nasłuchu",
@@ -1564,7 +1564,6 @@
"prometheusTrustedNoTokenHelp": "Klient nadal musi pasować do listy dozwolonych CIDR. Włączaj tylko w prywatnej, zaufanej sieci monitoringu; nagłówki przekazywane nie są używane do tej decyzji.",
"docker-vhosts": "Docker vhosty",
"docker-vhostsTitle": "Usługi Dockera pod nazwami.",
- "docker-vhostsDescription": "Wykrywaj opublikowane porty Docker i Podman i mapuj usługi na nazwy w domenach agenta, z aliasami, bez kopiowania obserwowanego stanu do SQLite.",
"dockerVhosts": "Docker vhosty",
"dockerVhostsIntro": "Opublikowane porty TCP wykryte przez skonfigurowanych agentów Docker/Podman. Przypisz każdej usłudze nazwę w jednej z domen agenta (jej domenie master), dodaj aliasy, wybierz IP hosta Docker oraz sprawdzaj i dostrajaj stan backendu każdej opublikowanej usługi.",
"dockerDiscovery": "WYKRYWANIE DOCKERA",
@@ -1923,27 +1922,27 @@
"cacheTabCold": "Cold cache",
"cacheTabDiagnostics": "Statyczne i diagnostyka",
"certificateApiTitle": "API certyfikatów",
- "certificateApiHelp": "Twórz osobne poświadczenia Key ID + Bearer Token dla automatyzacji certyfikatów. Nowe tokeny są domyślnie tylko do reload i są ograniczone do wskazanych ID certyfikatów. Włącz deploy tylko dla automatyzacji, która musi wysyłać materiał certyfikatu.",
+ "certificateApiHelp": "Klucze pozwalają zewnętrznej automatyzacji (Certbot, acme.sh, klient ACME w OPNsense) przeładowywać lub wgrywać certyfikaty. Klucz działa tylko dla wybranych certyfikatów i nie może czytać konfiguracji ani używać innych API administracyjnych.",
"certificateApiKeyId": "Key ID",
"certificateApiToken": "Bearer token (opcjonalna własna wartość)",
- "certificateApiTokenHelp": "Pozostaw pole puste, aby wygenerować silny token. Jawna wartość każdego tokenu jest pokazywana tylko raz; RustProxy zapisuje wyłącznie jego hash.",
+ "certificateApiTokenHelp": "Zostaw puste, aby wygenerować silny token (zalecane). Własny token musi mieć 32-128 znaków: litery, cyfry, '.', '_', '-' lub '~'. Token jest pokazywany tylko raz; RustProxy zapisuje wyłącznie jego hash.",
"certificateApiRotate": "Generuj / obróć token",
"certificateApiView": "Podgląd ustawień",
"certificateApiHide": "Ukryj ustawienia",
- "certificateApiEdit": "Edytuj ustawienia",
- "certificateApiSave": "Zapisz ustawienia",
+ "certificateApiEdit": "Edytuj",
+ "certificateApiSave": "Zapisz zmiany",
"certificateApiSaved": "Ustawienia API certyfikatów zapisane. Dotychczasowy token pozostał bez zmian.",
- "certificateApiCancelEdit": "Anuluj edycję",
- "certificateApiEditNote": "Możesz zmienić komentarz, uprawnienia i dozwolone ID certyfikatów bez zmiany tokenu. Key ID pozostaje bez zmian.",
+ "certificateApiCancelEdit": "Anuluj",
+ "certificateApiEditNote": "Token się nie zmienia. Nowy token wydasz przyciskiem Regeneruj token.",
"certificateApiRegenerate": "Regeneruj token",
"certificateApiRegenerateConfirm": "Regenerować token {key}? Poprzedni token natychmiast przestanie działać. Po regeneracji skopiuj nowy token.",
"certificateApiRegenerated": "Token zregenerowany. Skopiuj go teraz — poprzedni token został unieważniony.",
- "certificateApiCreatedAt": "Utworzony / ostatnio zmieniony",
+ "certificateApiCreatedAt": "utworzony",
"certificateApiPermissions": "Uprawnienia",
"certificateApiTokenLabel": "Bearer token",
"certificateApiTokenHidden": "Niedostępny (zapisany wyłącznie hash). Regeneruj, aby uzyskać nowy token.",
"certificateApiRevoke": "Unieważnij token",
- "certificateApiOneTimeToken": "Skopiuj ten token teraz",
+ "certificateApiOneTimeToken": "Skopiuj token teraz i zapisz go w automatyzacji (np. RUSTPROXY_TOKEN). Nie zostanie pokazany ponownie.",
"certificateApiCurlHelp": "Automatyzacja zewnętrzna wysyła Key ID i Bearer Token przez HTTPS (lub HTTP po loopback). Token reload musi używać /api/certificates/{id}/reload; token API nie może wywołać globalnego reload wszystkich certyfikatów.",
"certificateApiUnknown": "Ładowanie statusu API certyfikatów…",
"certificateApiConfigured": "API certyfikatów włączone",
@@ -1961,16 +1960,15 @@
"vhWebsocketLegacyBadge": "WebSocket legacy",
"runtimeInformation": "Informacje środowiska",
"runtimeInformationHelp": "Wartości raportuje uruchomiony proces RustProxy. Są dostępne tylko w uwierzytelnionym API administratora.",
- "runtimePlatform": "Platforma",
"statisticsSource": "Źródło statystyk",
"dataDirectory": "Katalog danych",
"databaseLocation": "Baza danych",
"connectionActivity": "Aktywność połączeń",
"reloadCertificate": "Przeładuj certyfikat",
"certificateApiComment": "Komentarz",
- "certificateApiCertificateIds": "Dozwolone ID certyfikatów",
+ "certificateApiCertificateIds": "Dozwolone certyfikaty",
"certificateApiCertificateIdsHelp": "Podaj jedno lub więcej ID certyfikatów oddzielonych przecinkiem lub nową linią. Dla każdego innego ID token zostanie odrzucony.",
- "certificateApiCertificateIdsRequired": "Podaj co najmniej jedno ID certyfikatu dla tego tokenu.",
+ "certificateApiCertificateIdsRequired": "Wybierz co najmniej jeden certyfikat dla tego klucza.",
"certificateApiAllowDeploy": "Zezwól także na deploy",
"certificateApiAllowDeployHelp": "Dla hooka odnowienia Certbot/acme.sh pozostaw wyłączone. Tryb tylko reload jest zalecanym wariantem least-privilege.",
"certificateApiScopeReloadOnly": "tylko reload",
@@ -1984,7 +1982,7 @@
"certificate_api.invalid_comment": "Komentarz tokenu API certyfikatów może mieć maksymalnie 256 znaków i nie może zawierać znaków sterujących.",
"certificate_api.limit_reached": "Osiągnięto limit tokenów API certyfikatów.",
"certificate_api.not_found": "Nie znaleziono tokenu API certyfikatów.",
- "certificate_api.invalid_certificate_ids": "Token API certyfikatów wymaga 1-32 poprawnych ID certyfikatów.",
+ "certificate_api.invalid_certificate_ids": "Klucz API certyfikatów wymaga 1-32 jawnych ID certyfikatów (litery, cyfry, - i _); * nie jest dozwolone.",
"certificate_api.target_required": "Token API certyfikatów nie może przeładować wszystkich certyfikatów naraz; użyj endpointu reload dla konkretnego ID.",
"certificate_api.certificate_forbidden": "Ten token API certyfikatów nie ma dostępu do wskazanego ID certyfikatu.",
"certificate_api.deploy_forbidden": "Ten token API certyfikatów ma tylko uprawnienie reload. Włącz deploy przy rotacji wyłącznie, jeśli automatyzacja musi wysyłać certyfikat.",
@@ -2287,7 +2285,6 @@
"runtimePython": "Python",
"runtimePip": "pip",
"runtimeCertbot": "Certbot",
- "runtimeAcmeMode": "Tryb ACME",
"runtimeAvailable": "Dostępny",
"runtimeUnavailable": "Niedostępny",
"vhPoolRecycleRequests": "Odśwież pulę upstream po liczbie żądań (0 = wył.)",
@@ -2635,22 +2632,17 @@
"vhostInterceptOriginErrorsHelp": "Przykład: 404, 500, 502, 503, 504. Dla wybranych kodów RustProxy zachowa kod błędu, ale wyświetli stronę skonfigurowaną dla vhosta/globalnie albo wbudowaną. Treść i ciasteczka aplikacji zostaną usunięte, a odpowiedź otrzyma no-store. Domyślnie wyłączone. Wewnętrzne lokalizacje błędów mają pierwszeństwo. Działa dla Reverse Proxy i Web Server (także PHP).",
"vhostInterceptOriginInvalid": "Podaj co najmniej jeden unikalny obsługiwany kod HTTP: 400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504.",
"systemInformation": "Informacje o systemie",
- "systemInformationHelp": "Bieżące dane tylko do odczytu z uwierzytelnionego API statusu. Brakujących wartości nie szacujemy.",
- "systemHostHeading": "System operacyjny i sprzęt",
- "systemOsVersion": "System operacyjny",
+ "systemInformationHelp": "Dane tylko do odczytu z uwierzytelnionego API system-info. Brakujących wartości nie szacujemy; wykresy trzymają krótką historię wyłącznie w tej przeglądarce.",
"systemKernel": "Jądro systemu",
"systemArchitecture": "Architektura",
"systemLogicalCpus": "Procesory logiczne",
- "systemCpuLoad": "Użycie CPU",
"systemProcessHeading": "Proces RustProxy",
"systemAppVersion": "Wersja RustProxy",
"systemProcessUptime": "Czas pracy procesu",
"systemProcessMemory": "Pamięć procesu (RSS)",
"systemProcessThreads": "Wątki procesu",
"systemOpenFds": "Otwarte deskryptory plików",
- "systemCertificateHeading": "Środowisko ACME / Python",
- "systemCertificateHelp": "Wersje są odczytywane z interpretera i narzędzi rzeczywiście używanych do obsługi certyfikatów.",
- "systemAcmeStatus": "Stan ACME",
+ "systemCertificateHeading": "Narzędzia certyfikatów",
"systemPathsHeading": "Ścieżki danych",
"refreshSection": "ODŚWIEŻANIE",
"refreshTitle": "Odświeżanie danych",
@@ -3033,20 +3025,18 @@
"certAssignVhosts": "Przypisz vhosty",
"certAssignHelp": "Wybierz vhosty dla tego certyfikatu. Odznaczenie wcześniej przypisanego vhosta usuwa jego przypisanie. Inne certyfikaty pozostają bez zmian.",
"certAssignApply": "Zapisz przypisania vhostów",
- "apiTokensMovedHelp": "Zarządzanie tokenami API przeniesiono do Ustawienia → Bezpieczeństwo.",
- "apiTokensOpenSecurity": "Przejdź do tokenów API w Bezpieczeństwie",
"generalApiTokensTitle": "Tokeny API (RO/RW)",
- "generalApiTokensHelp": "Oddzielne tokeny do obsługi API z zewnątrz. Każdy token ma listę dozwolonych IP/CIDR. Dostępne są tylko wybrane operacje API; logowanie administratora działa nadal. Zdalny dostęp wymaga HTTPS.",
+ "generalApiTokensHelp": "Tokeny dla zewnętrznych klientów API (skrypty, monitoring, CI). Każdy token jest ograniczony do swoich adresów źródłowych i dozwolonych ścieżek API; nie może zarządzać tokenami ani sesjami.",
"apiTokenComment": "Opis",
"apiTokenPermission": "Uprawnienia",
"apiTokenReadOnly": "Tylko odczyt (RO)",
"apiTokenReadWrite": "Odczyt i zapis (RW)",
- "apiTokenIpAllow": "Dozwolone adresy IP/CIDR (po jednym w linii)",
+ "apiTokenIpAllow": "Dozwolone adresy źródłowe",
"apiTokenCreate": "Wygeneruj token API",
- "apiTokenCopyNow": "Skopiuj token teraz — nie zostanie pokazany ponownie",
+ "apiTokenCopyNow": "Skopiuj token teraz i zapisz go w kliencie (np. RUSTPROXY_API_TOKEN). Nie zostanie pokazany ponownie.",
"apiTokenLastUsed": "Ostatnie użycie",
"apiTokenRevoke": "Unieważnij token",
- "apiTokenEmpty": "Brak tokenów API",
+ "apiTokenEmpty": "Brak tokenów API. Utwórz pierwszy przyciskiem Nowy token.",
"promTokenTitle": "Token Bearer Prometheusa",
"promTokenHelp": "Generuj token w panelu. Przechowywany jest tylko jego skrót. Odnowienie lub usunięcie działa natychmiast. Umieść token w pliku credentials_file Prometheusa.",
"promTokenGenerate": "Generuj / odnów token",
@@ -3209,7 +3199,7 @@
"dockerContainerStarted": "Uruchomiony",
"dockerLabelIssue": "BŁĄD ETYKIET",
"dockerLabelPublish": "Publikuj z etykiet kontenerów",
- "dockerLabelPublishHelp": "Kontenery z rustproxy.enable=true są publikowane automatycznie (rustproxy.host, .domain, .aliases, .scheme, .port, .force_ssl, .websockets, .cache, .compression, .preserve_host). Nazwy muszą należeć do domen agenta; ręczne ustawienie zawsze ma pierwszeństwo.",
+ "dockerLabelPublishHelp": "Kontenery z etykietą rustproxy.enable=true są publikowane automatycznie. Nazwy muszą należeć do domen agenta; ręczne ustawienie zawsze ma pierwszeństwo.",
"dockerLabelPublished": "ETYKIETY",
"dockerLabelPublishedHelp": "Opublikowane automatycznie z etykiet rustproxy.* kontenera. Zastosuj zmiany, aby przejąć je jako ręczne ustawienie; wyłączenie Publikuj zapisuje ręczne nadpisanie.",
"dockerProvisionEnrolling": "Realizuję jednorazowy kod u agenta…",
@@ -3223,6 +3213,293 @@
"dockerContainerUnhealthy": "niezdrowy",
"dockerContainerHealthStarting": "healthcheck startuje",
"dockerContainerNoHealthcheck": "brak healthchecka",
- "dockerContainerNoHealthcheckHelp": "Obraz nie definiuje HEALTHCHECK; znany jest tylko stan kontenera. Dodaj healthcheck do kontenera, aby dostawać alerty o jego zdrowiu."
+ "dockerContainerNoHealthcheckHelp": "Obraz nie definiuje HEALTHCHECK; znany jest tylko stan kontenera. Dodaj healthcheck do kontenera, aby dostawać alerty o jego zdrowiu.",
+ "dockerTargetGroupRecommended": "Zalecane (trasa główna / publiczny / nadpisany)",
+ "dockerTargetGroupHost": "Inne interfejsy hosta",
+ "dockerTargetGroupBridge": "Mosty kontenerów (docker0, br-*, podman*)",
+ "dockerTargetBridgeHint": "Adres mostu: osiągalny tylko, gdy RustProxy działa na tym samym hoście co agent.",
+ "dockerCertificateHintAutoMatched": "Certyfikat: automatycznie (SNI) → {id}",
+ "dockerCertificateHintAutoMissing": "Żaden zapisany certyfikat nie obejmuje {hosts}: zostanie podany certyfikat domyślny, a przeglądarki pokażą ostrzeżenie",
+ "dockerLabelHelpTitle": "Etykiety kontenerów (rustproxy.*)",
+ "dockerLabelHelpIntro": "Po włączeniu publikacji z etykiet agent odczytuje etykiety rustproxy.* uruchomionych kontenerów z opublikowanymi portami, a RustProxy tworzy virtual host bez ręcznej konfiguracji. Nieznane lub błędne etykiety są zgłaszane przy usłudze.",
+ "dockerLabelHelpEnable": "Wymagana. true/yes/1/on publikuje kontener.",
+ "dockerLabelHelpHost": "Nazwa hosta: krótka (shop → shop.) albo pełna w domenach agenta. Domyślnie: nazwa usługi.",
+ "dockerLabelHelpDomain": "Jedna z domen agenta dla krótkich nazw. Domyślnie: domena główna.",
+ "dockerLabelHelpAliases": "Dodatkowe nazwy rozdzielone przecinkami lub spacjami; krótkie nazwy używają wybranej domeny.",
+ "dockerLabelHelpPort": "Port kontenera (prywatny) do publikacji, gdy kontener wystawia kilka portów. Port musi być też opublikowany (ports:).",
+ "dockerLabelHelpScheme": "Protokół backendu: http (domyślnie) lub https.",
+ "dockerLabelHelpForceSsl": "Przekierowanie HTTP na HTTPS (true/false). Domyślnie: false.",
+ "dockerLabelHelpWebsockets": "Zezwala na WebSocket. Domyślnie: true.",
+ "dockerLabelHelpCache": "Włącza cache odpowiedzi. Domyślnie: false.",
+ "dockerLabelHelpCompression": "Włącza kompresję odpowiedzi. Domyślnie: ustawienie globalne.",
+ "dockerLabelHelpPreserveHost": "Przekazuje oryginalny nagłówek Host do backendu. Domyślnie: true.",
+ "dockerLabelHelpExample": "Przykład: docker compose",
+ "dockerLabelHelpNote": "Etykiety są stosowane przy następnym odpytaniu agenta. Usługa edytowana i zastosowana w panelu staje się ustawieniem ręcznym i etykiety jej już nie zmieniają; Podman używa tych samych etykiet.",
+ "certificateApiLegacyWildcard": "Ten klucz został zmigrowany ze starszej wersji z dostępem do wszystkich certyfikatów (*). Wybierz potrzebne certyfikaty; * nie da się już zapisać.",
+ "certificateApiWildcardNotAllowed": "* (wszystkie certyfikaty) nie jest już dozwolone. Wpisz ID certyfikatów jawnie.",
+ "certificateApiCertificateIdInvalid": "Niepoprawne ID certyfikatu: {id}. Użyj 1-64 liter, cyfr, - lub _.",
+ "certificateApiCertificateIdsTooMany": "Klucz może mieć najwyżej 32 ID certyfikatów.",
+ "certificateApiNewKey": "Nowy klucz",
+ "certificateApiNewTitle": "Nowy klucz Certificate API",
+ "certificateApiEditTitle": "Edycja klucza {key}",
+ "certificateApiCreate": "Utwórz klucz i token",
+ "certificateApiEmpty": "Brak kluczy. Utwórz pierwszy przyciskiem Nowy klucz.",
+ "certificateApiModeReload": "Tylko przeładowanie",
+ "certificateApiModeReloadHelp": "Zalecane dla hooków Certbot / acme.sh, które same zapisują pliki PEM; klucz może tylko poprosić RustProxy o przeładowanie wybranych certyfikatów.",
+ "certificateApiModeDeploy": "Wgrywanie i przeładowanie",
+ "certificateApiModeDeployHelp": "Dla automatyzacji, która wysyła certyfikat i klucz (skrypt klienta ACME w OPNsense, CI). Klucz może tworzyć i podmieniać wybrane certyfikaty ręczne.",
+ "certificateApiCertificatesReloadHelp": "Wybierz zapisane certyfikaty, które ten klucz może przeładowywać.",
+ "certificateApiCertificatesDeployHelp": "Wybierz zapisane certyfikaty albo wpisz nowe ID i naciśnij Enter: deploy utworzy go przy pierwszym wgraniu. Certyfikaty zarządzane przez ACME RustProxy można tylko przeładować.",
+ "certificateApiManagedWarning": "Deploy zostanie odrzucony dla {ids} (zarządzane przez ACME RustProxy).",
+ "certificateApiManagedReloadOnly": "ACME RustProxy: tylko przeładowanie",
+ "certificateApiCertificateNew": "jeszcze nie zapisany: utworzy go pierwszy deploy",
+ "certificateApiPickerChoose": "Wybierz certyfikaty",
+ "certificateApiPickerSelected": "Wybrane certyfikaty: {count}",
+ "certificateApiPickerNone": "Nie wybrano certyfikatu",
+ "certificateApiPickerSearch": "Szukaj po ID lub nazwie hosta albo wpisz nowe ID",
+ "certificateApiPickerAddHint": "Naciśnij Enter, aby dodać ID {value}",
+ "certificateApiPickerEmpty": "Brak zapisanych certyfikatów. Wpisz nowe ID, aby pozwolić na jego wgranie.",
+ "certificateApiCustomToken": "Własny token (opcjonalnie)",
+ "certificateApiSecretTitle": "Token dla klucza {key}",
+ "certificateApiExampleTitle": "Przykład użycia (curl)",
+ "certificateApiLegacyWildcardShort": "Stary dostęp do wszystkich certyfikatów (*): edytuj klucz i wybierz certyfikaty.",
+ "invalidValue": "Niepoprawna wartość",
+ "apiTokenNew": "Nowy token",
+ "apiTokenNewTitle": "Nowy token API",
+ "apiTokenReadOnlyHelp": "Odczyt stanu, metryk i sekcji konfiguracji przez dozwolone ścieżki API.",
+ "apiTokenReadWriteHelp": "Także zapis sekcji konfiguracji. Tylko dla zaufanej automatyzacji.",
+ "apiTokenIpAllowHelp": "Adres IP lub CIDR klienta, Enter po każdym (pojedynczy IP staje się /32 lub /128). Żądania z innych adresów są odrzucane; dostęp zdalny wymaga HTTPS.",
+ "apiTokenCidrInvalid": "Podaj adres IP lub CIDR, np. 192.0.2.10 albo 10.0.0.0/24.",
+ "apiTokenCidrLimit": "Najwyżej 32 adresy na token.",
+ "apiTokenCidrRequired": "Dodaj co najmniej jeden dozwolony adres źródłowy.",
+ "apiTokenCount": "Tokeny API: {count} / {max}",
+ "apiTokenRevokeConfirm": "Unieważnić token API {id}? Klienci, którzy go używają, natychmiast przestaną działać.",
+ "apiTokenRevoked": "Token API unieważniony.",
+ "apiTokenSecretTitle": "Token {id}",
+ "apiTokenCreated": "Token API utworzony. Skopiuj go teraz.",
+ "restartPartialLabel": "NA ŻYWO + RESTART",
+ "restartFieldBadge": "restart",
+ "restartFieldHelp": "To ustawienie zadziała po restarcie RustProxy.",
+ "prometheusEndpoint": "Endpoint",
+ "prometheusScrapeExample": "Konfiguracja scrape dla Prometheusa",
+ "promTokenSecretTitle": "Token Prometheusa",
+ "promTokenCopyNow": "Skopiuj token teraz do credentials_file Prometheusa. Nie zostanie pokazany ponownie.",
+ "promTokenMissingShort": "Brak tokenu",
+ "promTokenRevokeConfirm": "Unieważnić token Prometheusa? Scrape z jego użyciem natychmiast przestanie działać.",
+ "administrationAccessTitle": "Adres i HTTPS",
+ "administrationSessionsTitle": "Sesje",
+ "countryPickerChoose": "Wybierz kraje",
+ "countryPickerSelected": "Wybrane kraje: {count}",
+ "countryPickerNone": "Nie wybrano kraju",
+ "countryPickerSearch": "Szukaj po nazwie lub kodzie ISO",
+ "countryPickerAddHint": "Naciśnij Enter, aby dodać {value}",
+ "countryPickerEmpty": "Brak krajów",
+ "globalPolicyOff": "wyłączone",
+ "globalPolicyOn": "włączone",
+ "globalPolicyBlockMode": "blokowanie listy",
+ "globalPolicyAllowMode": "tylko lista",
+ "globalPolicySummary": "Stan reguł",
+ "cancel": "Anuluj",
+ "cacheTabRules": "Reguły",
+ "cacheRulesHelp": "Reguły warunkowe w duchu VCL Varnisha: decydują, co trafia do cache, jak budowany jest klucz, jak długo obiekt żyje i jakie nagłówki dostaje klient. Reguły żądania działają przed wyszukaniem w cache, reguły odpowiedzi na odpowiedzi backendu, reguły wysyłki na każdej odpowiedzi. Reguły vhosta (edytor vhosta → Cache) działają przed tymi globalnymi. Zapisywane przyciskiem zapisu ustawień cache.",
+ "vhCacheRulesTitle": "Reguły cache tego vhosta",
+ "vhCacheRulesHelp": "Działają przed regułami globalnymi z Ustawienia → Cache → Reguły. Gdy obie ustawiają to samo (TTL, grace, pominięcie cache, brak zapisu), wygrywa reguła vhosta.",
+ "cacheRulesTemplates": "Dodaj z szablonu…",
+ "cacheRulesImportVcl": "Import VCL",
+ "cacheRulesExportVcl": "Kopiuj jako VCL",
+ "cacheRulesAdd": "Nowa reguła",
+ "cacheRulesIgnoreGlobal": "Ignoruj globalne reguły cache w tym vhoście",
+ "cacheRulesEmpty": "Brak reguł cache. Dodaj regułę albo zacznij od szablonu.",
+ "cacheRulesEmptyVhost": "Brak reguł cache dla tego vhosta. Reguły globalne nadal działają, chyba że je zignorujesz.",
+ "cacheRulesImportHelp": "Wklej VCL (vcl_recv, vcl_hash, vcl_backend_response, vcl_deliver). Obsługiwane instrukcje staną się regułami, resztę wypiszemy jako ostrzeżenia. Zaimportowane reguły zostaną dodane poniżej i zapisane z formularzem.",
+ "cacheRulesImportRun": "Zamień na reguły",
+ "cacheRulesImportDone": "Zaimportowano reguł: {count}. Sprawdź je i zapisz.",
+ "cacheRulesImportWarnings": "Nie zaimportowano:",
+ "cacheRulesVclPreview": "Podgląd VCL (tylko do odczytu)",
+ "cacheRulesGlobalApply": "W tym vhoście działają też reguły globalne ({count}): {names}.",
+ "cacheRulesGlobalSkipped": "Reguły globalne ({count}) są w tym vhoście ignorowane.",
+ "cacheRulesOverrideNotice": "Reguła vhosta „{vhost}” ma pierwszeństwo przed regułą globalną „{global}” ({aspects}), gdy obie pasują.",
+ "cacheRulesOverriddenIn": "Nadpisywana przez reguły vhostów: {vhosts}",
+ "cacheRulesIgnoredIn": "Ignorowana w vhostach: {vhosts}",
+ "cacheRulesHits": "trafień: {count}",
+ "cacheRulesDrag": "Przeciągnij, aby zmienić kolejność (reguły działają od góry)",
+ "cacheRulesMoveUp": "W górę",
+ "cacheRulesMoveDown": "W dół",
+ "cacheRulesDuplicate": "Duplikuj",
+ "cacheRulesCopySuffix": "kopia",
+ "cacheRulesLimit": "Najwyżej 128 reguł.",
+ "cacheRulesTemplateAdded": "Dodano reguł z szablonu: {count}.",
+ "cacheRulesTester": "Testuj żądanie",
+ "cacheRulesTesterHelp": "Sprawdza powyższe reguły (także niezapisane zmiany) na przykładowym żądaniu i odpowiedzi backendu. Nic nie jest wysyłane do backendów, a liczniki trafień się nie zmieniają.",
+ "cacheRulesTesterUrl": "URL lub ścieżka",
+ "cacheRulesTesterVhost": "Vhost",
+ "cacheRulesTesterNoVhost": "Tylko reguły globalne",
+ "cacheRulesTesterHeaders": "Nagłówki żądania (Nazwa: wartość)",
+ "cacheRulesTesterResponseHeaders": "Nagłówki odpowiedzi backendu",
+ "cacheRulesTesterRun": "Testuj",
+ "cacheRulesTesterRunning": "Testowanie…",
+ "cacheRulesResultDecision": "Decyzja",
+ "cacheRulesResultHit": "Zapisane w cache: TTL {ttl}, grace {grace}",
+ "cacheRulesResultNotStored": "Nie zapisane ({reason})",
+ "cacheRulesResultPass": "Pominięcie cache ({reason})",
+ "cacheRulesResultRequest": "Reguły żądania",
+ "cacheRulesResultResponse": "Reguły odpowiedzi",
+ "cacheRulesResultDeliver": "Nagłówki wysyłki",
+ "cacheRulesResultKey": "Klucz cache",
+ "cacheRulesResultCookie": "Ciasteczka po regułach",
+ "cacheRulesResultOverridden": "Nadpisane",
+ "cacheRulesResultOverriddenText": "{winner} wygrywa z {ignored} ({aspect})",
+ "cacheRulesOriginVhost": "vhost",
+ "cacheRulesOriginGlobal": "globalna",
+ "cacheRuleNewName": "Nowa reguła",
+ "cacheRuleName": "Nazwa",
+ "cacheRuleNamePlaceholder": "Pomiń panel administracyjny",
+ "cacheRuleId": "ID",
+ "cacheRuleIdInvalid": "ID musi być unikalne i mieć 1-64 liter, cyfr, - lub _.",
+ "cacheRuleStage": "Kiedy",
+ "cacheRuleStageRequest": "żądanie",
+ "cacheRuleStageResponse": "odpowiedź backendu",
+ "cacheRuleStageDeliver": "wysyłka",
+ "cacheRuleStageHelpRequest": "Przed wyszukaniem w cache (vcl_recv / vcl_hash): pominięcie, ciasteczka, parametry, klucz cache.",
+ "cacheRuleStageHelpResponse": "Gdy odpowie backend (vcl_backend_response): TTL, grace, zapisywać czy nie.",
+ "cacheRuleStageHelpDeliver": "Przed wysłaniem każdej odpowiedzi do klienta (vcl_deliver): nagłówki.",
+ "cacheRuleMatch": "Warunki",
+ "cacheRuleMatchAll": "Wszystkie muszą pasować",
+ "cacheRuleMatchAny": "Wystarczy dowolny",
+ "cacheRuleStop": "Nie sprawdzaj kolejnych reguł tego etapu",
+ "cacheRuleVhosts": "Vhosty",
+ "cacheRuleVhostsHelp": "Puste = wszystkie vhosty.",
+ "cacheRuleVhostsAll": "Wszystkie vhosty",
+ "cacheRuleVhostsSelected": "Vhosty: {count}",
+ "cacheRuleVhostsNone": "—",
+ "cacheRuleVhostsEmpty": "Brak vhostów",
+ "cacheRuleConditions": "Jeśli",
+ "cacheRuleActions": "Wtedy",
+ "cacheRuleNoConditions": "Bez warunków: reguła pasuje do każdego żądania.",
+ "cacheRuleAddCondition": "Dodaj warunek",
+ "cacheRuleAddAction": "Dodaj akcję",
+ "cacheRuleVcl": "Odpowiednik w VCL",
+ "cacheRuleField": "Pole",
+ "cacheRuleOperator": "Operator",
+ "cacheRuleNegate": "nie",
+ "cacheRuleNamePlaceholderField": "nazwa",
+ "cacheRuleValuesPlaceholder": "wartości, po przecinku",
+ "cacheRuleValuesPlaceholderStatus": "200, 4xx, 500-599",
+ "cacheRuleValuesPlaceholderCidr": "10.0.0.0/8, 192.0.2.10",
+ "cacheRuleValuesPlaceholderExtension": "css, js, png",
+ "cacheRuleValuesPlaceholderMethod": "GET, HEAD",
+ "cacheRuleFieldHost": "Host",
+ "cacheRuleFieldUrl": "URL (ścieżka + zapytanie)",
+ "cacheRuleFieldPath": "Ścieżka",
+ "cacheRuleFieldExtension": "Rozszerzenie pliku",
+ "cacheRuleFieldMethod": "Metoda",
+ "cacheRuleFieldQuery": "Parametr zapytania",
+ "cacheRuleFieldHeader": "Nagłówek żądania",
+ "cacheRuleFieldCookie": "Ciasteczko",
+ "cacheRuleFieldClientIp": "IP klienta",
+ "cacheRuleFieldStatus": "Status odpowiedzi",
+ "cacheRuleFieldContentType": "Content-Type",
+ "cacheRuleFieldResponseHeader": "Nagłówek odpowiedzi",
+ "cacheRuleOpEquals": "jest",
+ "cacheRuleOpPrefix": "zaczyna się od",
+ "cacheRuleOpSuffix": "kończy się na",
+ "cacheRuleOpContains": "zawiera",
+ "cacheRuleOpGlob": "pasuje do wzorca (*)",
+ "cacheRuleOpRegex": "pasuje do regex",
+ "cacheRuleOpExists": "występuje",
+ "cacheRuleOpCidr": "należy do",
+ "cacheRuleAction": "Akcja",
+ "cacheRuleActionPass": "Pomiń cache (pass)",
+ "cacheRuleActionStripCookies": "Usuń ciasteczka",
+ "cacheRuleActionStripQuery": "Usuń parametry zapytania",
+ "cacheRuleActionHashHeader": "Dodaj nagłówek do klucza",
+ "cacheRuleActionHashCookie": "Dodaj ciasteczko do klucza",
+ "cacheRuleActionTtl": "Ustaw TTL",
+ "cacheRuleActionGrace": "Ustaw grace",
+ "cacheRuleActionNoStore": "Nie zapisuj",
+ "cacheRuleActionIgnoreCacheControl": "Ignoruj Cache-Control backendu",
+ "cacheRuleActionStripSetCookie": "Usuń Set-Cookie",
+ "cacheRuleActionSetHeader": "Ustaw nagłówek odpowiedzi",
+ "cacheRuleActionRemoveHeader": "Usuń nagłówek odpowiedzi",
+ "cacheRuleActionHelpPass": "Żądanie idzie prosto do backendu; nic nie jest czytane z cache ani do niego zapisywane.",
+ "cacheRuleActionHelpNoStore": "Odpowiedź jest wysyłana, ale nie trafia do cache.",
+ "cacheRuleActionHelpIgnoreCacheControl": "Zapisuje mimo no-cache, private lub no-store z backendu (TTL z akcji TTL albo domyślny). Odpowiedzi z Set-Cookie wymagają też Usuń Set-Cookie.",
+ "cacheRuleActionHelpStripSetCookie": "Usuwa Set-Cookie z odpowiedzi backendu (zapisywanej i wysyłanej), jak unset beresp.http.Set-Cookie.",
+ "cacheRuleKeepCookies": "zostaw ciasteczka (puste = usuń wszystkie)",
+ "cacheRuleKeepOnly": "zostaw tylko te",
+ "cacheRuleQueryParams": "utm_*, fbclid (puste = wszystkie)",
+ "cacheRuleHeaderValue": "wartość",
+ "cacheRuleDurationUnit": "Jednostka",
+ "cacheRuleUnitS": "sekundy",
+ "cacheRuleUnitM": "minuty",
+ "cacheRuleUnitH": "godziny",
+ "cacheRuleUnitD": "dni",
+ "cacheRuleAspectPass": "pominięcie cache",
+ "cacheRuleAspectTtl": "TTL",
+ "cacheRuleAspectGrace": "grace",
+ "cacheRuleAspectStore": "zapis",
+ "cacheRuleNeedsAction": "Reguła „{rule}” potrzebuje co najmniej jednej akcji.",
+ "cacheRuleNeedsName": "Reguła „{rule}”: podaj nazwę nagłówka, ciasteczka lub parametru.",
+ "cacheRuleNeedsValue": "Reguła „{rule}”: warunek nie ma wartości.",
+ "cacheRuleTplWordpress": "WordPress: pomiń panel i zalogowanych",
+ "cacheRuleTplStatic": "Pliki statyczne: bez ciasteczek, 30 dni",
+ "cacheRuleTplStaticCookies": "Pliki statyczne: usuń ciasteczka",
+ "cacheRuleTplStaticTtl": "Pliki statyczne: TTL 30 dni",
+ "cacheRuleTplTracking": "Ignoruj parametry śledzące (utm_*, fbclid, gclid)",
+ "cacheRuleTplApi": "API: pomiń cache",
+ "cacheRuleTplLanguage": "Osobny cache dla ciasteczka języka",
+ "cacheRuleTplNotfound": "Krótki TTL dla 404",
+ "cacheRuleTplNotFound": "Krótki TTL dla 404",
+ "cacheRuleTplHeaders": "Ukryj X-Powered-By",
+ "cacheRulesDocs": "Dokumentacja reguł cache",
+ "certificateApiDocs": "Dokumentacja Certificate API",
+ "certificateApiOpnsenseDocs": "Integracja z klientem ACME w OPNsense",
+ "apiTokensDocs": "Dokumentacja tokenów API",
+ "dockerLabelHelpDocs": "Dokumentacja etykiet kontenerów",
+ "systemInfoCopyDiagnostics": "Kopiuj diagnostykę",
+ "systemInfoCopyFailed": "Nie udało się skopiować do schowka.",
+ "systemInfoCopy": "Kopiuj",
+ "systemInfoRam": "RAM",
+ "systemInfoSwap": "Swap",
+ "systemInfoProcessUptime": "Czas pracy RustProxy",
+ "systemInfoSystemCpu": "CPU systemu",
+ "systemInfoProcessCpu": "CPU RustProxy",
+ "systemInfoCoreNote": "100% = 1 rdzeń",
+ "systemInfoCores": "Procesory logiczne: {count}",
+ "systemInfoLoad": "Średnie obciążenie",
+ "systemInfoLoadUnavailable": "Niedostępne na tej platformie",
+ "systemInfoOf": "z",
+ "systemInfoProcessHeading": "Proces RustProxy",
+ "systemInfoResidentMemory": "Pamięć rezydentna (RSS)",
+ "systemInfoHotCache": "Cache HOT",
+ "systemInfoTransient": "Tymczasowa",
+ "systemInfoAnonymous": "Anonimowa",
+ "systemInfoFileBacked": "Z plików",
+ "systemInfoBudgets": "Budżety",
+ "systemInfoHotLimit": "Cache HOT / limit",
+ "systemInfoTransientLimit": "Tymczasowa / limit",
+ "systemInfoTransforms": "Transformacje w toku / budżet",
+ "systemInfoProcessDetails": "Proces",
+ "systemInfoVirtual": "Pamięć wirtualna",
+ "systemInfoProcessSwap": "Swap",
+ "systemInfoDiskIo": "Dysk odczyt / zapis",
+ "systemInfoNoLimit": "Brak limitu",
+ "systemInfoNone": "Brak",
+ "systemInfoNetworkHeading": "Sieć",
+ "systemInfoInterface": "Interfejs",
+ "systemInfoRxRate": "Odbiór/s",
+ "systemInfoTxRate": "Wysyłka/s",
+ "systemInfoTotals": "Odebrano / wysłano",
+ "systemInfoNoInterfaces": "Brak aktywnych interfejsów.",
+ "systemInfoIdleInterfaces": "Nieaktywne interfejsy ({count})",
+ "systemInfoNetworkHistory": "Historia odbioru / wysyłki",
+ "systemInfoEnvironment": "Środowisko",
+ "systemInfoLive": "NA ŻYWO",
+ "systemInfoManual": "RĘCZNIE",
+ "systemInfoSampledAgo": "próbka sprzed {seconds} s",
+ "systemInfoSource": "Źródło",
+ "systemInfoFooter": "Tylko odczyt · brakujących wartości nie szacujemy",
+ "systemInfoDocs": "Dokumentacja",
+ "systemInfoFdsNote": "limit {limit} · wątki: {count}"
}
}
diff --git a/src/admin/cache_rules.rs b/src/admin/cache_rules.rs
new file mode 100644
index 0000000..f8cd911
--- /dev/null
+++ b/src/admin/cache_rules.rs
@@ -0,0 +1,251 @@
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CacheRuleTestRequest {
+ #[serde(default = "cache_rule_test_method")]
+ method: String,
+ url: String,
+ #[serde(default)]
+ headers: Vec<(String, String)>,
+ #[serde(default)]
+ client_ip: Option,
+}
+
+fn cache_rule_test_method() -> String {
+ "GET".into()
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CacheRuleTestResponse {
+ status: u16,
+ #[serde(default)]
+ headers: Vec<(String, String)>,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CacheRuleTestInput {
+ #[serde(default)]
+ vhost_id: Option,
+ #[serde(default)]
+ global_rules: Option>,
+ #[serde(default)]
+ vhost_rules: Option>,
+ #[serde(default)]
+ ignore_global_rules: Option,
+ request: CacheRuleTestRequest,
+ #[serde(default)]
+ response: Option,
+}
+
+fn cache_rule_headers(pairs: &[(String, String)]) -> Result {
+ if pairs.len() > 64 {
+ return Err(ApiError(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "at most 64 test headers".into(),
+ ));
+ }
+ let mut headers = http::HeaderMap::new();
+ for (name, value) in pairs {
+ let name = http::HeaderName::from_bytes(name.trim().as_bytes()).map_err(|_| {
+ ApiError(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ format!("invalid header name {name:?}"),
+ )
+ })?;
+ let value = http::HeaderValue::from_str(value.trim()).map_err(|_| {
+ ApiError(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ format!("invalid value for header {name}"),
+ )
+ })?;
+ headers.append(name, value);
+ }
+ Ok(headers)
+}
+
+async fn cache_rules_test(
+ State(state): State>,
+ Json(input): Json,
+) -> Result, ApiError> {
+ let invalid =
+ |error: anyhow::Error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
+ let snapshot = state.config.load_full();
+ let config = &snapshot.envelope.config;
+ let vhost = match input.vhost_id.as_deref().filter(|id| !id.is_empty()) {
+ Some(id) => Some(
+ config
+ .vhosts
+ .iter()
+ .find(|vhost| vhost.id == id)
+ .ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown vhost".into()))?,
+ ),
+ None => None,
+ };
+ let mut global = config.cache.clone();
+ if let Some(rules) = input.global_rules {
+ global.rules = rules;
+ }
+ crate::cache::validate_rules(&global.rules, true).map_err(invalid)?;
+ let mut overrides = vhost.map(|vhost| vhost.cache.clone()).unwrap_or_default();
+ if let Some(rules) = input.vhost_rules {
+ overrides.rules = rules;
+ }
+ if let Some(ignore) = input.ignore_global_rules {
+ overrides.ignore_global_rules = ignore;
+ }
+ let vhost_id = vhost.map(|vhost| vhost.id.as_str()).unwrap_or("");
+ let settings = overrides.resolve_for(&global, vhost_id).map_err(invalid)?;
+ let rules = settings.compiled_rules.clone().unwrap_or_default();
+ let raw = input.request.url.trim();
+ if raw.is_empty() || raw.len() > 8192 {
+ return Err(ApiError(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "enter a URL or path to test".into(),
+ ));
+ }
+ let uri: http::Uri = raw
+ .parse()
+ .map_err(|_| ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid test URL".into()))?;
+ let mut headers = cache_rule_headers(&input.request.headers)?;
+ let host = uri
+ .host()
+ .map(str::to_owned)
+ .or_else(|| {
+ headers
+ .get(http::header::HOST)
+ .and_then(|v| v.to_str().ok())
+ .map(|v| v.split(':').next().unwrap_or(v).to_owned())
+ })
+ .or_else(|| vhost.and_then(|vhost| vhost.frontend.hosts.first().cloned()))
+ .unwrap_or_default();
+ let method =
+ http::Method::from_bytes(input.request.method.trim().to_ascii_uppercase().as_bytes())
+ .map_err(|_| ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid method".into()))?;
+ let client_ip =
+ match input
+ .request
+ .client_ip
+ .as_deref()
+ .map(str::trim)
+ .filter(|v| !v.is_empty())
+ {
+ Some(value) => Some(value.parse().map_err(|_| {
+ ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid client IP".into())
+ })?),
+ None => None,
+ };
+ let path = uri.path().to_owned();
+ let mut request = crate::cache::RuleRequest {
+ host: host.clone(),
+ path: path.clone(),
+ query: uri.query().map(str::to_owned),
+ method: method.clone(),
+ headers: headers.clone(),
+ client_ip,
+ };
+ let request_outcome = rules.evaluate_request(&request, false);
+ request_outcome.rewrite_cookies(&mut headers);
+ let query = match request_outcome.rewrite_query(uri.query()) {
+ Some(rewritten) => rewritten,
+ None => uri.query().map(str::to_owned),
+ };
+ request.headers = headers.clone();
+ request.query = query.clone();
+ let target = match &query {
+ Some(query) => format!("{path}?{query}"),
+ None => path.clone(),
+ };
+ let request_policy = if request_outcome.pass.is_some() {
+ Some("cache_rule")
+ } else if !settings.enabled {
+ Some("cache_disabled")
+ } else {
+ crate::cache::request_policy(&method, &headers, true, &path, query.is_some(), &settings)
+ .bypass_reason()
+ };
+ let mut response_value = Value::Null;
+ let mut deliver_value = Value::Null;
+ if let Some(response) = input.response {
+ let status = StatusCode::from_u16(response.status).map_err(|_| {
+ ApiError(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "invalid response status".into(),
+ )
+ })?;
+ let mut response_headers = cache_rule_headers(&response.headers)?;
+ let outcome = rules.evaluate_response(&request, status, &response_headers, false);
+ if outcome.overrides.strip_set_cookie {
+ response_headers.remove(http::header::SET_COOKIE);
+ }
+ let plan = if request_policy.is_none() {
+ crate::cache::plan_with(
+ status,
+ &response_headers,
+ &settings,
+ std::time::Duration::ZERO,
+ &outcome.overrides,
+ )
+ } else {
+ None
+ };
+ let store_reason = if request_policy.is_some() {
+ None
+ } else if outcome.overrides.no_store {
+ Some("cache_rule_no_store")
+ } else if plan.is_none() {
+ Some(crate::cache::response_reason(
+ status,
+ &response_headers,
+ &settings,
+ ))
+ } else {
+ None
+ };
+ response_value = json!({
+ "matched": outcome.matched,
+ "overridden": outcome.overridden,
+ "overrides": outcome.overrides,
+ "stored": plan.is_some(),
+ "ttl": plan.as_ref().map(|plan| plan.ttl()),
+ "grace": plan.as_ref().map(|plan| plan.grace()),
+ "reason": store_reason,
+ });
+ let deliver = rules.evaluate_deliver(&request, status, &response_headers, false);
+ deliver_value =
+ json!({"matched": deliver.matched, "set": deliver.set, "remove": deliver.remove});
+ }
+ Ok(Json(json!({
+ "host": host,
+ "request": {
+ "matched": request_outcome.matched,
+ "overridden": request_outcome.overridden,
+ "pass": request_outcome.pass,
+ "target": target,
+ "cookie": headers.get(http::header::COOKIE).and_then(|v| v.to_str().ok()),
+ "variant": request_outcome.hash,
+ "cacheable": request_policy.is_none(),
+ "reason": request_policy,
+ },
+ "response": response_value,
+ "deliver": deliver_value,
+ })))
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CacheVclImportInput {
+ vcl: String,
+}
+
+async fn cache_rules_import_vcl(
+ Json(input): Json,
+) -> Result, ApiError> {
+ let result = crate::cache::import_vcl(&input.vcl)
+ .map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()))?;
+ Ok(Json(json!(result)))
+}
+
+async fn cache_rules_stats() -> Json {
+ Json(json!({"hits": crate::cache::rule_hit_counts()}))
+}
diff --git a/src/admin/documentation/documents.rs b/src/admin/documentation/documents.rs
index 43d934c..5e1d7e8 100644
--- a/src/admin/documentation/documents.rs
+++ b/src/admin/documentation/documents.rs
@@ -37,4 +37,5 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/API.md", "guides"),
reader_doc!("docs/PERFORMANCE.md", "guides"),
reader_doc!("docs/TROUBLESHOOTING.md", "guides"),
+ reader_doc!("integrations/opnsense-acme/README.md", "guides"),
];
diff --git a/src/admin/mod.rs b/src/admin/mod.rs
index a3a1216..7cf5f0d 100644
--- a/src/admin/mod.rs
+++ b/src/admin/mod.rs
@@ -12,6 +12,7 @@ include!("api_tokens.rs");
include!("file_logs.rs");
include!("file_log_search.rs");
include!("operations.rs");
+include!("cache_rules.rs");
include!("certificate_api.rs");
include!("certificates.rs");
include!("tail.rs");
diff --git a/src/admin/openapi.json b/src/admin/openapi.json
index 1340d9a..b8e9eb0 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.37.0",
+ "version": "0.37.1",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
@@ -755,6 +755,19 @@
"nullable": true,
"default": null,
"description": "If true, only emit cache diagnostic headers for actual HIT responses, never MISS/BYPASS. null inherits global expose_only_hits. Via is controlled independently."
+ },
+ "rules": {
+ "type": "array",
+ "maxItems": 128,
+ "items": {
+ "$ref": "#/components/schemas/CacheRule"
+ },
+ "description": "Vhost cache rules; evaluated before global rules (no vhosts field)."
+ },
+ "ignore_global_rules": {
+ "type": "boolean",
+ "default": false,
+ "description": "Skip global cache rules for this vhost."
}
},
"additionalProperties": true
@@ -2412,6 +2425,14 @@
"type": "boolean",
"default": true,
"description": "Default true: ignore only client hard-reload no-cache, max-age=0 and Pragma: no-cache on fresh cache lookups. Preserve client no-store, only-if-cached (504 on MISS), min-fresh/max-stale, origin ETag revalidation and zero-TTL stale-if-error storage. A positive default_ttl_seconds explicitly allows public origin no-cache responses to be reused for that fallback TTL, even without validators; zero keeps validator-only revalidation. Surrogate-Control: no-store and all private/no-store/Set-Cookie/Vary restrictions remain active. Eligible positive-TTL entries without an explicit stale-while-revalidate directive get configurable grace (varnish_grace_seconds, default 60s; explicit =0 is honored). False restores strict browser reload. Switching modes invalidates cache; not full Varnish VCL emulation."
+ },
+ "rules": {
+ "type": "array",
+ "maxItems": 128,
+ "items": {
+ "$ref": "#/components/schemas/CacheRule"
+ },
+ "description": "Global cache rules (Cache → Rules)."
}
},
"additionalProperties": false
@@ -3715,7 +3736,7 @@
},
"source": {
"type": "string",
- "description": "Discovery sources, for example interface, route, public_api or override."
+ "description": "Discovery sources, for example interface, route, public_api, override or bridge (container bridge interfaces such as docker0, br-*, podman*, reported since agent 0.37.1)."
},
"interface": {
"type": "string"
@@ -8549,6 +8570,192 @@
"type": "string"
}
}
+ },
+ "CacheRule": {
+ "type": "object",
+ "description": "Cache rule (since 0.37.1). Request rules run before the cache lookup (vcl_recv/vcl_hash), response rules on a backend response (vcl_backend_response), deliver rules on every response sent to the client (vcl_deliver). Vhost rules run before global rules; for TTL, grace, pass and no_store the first matching rule wins.",
+ "required": [
+ "id",
+ "actions"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ },
+ "stage": {
+ "type": "string",
+ "enum": [
+ "request",
+ "response",
+ "deliver"
+ ],
+ "default": "request"
+ },
+ "match": {
+ "type": "string",
+ "enum": [
+ "all",
+ "any"
+ ],
+ "default": "all"
+ },
+ "conditions": {
+ "type": "array",
+ "maxItems": 16,
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "enum": [
+ "host",
+ "url",
+ "path",
+ "extension",
+ "method",
+ "query",
+ "header",
+ "cookie",
+ "client_ip",
+ "status",
+ "content_type",
+ "response_header"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "operator": {
+ "type": "string",
+ "enum": [
+ "equals",
+ "prefix",
+ "suffix",
+ "contains",
+ "glob",
+ "regex",
+ "exists",
+ "cidr"
+ ]
+ },
+ "values": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "negate": {
+ "type": "boolean"
+ }
+ }
+ }
+ },
+ "actions": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 16,
+ "items": {
+ "type": "object",
+ "description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, remove_header{name} (deliver).",
+ "additionalProperties": true
+ }
+ },
+ "stop": {
+ "type": "boolean"
+ },
+ "vhosts": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Global rules only: limit to these vhost ids (empty = all)."
+ }
+ }
+ },
+ "CacheRuleTestRequest": {
+ "type": "object",
+ "required": [
+ "request"
+ ],
+ "properties": {
+ "vhost_id": {
+ "type": "string"
+ },
+ "global_rules": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CacheRule"
+ }
+ },
+ "vhost_rules": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CacheRule"
+ }
+ },
+ "ignore_global_rules": {
+ "type": "boolean"
+ },
+ "request": {
+ "type": "object",
+ "properties": {
+ "method": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ },
+ "headers": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "client_ip": {
+ "type": "string"
+ }
+ }
+ },
+ "response": {
+ "type": "object",
+ "properties": {
+ "status": {
+ "type": "integer"
+ },
+ "headers": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "CacheVclImportRequest": {
+ "type": "object",
+ "required": [
+ "vcl"
+ ],
+ "properties": {
+ "vcl": {
+ "type": "string",
+ "maxLength": 262144
+ }
+ }
}
}
},
@@ -15374,6 +15581,342 @@
}
}
}
+ },
+ "/api/cache/rules/stats": {
+ "get": {
+ "summary": "Cache rule match counters",
+ "tags": [
+ "Cache"
+ ],
+ "operationId": "get_api_cache_rules_stats",
+ "responses": {
+ "200": {
+ "description": "Match counters keyed by global: or vhost:: since process start",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required or revoked",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Host, origin or CSRF validation failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Bounded worker/session/rate limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Control-plane storage/worker unavailable",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "AdminSession": []
+ },
+ {
+ "GeneralApiBearer": []
+ }
+ ]
+ }
+ },
+ "/api/cache/rules/test": {
+ "post": {
+ "summary": "Simulate cache rules for a request",
+ "tags": [
+ "Cache"
+ ],
+ "operationId": "post_api_cache_rules_test",
+ "description": "Evaluates saved or draft global/vhost cache rules for a test request (and optional backend response) without sending traffic or counting matches. Returns matched rules per stage, overridden rule actions, the rewritten URL, cookies, cache key variants, TTL/grace and the cache decision.",
+ "parameters": [
+ {
+ "name": "Origin",
+ "in": "header",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE."
+ },
+ {
+ "name": "X-RustProxy-Request",
+ "in": "header",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "enum": [
+ "1"
+ ]
+ }
+ }
+ ],
+ "security": [
+ {
+ "AdminSession": []
+ },
+ {
+ "GeneralApiBearer": []
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CacheRuleTestRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Simulation result",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required or revoked",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Host, origin or CSRF validation failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "413": {
+ "description": "Request exceeds the endpoint body limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Configuration/input validation failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Bounded worker/session/rate limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Control-plane storage/worker unavailable",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/cache/rules/import-vcl": {
+ "post": {
+ "summary": "Convert a VCL subset into cache rules",
+ "tags": [
+ "Cache"
+ ],
+ "operationId": "post_api_cache_rules_import_vcl",
+ "description": "Parses vcl_recv/vcl_hash, vcl_backend_response/vcl_fetch and vcl_deliver and converts supported statements into cache rules. Unsupported statements are returned as warnings; nothing is saved.",
+ "parameters": [
+ {
+ "name": "Origin",
+ "in": "header",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE."
+ },
+ {
+ "name": "X-RustProxy-Request",
+ "in": "header",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "enum": [
+ "1"
+ ]
+ }
+ }
+ ],
+ "security": [
+ {
+ "AdminSession": []
+ },
+ {
+ "GeneralApiBearer": []
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CacheVclImportRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Imported rules and warnings",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required or revoked",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Host, origin or CSRF validation failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "413": {
+ "description": "Request exceeds the endpoint body limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Configuration/input validation failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "Bounded worker/session/rate limit",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Control-plane storage/worker unavailable",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"tags": []
diff --git a/src/admin/router.rs b/src/admin/router.rs
index e0d2be8..2800977 100644
--- a/src/admin/router.rs
+++ b/src/admin/router.rs
@@ -88,6 +88,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/drafts.js"),
include_str!("web/integrations.js"),
include_str!("web/acl-picker.js"),
+ include_str!("web/cache-rules.js"),
admin_vhosts_javascript(),
include_str!("web/web-server-profiles.js"),
include_str!("web/web-server.js"),
@@ -100,6 +101,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/transform-panel.js"),
include_str!("web/acme.js"),
include_str!("web/settings.js"),
+ include_str!("web/system-info.js"),
include_str!("web/certificate-api.js"),
include_str!("web/api-tokens.js"),
include_str!("web/prometheus-token.js"),
@@ -249,6 +251,15 @@ pub fn router(state: Arc) -> Router {
post(cache_invalidate).layer(DefaultBodyLimit::max(16 * 1024)),
)
.route("/api/cache/bans", get(cache_bans))
+ .route("/api/cache/rules/stats", get(cache_rules_stats))
+ .route(
+ "/api/cache/rules/test",
+ post(cache_rules_test).layer(DefaultBodyLimit::max(256 * 1024)),
+ )
+ .route(
+ "/api/cache/rules/import-vcl",
+ post(cache_rules_import_vcl).layer(DefaultBodyLimit::max(300 * 1024)),
+ )
.route("/api/cache/bans/{id}", delete(cache_ban_delete))
.route("/api/tunnels", get(active_tunnels))
.route(
diff --git a/src/admin/web/acl-picker.js b/src/admin/web/acl-picker.js
index 47f6f8e..5c0c7e4 100644
--- a/src/admin/web/acl-picker.js
+++ b/src/admin/web/acl-picker.js
@@ -135,7 +135,7 @@ window.rustProxyChoicePicker = (() => {
remove.addEventListener("click", () => { const box = checks.get(id); box.checked = false; box.dispatchEvent(new Event("change", { bubbles: true })); });
tag.append(text);
if (index > 0 && options.markFirst && options.makeFirst) {
- const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`);
+ const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.dataset.uiIconName = "none"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`);
promote.addEventListener("click", () => { order.splice(order.indexOf(id), 1); order.unshift(id); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); });
tag.append(promote);
}
@@ -170,3 +170,73 @@ window.rustProxyChoicePicker = (() => {
}
return { create, read: root => root?.read?.() || [] };
})();
+
+window.rustProxyChipInput = (() => {
+ const CIDR = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}(?:\/(?:3[0-2]|[12]?\d))?|[0-9a-fA-F:]*:[0-9a-fA-F:.]*(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?)$/;
+ function create(options = {}) {
+ const box = el("div", undefined, `host-chip-editor ${options.className || ""}`.trim()), input = document.createElement("input");
+ input.type = "text"; input.maxLength = options.maxLength || 128; input.placeholder = options.placeholder || ""; input.spellcheck = false;
+ if (options.label) input.setAttribute("aria-label", options.label);
+ const values = [], limit = options.limit || 64;
+ const changed = () => box.dispatchEvent(new Event("change", { bubbles: true }));
+ const normalize = raw => { const value = String(raw || "").trim(); if (!value) return null; if (options.validate) { const result = options.validate(value); if (result === false) throw fieldError(input, options.invalidMessage || t("invalidValue")); if (typeof result === "string") return result; } return value; };
+ const sync = () => {
+ box.querySelectorAll(".host-chip").forEach(node => node.remove());
+ for (const value of values) {
+ const chip = el("span", undefined, "host-chip"); chip.append(el("span", value));
+ const remove = el("button", "×"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${value}`);
+ remove.addEventListener("click", () => { values.splice(values.indexOf(value), 1); sync(); changed(); });
+ chip.append(remove); box.insertBefore(chip, input);
+ }
+ };
+ const add = (raw, notify = true) => { const value = normalize(raw); if (!value || values.includes(value)) return; if (values.length >= limit) throw fieldError(input, options.limitMessage || t("aclPickerLimit")); values.push(value); sync(); if (notify) changed(); };
+ const consume = raw => { for (const part of String(raw).split(/[\s,;]+/).filter(Boolean)) add(part); input.value = ""; };
+ const guarded = raw => { try { consume(raw); } catch (error) { toast(error.message, true); } };
+ input.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === ",") { event.preventDefault(); guarded(input.value); } });
+ input.addEventListener("blur", () => { if (input.value.trim()) guarded(input.value); });
+ input.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,;]/.test(value.trim())) return; event.preventDefault(); guarded(value); });
+ box.append(input);
+ for (const value of options.values || []) { try { add(value, false); } catch { } }
+ box.read = () => { if (input.value.trim()) consume(input.value); return [...values]; };
+ box.set = list => { values.length = 0; for (const value of list || []) { try { add(value, false); } catch { } } sync(); };
+ box.input = input;
+ return box;
+ }
+ const validCidr = value => CIDR.test(value);
+ return { create, validCidr };
+})();
+
+window.rustProxyCountryPicker = (() => {
+ const CODES = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW".split(" ");
+ const nameOf = code => { try { return new Intl.DisplayNames([document.documentElement.lang || "en"], { type: "region" }).of(code) || code; } catch { return code; } };
+ const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
+ function attach(textarea, options = {}) {
+ if (!textarea || textarea.dataset.countryPicker) return null;
+ textarea.dataset.countryPicker = "1"; textarea.hidden = true;
+ const host = el("div", undefined, "country-picker-host"); textarea.after(host);
+ let picker = null, writing = false;
+ const build = () => {
+ const items = CODES.map(code => ({ id: code, title: `${code} · ${nameOf(code)}`, search: nameOf(code) }));
+ picker = window.rustProxyChoicePicker.create({
+ className: "country-picker", selected: parse(textarea.value), items, limit: options.limit || 250,
+ labels: { choose: "countryPickerChoose", selected: "countryPickerSelected", none: "countryPickerNone", search: "countryPickerSearch", addHint: "countryPickerAddHint", empty: "countryPickerEmpty" },
+ custom: raw => {
+ const text = String(raw || "").trim(); if (!text) return null;
+ const code = text.toUpperCase();
+ if (/^[A-Z]{2}$/.test(code)) return { id: code, title: `${code} · ${nameOf(code)}` };
+ const query = text.toLocaleLowerCase(), matches = CODES.filter(item => nameOf(item).toLocaleLowerCase().includes(query));
+ const exact = matches.find(item => nameOf(item).toLocaleLowerCase() === query) || (matches.length === 1 ? matches[0] : null);
+ return exact ? { id: exact, title: `${exact} · ${nameOf(exact)}` } : null;
+ },
+ });
+ picker.addEventListener("choicechange", event => { if (writing) return; const value = (event.detail || []).join("\n"); if (value === textarea.value) return; textarea.value = value; textarea.dispatchEvent(new Event("input", { bubbles: true })); });
+ host.replaceChildren(picker);
+ picker.setDisabled(textarea.disabled);
+ };
+ const refresh = () => { writing = true; try { build(); } finally { writing = false; } };
+ refresh();
+ new MutationObserver(() => picker?.setDisabled(textarea.disabled)).observe(textarea, { attributes: true, attributeFilter: ["disabled"] });
+ return { refresh, host };
+ }
+ return { attach, codes: CODES, nameOf };
+})();
diff --git a/src/admin/web/api-tokens.js b/src/admin/web/api-tokens.js
index 45e7fbf..2b14e0f 100644
--- a/src/admin/web/api-tokens.js
+++ b/src/admin/web/api-tokens.js
@@ -1,47 +1,84 @@
"use strict";
window.rustProxyApiTokens = (() => {
- let loading = false;
+ let loading = false, state = null, cidrs = null;
const hideSecret = () => { $("api-token-secret").textContent = ""; $("api-token-secret-wrap").hidden = true; };
+ const normalizeCidr = value => {
+ if (!window.rustProxyChipInput.validCidr(value)) return false;
+ if (value.includes("/")) return value;
+ return value.includes(":") ? `${value}/128` : `${value}/32`;
+ };
+ function closeEditor() { $("api-tokens-form").hidden = true; $("api-token-new").disabled = false; }
+ function openEditor() {
+ hideSecret();
+ $("api-token-comment").value = "";
+ $("api-token-permission-ro").checked = true;
+ cidrs = window.rustProxyChipInput.create({ className: "api-token-cidr-editor", placeholder: "192.0.2.10 / 10.0.0.0/24 / 2001:db8::/64", label: t("apiTokenIpAllow"), limit: 32, validate: normalizeCidr, invalidMessage: t("apiTokenCidrInvalid"), limitMessage: t("apiTokenCidrLimit") });
+ $("api-token-cidrs").replaceChildren(cidrs);
+ $("api-tokens-form").hidden = false;
+ $("api-token-new").disabled = true;
+ $("api-token-comment").focus?.();
+ }
+ function example(id) {
+ $("api-token-example").textContent = `curl -H "Authorization: Bearer $RUSTPROXY_API_TOKEN" ${location.origin}/api/status`;
+ if (id) $("api-token-example").textContent += `\n\n# ${id}`;
+ }
+ function render() {
+ const list = $("api-token-list"); list.replaceChildren();
+ const tokens = state?.tokens || [], max = Number(state?.max_tokens) || 0;
+ $("api-token-status").textContent = tokens.length ? t("apiTokenCount").replace("{count}", tokens.length).replace("{max}", max || "-") : t("apiTokenEmpty");
+ $("api-token-new").disabled = !$("api-tokens-form").hidden || (max && tokens.length >= max);
+ for (const entry of tokens) {
+ const item = el("div", undefined, "certificate-api-credential-item"), row = el("div", undefined, "certificate-api-credential-row"), info = el("div", undefined, "certificate-api-credential-info");
+ const title = el("div", undefined, "certificate-api-credential-title");
+ title.append(el("b", entry.id, "mono"), el("span", entry.permission === "rw" ? "RW" : "RO", `pill ${entry.permission === "rw" ? "warn" : "live"}`));
+ if (entry.comment) title.append(el("span", entry.comment, "fine"));
+ const chips = el("div", undefined, "certificate-api-chips");
+ for (const cidr of entry.allowed_cidrs || []) chips.append(el("span", cidr, "certificate-api-chip"));
+ const created = entry.created_at ? formatDateTime(entry.created_at * 1000) : "-", used = entry.last_used_at ? formatDateTime(entry.last_used_at * 1000) : t("certificateApiNeverUsed");
+ info.append(title, chips, el("span", `${t("certificateApiCreatedAt")}: ${created} · ${t("certificateApiLastUsed")}: ${used}`, "fine"));
+ const actions = el("div", undefined, "certificate-api-row-actions");
+ const revoke = action(t("apiTokenRevoke"), async () => {
+ if (!(await appConfirm(t("apiTokenRevokeConfirm").replace("{id}", entry.id), { danger: true }))) return;
+ revoke.disabled = true;
+ try { await api(`/api/api-tokens/${encodeURIComponent(entry.id)}`, { method: "DELETE" }); hideSecret(); await refresh(true); toast(t("apiTokenRevoked")); }
+ catch (error) { toast(error.message, true); revoke.disabled = false; }
+ });
+ revoke.classList.add("danger"); actions.append(revoke);
+ row.append(info, actions); item.append(row); list.append(item);
+ }
+ example();
+ }
async function refresh() {
if (!authenticated || loading) return;
loading = true;
- try {
- const result = await api("/api/api-tokens");
- const list = $("api-token-list"); list.replaceChildren();
- for (const entry of result.tokens || []) {
- const card = el("div", undefined, "entity");
- card.append(el("span", `${entry.id} · ${entry.permission.toUpperCase()} · ${entry.comment || "-"}`, "entity-title"));
- card.append(el("p", `${t("apiTokenIpAllow")}: ${(entry.allowed_cidrs || []).join(", ")}`, "fine"));
- card.append(el("p", `${t("apiTokenLastUsed")}: ${entry.last_used_at ? formatDateTime(entry.last_used_at * 1000) : "-"}`, "fine"));
- card.append(action(t("apiTokenRevoke"), async () => {
- if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return;
- try { await api(`/api/api-tokens/${encodeURIComponent(entry.id)}`, { method: "DELETE" }); hideSecret(); await refresh(); }
- catch (error) { toast(error.message, true); }
- }));
- list.append(card);
- }
- if (!result.tokens?.length) list.append(el("p", t("apiTokenEmpty"), "fine"));
- } catch (error) { if (error.status !== 401) toast(error.message, true); }
+ try { state = await api("/api/api-tokens"); render(); }
+ catch (error) { if (error.status !== 401) toast(error.message, true); }
finally { loading = false; }
}
+ $("api-token-new").addEventListener("click", openEditor);
+ $("api-token-cancel").addEventListener("click", () => { closeEditor(); render(); });
+ $("api-token-secret-copy").addEventListener("click", async () => {
+ try { await navigator.clipboard.writeText($("api-token-secret").textContent); toast(t("copied")); }
+ catch { const range = document.createRange(); range.selectNodeContents($("api-token-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
+ });
$("api-tokens-form").addEventListener("submit", async event => {
event.preventDefault(); if (!authenticated) return;
- const button = event.submitter; button.disabled = true;
+ const button = event.submitter; if (button) button.disabled = true;
hideSecret();
try {
- const result = await api("/api/api-tokens", {
- method: "POST", body: JSON.stringify({
- permission: $("api-token-permission").value,
- comment: $("api-token-comment").value.trim(),
- allowed_cidrs: $("api-token-cidrs").value.split(/[\n,]+/).map(s => s.trim()).filter(Boolean)
- })
- });
- $("api-token-secret").textContent = result.token;
- $("api-token-secret-wrap").hidden = false;
- $("api-token-comment").value = "";
+ const allowed = cidrs?.read() || [];
+ if (!allowed.length) throw fieldError(cidrs, t("apiTokenCidrRequired"));
+ const permission = $("api-token-permission-rw").checked ? "rw" : "ro";
+ const result = await api("/api/api-tokens", { method: "POST", body: JSON.stringify({ permission, comment: $("api-token-comment").value.trim(), allowed_cidrs: allowed }) });
+ closeEditor();
await refresh();
- } catch (error) { toast(error.message, true); }
- finally { button.disabled = false; }
+ $("api-token-secret").textContent = result.token;
+ $("api-token-secret-title").textContent = t("apiTokenSecretTitle").replace("{id}", result.id);
+ $("api-token-secret-wrap").hidden = false;
+ toast(t("apiTokenCreated"));
+ } catch (error) { showFieldError(error, $("api-tokens-form")); toast(error.message, true); }
+ finally { if (button) button.disabled = false; }
});
- return { refresh, hideSecret, reset() { hideSecret(); $("api-token-list").replaceChildren(); } };
+ example();
+ return { refresh, hideSecret, reset() { state = null; hideSecret(); closeEditor(); $("api-token-list").replaceChildren(); } };
})();
diff --git a/src/admin/web/app/core.js b/src/admin/web/app/core.js
index fe282fd..43ee3fd 100644
--- a/src/admin/web/app/core.js
+++ b/src/admin/web/app/core.js
@@ -165,7 +165,7 @@ function setPanel(name, navigate = true) {
for (const id of ["overview-layout-open", "overview-layout-unlock"]) if ($(id)) $(id).hidden = name !== "overview" || (id === "overview-layout-unlock" && !!window.rustProxyInlineLayout?.isEditing?.());
document.querySelectorAll(".nav").forEach(e => e.classList.toggle("active", e.dataset.panel === name));
document.querySelectorAll(".panel").forEach(e => e.hidden = e.id !== `panel-${name}`);
- $("page-label").textContent = t(name); $("page-title").textContent = t(`${name}Title`); $("page-description").textContent = t(`${name}Description`);
+ $("page-label").textContent = t(name); $("page-title").textContent = t(`${name}Title`); const descriptionKey = `${name}Description`, description = t(descriptionKey); $("page-description").textContent = description === descriptionKey ? "" : description; $("page-description").hidden = description === descriptionKey;
if (navigate && typeof location !== "undefined" && ["http:", "https:"].includes(location.protocol) && location.pathname !== PANEL_PATHS[name]) history.pushState({ panel: name }, "", PANEL_PATHS[name]);
if (name === "web-server" && latestStatus) window.rustProxyWebServer?.renderLive?.(latestStatus, false);
if (name === "settings") window.rustProxySettings?.syncLocation?.();
@@ -542,6 +542,8 @@ async function activate(info) {
void window.rustProxyApiTokens?.refresh?.();
window.rustProxySettings?.scrollToApiTokens?.();
}
+ if (window.rustProxySettings?.current?.() === "prometheus") void window.rustProxyPrometheusToken?.refresh?.();
+ if (window.rustProxySettings?.current?.() === "certificate-api") void window.rustProxyCertificateApi?.load?.();
void refresh(true).catch(error => {
if (authenticated && epoch === authEpoch && error?.status !== 401) toast(error.message, true);
});
diff --git a/src/admin/web/app/dashboard-inline-layout.js b/src/admin/web/app/dashboard-inline-layout.js
index 6b1ef08..fd442e2 100644
--- a/src/admin/web/app/dashboard-inline-layout.js
+++ b/src/admin/web/app/dashboard-inline-layout.js
@@ -35,17 +35,22 @@ window.rustProxyInlineLayout = (() => {
function renderHidden() {
if (!hiddenList || !draft) return;
- const entries = draft.order.filter(id => draft.hidden.has(id));
+ const docker = window.rustProxyDockerDashboard;
+ const hiddenLabel = id => docker?.isDocker?.(id) ? dashboardWidgetBaseLabel(id) : label(id);
+ const all = draft.order.filter(id => draft.hidden.has(id)), entries = docker?.collapseHidden?.(all) || all;
if (hiddenCount) hiddenCount.textContent = `(${entries.length})`;
hiddenList.replaceChildren(...(entries.length ? entries.map(id => {
- const add = control("+", `${t("overviewLayoutInlineRestore")}: ${label(id)}`, "overview-inline-restore", () => {
- draft.hidden.delete(id);
+ const picker = docker?.agentPicker?.(id);
+ const add = control("+", `${t("overviewLayoutInlineRestore")}: ${hiddenLabel(id)}`, "overview-inline-restore", async () => {
+ const slot = docker?.slotFor?.(id, draft.hidden) || id;
+ await docker?.addWithScope?.(slot, picker);
+ draft.hidden.delete(slot);
paint();
- nodeFor(id)?.querySelector(".overview-inline-grip")?.focus();
+ nodeFor(slot)?.querySelector(".overview-inline-grip")?.focus();
});
const item = el("div", undefined, "overview-inline-hidden-item");
- item.append(el("span", label(id)), dashboardWidgetTypeBadge(id));
- const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope);
+ item.append(el("span", hiddenLabel(id)), dashboardWidgetTypeBadge(id));
+ if (picker) item.append(picker);
item.append(add);
return item;
}) : [el("span", t("overviewLayoutInlineHiddenEmpty"), "fine")]));
diff --git a/src/admin/web/app/dashboard-layout-editor.js b/src/admin/web/app/dashboard-layout-editor.js
index 55a8dbb..9a9df20 100644
--- a/src/admin/web/app/dashboard-layout-editor.js
+++ b/src/admin/web/app/dashboard-layout-editor.js
@@ -183,21 +183,24 @@ window.rustProxyDashboardLayout = (() => {
});
visibleRoot.replaceChildren(...(tiles.length ? tiles : [el("p", t("overviewLayoutEditorEmpty"), "fine")]));
const query = (search?.value || "").trim().toLocaleLowerCase();
- const hidden = draft.order.filter(id => draft.hidden.has(id)
- && (typeFilter?.value === "all" || !typeFilter?.value || dashboardWidgetType(id) === typeFilter.value)
- && (`${label(id)} ${dashboardWidgetTypeLabel(id)}`).toLocaleLowerCase().includes(query));
+ 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", label(id));
+ 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")}: ${label(id)}`);
- add.addEventListener("click", () => { draft.hidden.delete(id); render(); });
+ 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));
- const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope);
+ if (picker) item.append(picker);
item.append(add);
return item;
});
diff --git a/src/admin/web/app/docker-dashboard.js b/src/admin/web/app/docker-dashboard.js
index e12bf17..9e05831 100644
--- a/src/admin/web/app/docker-dashboard.js
+++ b/src/admin/web/app/docker-dashboard.js
@@ -26,12 +26,36 @@ window.rustProxyDockerDashboard = (() => {
select.addEventListener("change", () => void setScope(id, select.value));
return select;
}
+ const isDocker = id => ids.includes(id);
+ function collapseHidden(list) {
+ const seen = new Set();
+ return list.filter(id => { if (!isDocker(id)) return true; const base = baseOf(id); if (seen.has(base)) return false; seen.add(base); return true; });
+ }
+ function slotFor(id, hidden) {
+ if (!isDocker(id)) return id;
+ const base = baseOf(id), set = hidden instanceof Set ? hidden : new Set(hidden || []);
+ return ids.find(item => baseOf(item) === base && set.has(item)) || id;
+ }
+ function agentPicker(id) {
+ if (!isDocker(id)) return null;
+ const agents = configuredAgents(); if (agents.length < 2) return null;
+ const select = el("select", undefined, "docker-widget-scope docker-widget-add-scope"); select.setAttribute("aria-label", t("dockerWidgetScope")); select.title = t("dockerWidgetScope");
+ const all = el("option", t("dockerWidgetScopeAll")); all.value = ""; select.append(all);
+ for (const agent of agents) { const option = el("option", agent.name || agent.id); option.value = agent.id; select.append(option); }
+ return select;
+ }
+ async function addWithScope(id, picker) { if (!isDocker(id)) return; const agent = picker?.value || ""; if (agent !== scopeOf(id)) await setScope(id, agent); }
+ function scopeLabel(id) {
+ if (!isDocker(id)) return "";
+ const agentId = scopeOf(id); if (!agentId) return "";
+ const agent = configuredAgents().find(item => item.id === agentId); return agent ? agent.name || agent.id : "";
+ }
const card = id => document.querySelector(`[data-dashboard-widget="${id}"]`);
const shown = id => card(id) && !card(id).hidden;
function syncCardControls() {
for (const id of ids) {
const node = card(id); if (!node) continue;
- const instance = id.match(/_([2-9])$/)?.[1]; if (instance) node.querySelector(":scope > span")?.setAttribute("data-instance", instance);
+ const instance = id.match(/_([2-9])$/)?.[1], title = node.querySelector(":scope > span"); if (instance && !scopeOf(id)) title?.setAttribute("data-instance", instance); else title?.removeAttribute("data-instance");
const signature = `${configuredAgents().map(agent => `${agent.id}:${agent.name}`).join("|")}#${scopeOf(id)}`;
if (node.dataset.dockerScope === signature) continue;
node.dataset.dockerScope = signature;
@@ -175,5 +199,5 @@ window.rustProxyDockerDashboard = (() => {
const detail = alerts.slice(0, 4).map(alertText).join(" · ") + (alerts.length > 4 ? ` · +${alerts.length - 4}` : "");
return { level: alerts.some(alert => alert.severity === "error") ? "error" : "warning", label: t("dockerAlertsHealth"), detail };
}
- return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, alertText, notify, healthCheck, ids };
+ return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, scopeLabel, isDocker, collapseHidden, slotFor, agentPicker, addWithScope, alertText, notify, healthCheck, ids };
})();
diff --git a/src/admin/web/app/icons.js b/src/admin/web/app/icons.js
index aa645f9..d59e02b 100644
--- a/src/admin/web/app/icons.js
+++ b/src/admin/web/app/icons.js
@@ -156,7 +156,7 @@ const UI_I18N_ICONS = Object.freeze({
renewalEnable: "toggleOn", renewalDisable: "toggleOff", tunnelKill: "ban", certAssignVhosts: "network",
});
-const UI_GLYPH_LABEL = /^[×✕−+←→↑↓⠿]$/;
+const UI_GLYPH_LABEL = /^[×✕−+←→↑↓⠿★☆]$/;
function uiIconForTarget(target) {
const manual = target.dataset.uiIconName;
if (manual === "none") return null;
diff --git a/src/admin/web/app/preferences.js b/src/admin/web/app/preferences.js
index df37952..d877dd1 100644
--- a/src/admin/web/app/preferences.js
+++ b/src/admin/web/app/preferences.js
@@ -183,7 +183,13 @@ function applyDashboardLayout(order, hidden, sizes = null, heights = undefined)
}
function dashboardWidgetLabel(id) {
const widget = ADMIN_DASHBOARD_BY_ID.get(id);
- return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id;
+ if (!widget) return id;
+ const scope = window.rustProxyDockerDashboard?.scopeLabel?.(id);
+ return `${t(widget.label_key)}${scope ? ` · ${scope}` : widget.instance > 1 ? ` #${widget.instance}` : ""}`;
+}
+function dashboardWidgetBaseLabel(id) {
+ const widget = ADMIN_DASHBOARD_BY_ID.get(id);
+ return widget ? t(widget.label_key) : id;
}
const DASHBOARD_DISPLAY_TYPE_KEYS = Object.freeze({
value: "overviewBlockTypeValue", value_chart: "overviewBlockTypeValueChart",
@@ -207,7 +213,9 @@ function renderDashboardWidgetSettings() {
const focusedId = focusedRow && list.contains?.(focusedRow) ? focusedRow.dataset.dashboardWidgetSetting : null;
const focusedAction = focusedId ? document.activeElement?.dataset.dashboardWidgetAction : null;
const current = adminPreferences || ADMIN_APPEARANCE_DEFAULTS, order = dashboardVisualOrder(current.dashboard_widgets, current.dashboard_widget_sizes), hidden = new Set(normalizeHiddenDashboardWidgets(current.dashboard_hidden_widgets));
+ const docker = window.rustProxyDockerDashboard, representatives = new Set(docker?.collapseHidden?.(order.filter(id => hidden.has(id))) || []);
const rows = order.map((id, index) => {
+ if (docker?.isDocker?.(id) && hidden.has(id) && !representatives.has(id)) return null;
const row = el("div", undefined, "dashboard-widget-setting"); row.dataset.dashboardWidgetSetting = id;
const visible = !hidden.has(id);
const toggle = el("button", undefined, "dashboard-widget-toggle"); toggle.type = "button"; toggle.dataset.dashboardWidgetAction = "toggle"; toggle.classList.toggle("is-hidden", !visible); toggle.setAttribute("aria-pressed", String(visible)); toggle.setAttribute("aria-label", `${t("dashboardWidgetVisible")}: ${dashboardWidgetLabel(id)}`);
@@ -239,7 +247,7 @@ function renderDashboardWidgetSettings() {
};
up.addEventListener("click", () => move(-1)); down.addEventListener("click", () => move(1)); actions.append(up, down); row.append(toggle, actions); return row;
});
- list.replaceChildren(...rows);
+ list.replaceChildren(...rows.filter(Boolean));
list.scrollLeft = previousScroll;
if (focusedId && focusedAction) {
const row = [...list.children].find(item => item.dataset.dashboardWidgetSetting === focusedId);
diff --git a/src/admin/web/app/runtime.js b/src/admin/web/app/runtime.js
index 8653bad..1e4ce6b 100644
--- a/src/admin/web/app/runtime.js
+++ b/src/admin/web/app/runtime.js
@@ -245,6 +245,10 @@ function syncSettingsDirtyIndicators() {
const dirty = dirtyTabs.has(button.dataset.settingsTab); button.classList.toggle("has-unsaved", dirty);
if (dirty) button.title = t("unsavedChanges"); else button.removeAttribute("title");
});
+ document.querySelectorAll("[data-settings-page] form[id]").forEach(form => {
+ const bar = [...form.children].filter(node => node.classList?.contains("form-actions")).pop(); if (!bar) return;
+ bar.classList.add("settings-save-bar"); bar.dataset.unsavedLabel = t("unsavedChanges"); bar.classList.toggle("has-unsaved", settingsDirty.has(form.id));
+ });
window.rustProxyIntegrations?.syncHttp2Availability?.();
window.rustProxyIntegrations?.syncHttp3Availability?.();
}
diff --git a/src/admin/web/app/settings.js b/src/admin/web/app/settings.js
index 3ffee69..5c07c1c 100644
--- a/src/admin/web/app/settings.js
+++ b/src/admin/web/app/settings.js
@@ -1,3 +1,4 @@
+let cacheRulesEditor = null, cacheRulesRendered = "";
function renderSettings() {
if (!envelope) return; const config = envelope.config; window.rustProxySettings?.render();
if (!settingsDirty.has("listeners-form")) window.rustProxyIntegrations?.renderListeners();
@@ -11,6 +12,12 @@ function renderSettings() {
$("compress-min").value = compression.min_bytes ?? 1024; syncServerMode();
}
if (!settingsDirty.has("cache-form")) {
+ const rulesJson = JSON.stringify(config.cache?.rules || []);
+ if (window.rustProxyCacheRules && (!cacheRulesEditor || rulesJson !== cacheRulesRendered)) {
+ cacheRulesEditor = window.rustProxyCacheRules.create({ scope: "global", rules: config.cache?.rules || [] });
+ cacheRulesRendered = rulesJson;
+ $("cache-rules-root")?.replaceChildren(cacheRulesEditor.node);
+ }
const c = config.cache || {}; $("cache-enabled").checked = !!c.enabled; $("cache-varnish-compatible").checked = c.varnish_compatible !== false; $("cache-varnish-grace").value = c.varnish_grace_seconds ?? 60; $("cache-memory").value = (c.max_bytes ?? 268435456) / 1048576;
$("cache-transient-memory").value = (c.transient_max_bytes ?? 67108864) / 1048576;
$("cache-object").value = (c.max_object_bytes ?? 16777216) / 1024; $("cache-entries").value = c.max_entries ?? 4096;
@@ -82,6 +89,7 @@ function renderSettings() {
const ua = global.user_agent_blocking || {}, acl = global.acl;
$("global-country-mode").value = country.mode || "off";
$("global-country-list").value = (country.countries || []).join("\n");
+ globalCountryPicker()?.refresh();
$("global-ua-block-enabled").checked = ua.enabled === true;
$("global-ua-block-patterns").value = (ua.patterns || []).join("\n");
$("global-ip-enabled").checked = !!acl;
@@ -123,8 +131,32 @@ function syncGlobalSecurityControls() {
]) {
const source = $(toggle);
const enabled = source.type === "checkbox" ? source.checked : source.value !== "off";
- for (const id of children) $(id).disabled = !enabled;
+ for (const id of children) { $(id).disabled = !enabled; const holder = $(id).closest("label, .settings-chip-field, .global-rate-fields"); if (holder && holder.contains(source) === false) holder.hidden = !enabled; }
+ const section = source.closest(".global-policy-section");
+ if (section) {
+ section.classList.toggle("is-off", !enabled);
+ const heading = section.querySelector(".global-policy-heading h3");
+ let pill = heading?.querySelector(".global-policy-state");
+ if (heading && !pill) { pill = el("span", "", "pill global-policy-state"); heading.append(pill); }
+ if (pill) { const mode = source.type === "checkbox" ? "" : source.value; pill.textContent = !enabled ? t("globalPolicyOff") : mode === "block" ? t("globalPolicyBlockMode") : mode === "allow" ? t("globalPolicyAllowMode") : t("globalPolicyOn"); pill.className = `pill global-policy-state ${enabled ? "live" : ""}`.trim(); }
+ }
}
+ globalCountryPicker();
+ syncGlobalPolicySummary();
+}
+let globalCountryPickerInstance = null;
+function globalCountryPicker() { if (!globalCountryPickerInstance) globalCountryPickerInstance = window.rustProxyCountryPicker?.attach($("global-country-list")) || null; return globalCountryPickerInstance; }
+function syncGlobalPolicySummary() {
+ const nav = $("global-policy-summary"); if (!nav) return;
+ const items = [...document.querySelectorAll("#global-security-form .global-policy-section")].map(section => {
+ const title = section.querySelector(".global-policy-heading h3")?.firstChild?.textContent?.trim() || "";
+ const state = section.querySelector(".global-policy-state")?.textContent || "";
+ const chip = el("button", undefined, `global-policy-chip${section.classList.contains("is-off") ? "" : " is-on"}`); chip.type = "button"; chip.dataset.uiIconName = "none";
+ chip.append(el("span", title), el("b", state));
+ chip.addEventListener("click", () => { section.scrollIntoView({ block: "start", behavior: "smooth" }); section.querySelector("input, select, textarea, summary")?.focus?.({ preventScroll: true }); });
+ return chip;
+ });
+ nav.replaceChildren(...items);
}
for (const id of ["global-country-mode", "global-ua-block-enabled", "global-ip-enabled", "global-method-mode", "global-content-type-enabled", "global-rate-enabled", "global-hsts-enabled"]) {
$(id)?.addEventListener("change", syncGlobalSecurityControls);
@@ -341,7 +373,7 @@ bindSettingsForm("response-form", next => {
next.compression = { min_bytes: Number($("compress-min").value) }; for (const name of ["gzip", "br", "zstd", "deflate"]) next.compression[name] = $(`compress-${name}`).checked;
}, "response", next => ({ server_header: next.server_header, diagnostic_headers: next.diagnostic_headers, compression: next.compression }));
bindSettingsForm("cache-form", next => {
- next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null };
+ next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) };
}, "cache");
bindSettingsForm("transform-form", next => {
next.transform = {
diff --git a/src/admin/web/cache-rules.js b/src/admin/web/cache-rules.js
new file mode 100644
index 0000000..ae417c9
--- /dev/null
+++ b/src/admin/web/cache-rules.js
@@ -0,0 +1,455 @@
+"use strict";
+window.rustProxyCacheRules = (() => {
+ const MAX_RULES = 128;
+ const STAGES = ["request", "response", "deliver"];
+ const STAGE_KEYS = { request: "cacheRuleStageRequest", response: "cacheRuleStageResponse", deliver: "cacheRuleStageDeliver" };
+ const FIELDS = {
+ host: { ops: ["equals", "suffix", "prefix", "regex", "glob"], stages: STAGES },
+ url: { ops: ["prefix", "regex", "glob", "equals", "contains"], stages: STAGES },
+ path: { ops: ["prefix", "equals", "glob", "regex", "suffix", "contains"], stages: STAGES },
+ extension: { ops: ["equals"], stages: STAGES },
+ method: { ops: ["equals"], stages: STAGES },
+ query: { ops: ["exists", "equals", "prefix", "regex"], name: true, stages: STAGES },
+ header: { ops: ["exists", "equals", "contains", "prefix", "regex"], name: true, stages: STAGES },
+ cookie: { ops: ["exists", "equals", "regex"], name: true, stages: STAGES },
+ client_ip: { ops: ["cidr"], stages: STAGES },
+ status: { ops: ["equals"], stages: ["response", "deliver"] },
+ content_type: { ops: ["prefix", "equals", "regex"], stages: ["response", "deliver"] },
+ response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
+ };
+ const ACTIONS = {
+ request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
+ response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
+ deliver: ["set_header", "remove_header"],
+ };
+ const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
+ const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
+ const fieldLabel = field => tk("cacheRuleField", field);
+ const opLabel = op => tk("cacheRuleOp", op);
+ const actionLabel = type => tk("cacheRuleAction", type);
+ const splitList = value => String(value || "").split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
+ const durationUnits = [["s", 1], ["m", 60], ["h", 3600], ["d", 86400]];
+ function slug(value, taken) {
+ let base = String(value || "").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/ł/g, "l").replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56) || "rule";
+ let candidate = base, n = 2;
+ while (taken.has(candidate)) candidate = `${base}-${n++}`;
+ return candidate;
+ }
+ function blankRule(taken, stage = "request") {
+ const id = slug(t("cacheRuleNewName"), taken);
+ return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
+ }
+ function normalize(rule) {
+ return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, vhosts: [...(rule.vhosts || [])] };
+ }
+ function clean(rule, global) {
+ const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
+ if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
+ return out;
+ }
+ const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const globRe = value => String(value).split("*").map(reEsc).join(".*");
+ function vclVar(field, name, stage) {
+ const resp = stage === "deliver" ? "resp" : "beresp";
+ return { host: "req.http.host", url: "req.url", path: "req.url", extension: "req.url", method: "req.method", query: "req.url", header: `req.http.${name}`, cookie: "req.http.Cookie", client_ip: "client.ip", status: `${resp}.status`, content_type: `${resp}.http.Content-Type`, response_header: `${resp}.http.${name}` }[field];
+ }
+ function vclCondition(c, stage) {
+ const variable = vclVar(c.field, c.name, stage), values = c.values || [];
+ const one = value => {
+ if (c.field === "status") { const m = String(value).match(/^(\d)xx$/i); if (m) return `(${variable} >= ${m[1]}00 && ${variable} <= ${m[1]}99)`; const r = String(value).split("-"); if (r.length === 2) return `(${variable} >= ${r[0]} && ${variable} <= ${r[1]})`; return `${variable} == ${value}`; }
+ if (c.field === "client_ip") return `client.ip ~ ${c.ruleAcl || "rule_acl"} /* ${value} */`;
+ if (c.field === "extension") return `req.url ~ "\\.${reEsc(value)}(\\?|$)"`;
+ if (c.field === "query") return c.operator === "exists" ? `req.url ~ "[?&]${reEsc(c.name)}="` : `req.url ~ "[?&]${reEsc(c.name)}=${c.operator === "regex" ? value : reEsc(value)}${c.operator === "equals" ? "(&|$)" : ""}"`;
+ if (c.field === "cookie") return c.operator === "exists" ? `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}="` : `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}=${c.operator === "regex" ? value : `${reEsc(value)}(;|$)`}"`;
+ if (c.field === "path" && c.operator === "equals") return `req.url ~ "^${reEsc(value)}(\\?|$)"`;
+ switch (c.operator) {
+ case "equals": return `${variable} == "${esc(value)}"`;
+ case "prefix": return `${variable} ~ "^${esc(reEsc(value))}"`;
+ case "suffix": return `${variable} ~ "${esc(reEsc(value))}$"`;
+ case "contains": return `${variable} ~ "${esc(reEsc(value))}"`;
+ case "glob": return `${variable} ~ "^${esc(globRe(value))}$"`;
+ case "regex": return `${variable} ~ "${esc(value)}"`;
+ default: return variable;
+ }
+ };
+ let expr = c.operator === "exists" && !["query", "cookie"].includes(c.field) ? variable : values.length > 1 ? `(${values.map(one).join(" || ")})` : one(values[0] ?? "");
+ if (c.negate) expr = `!(${expr})`;
+ return expr;
+ }
+ function vclActions(rule) {
+ return rule.actions.map(a => {
+ switch (a.type) {
+ case "pass": return "return (pass);";
+ case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
+ case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
+ case "hash_header": return `hash_data(req.http.${a.name});`;
+ case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
+ case "ttl": return `set beresp.ttl = ${a.seconds ?? 0}s;`;
+ case "grace": return `set beresp.grace = ${a.seconds ?? 0}s;`;
+ case "no_store": return "set beresp.uncacheable = true;";
+ case "ignore_cache_control": return "unset beresp.http.Cache-Control;";
+ case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
+ case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
+ case "remove_header": return `unset resp.http.${a.name};`;
+ default: return `# ${a.type}`;
+ }
+ });
+ }
+ function ruleVcl(rule) {
+ const lines = vclActions(rule).flatMap(line => line.split("\n"));
+ const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
+ const joined = conditions.join(rule.match === "any" ? " ||\n " : " &&\n ");
+ const body = lines.map(line => ` ${line}`).join("\n");
+ const head = `# ${rule.name || rule.id}${rule.enabled === false ? " (disabled)" : ""}${rule.vhosts?.length ? ` · vhosts: ${rule.vhosts.join(", ")}` : ""}`;
+ return conditions.length ? `${head}\nif (${joined}) {\n${body}\n}` : `${head}\n${body.replace(/^ {4}/gm, "")}`;
+ }
+ function exportVcl(rules) {
+ const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
+ const blocks = ["vcl 4.1;", "# Generated by RustProxy cache rules (read-only preview)"];
+ const indent = text => text.replace(/^/gm, " ");
+ for (const stage of STAGES) {
+ const items = rules.filter(rule => rule.stage === stage);
+ const main = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
+ const hash = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
+ if (main.length) blocks.push(`\nsub ${subs[stage]} {\n${main.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
+ if (hash.length) blocks.push(`\nsub vcl_hash {\n${hash.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
+ }
+ return blocks.join("\n");
+ }
+ function summary(rule) {
+ const actions = rule.actions.map(a => {
+ if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
+ if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
+ if (a.type === "set_header" || a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
+ return actionLabel(a.type);
+ });
+ return actions.join(" · ");
+ }
+ function fmtDuration(seconds) {
+ seconds = Number(seconds) || 0;
+ for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
+ return `${seconds}s`;
+ }
+ const TEMPLATES = {
+ wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }],
+ static: () => [
+ { name: t("cacheRuleTplStaticCookies"), stage: "request", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }], actions: [{ type: "strip_cookies", keep: [] }] },
+ { name: t("cacheRuleTplStaticTtl"), stage: "response", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "ttl", seconds: 2592000 }, { type: "strip_set_cookie" }] },
+ ],
+ tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
+ api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
+ language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
+ notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
+ headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
+ };
+ function applicableGlobals(vhostId) {
+ return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
+ }
+ function aspects(rule) { return new Set(rule.actions.map(a => ASPECTS[a.type]).filter(Boolean)); }
+ function conflictsFor(vhostRules, globals) {
+ const notes = [];
+ for (const local of vhostRules.filter(rule => rule.enabled !== false)) {
+ const mine = aspects(local);
+ if (!mine.size) continue;
+ for (const global of globals) {
+ if (global.stage !== local.stage) continue;
+ const shared = [...aspects(normalize(global))].filter(aspect => mine.has(aspect));
+ if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
+ }
+ }
+ return notes;
+ }
+ function globalOverrideNotes(rule) {
+ const vhosts = envelope?.config?.vhosts || [], mine = aspects(rule), overriddenBy = [], skippedBy = [];
+ for (const vhost of vhosts) {
+ if (rule.vhosts?.length && !rule.vhosts.includes(vhost.id)) continue;
+ if (vhost.cache?.ignore_global_rules) { skippedBy.push(vhost.id); continue; }
+ if ((vhost.cache?.rules || []).some(local => local.enabled !== false && local.stage === rule.stage && [...aspects(normalize(local))].some(aspect => mine.has(aspect)))) overriddenBy.push(vhost.id);
+ }
+ const notes = [];
+ if (overriddenBy.length) notes.push(t("cacheRulesOverriddenIn").replace("{vhosts}", overriddenBy.join(", ")));
+ if (skippedBy.length) notes.push(t("cacheRulesIgnoredIn").replace("{vhosts}", skippedBy.join(", ")));
+ return notes;
+ }
+ let hits = {};
+ async function loadHits() {
+ if (!authenticated) return;
+ try { hits = (await api("/api/cache/rules/stats")).hits || {}; } catch { hits = {}; }
+ }
+ function select(values, current, label) {
+ const node = el("select"); for (const [value, text] of values) { const option = el("option", text); option.value = value; node.append(option); } node.value = current; if (label) node.setAttribute("aria-label", label); return node;
+ }
+ function textInput(value, placeholder = "", cls = "") { const node = el("input", undefined, cls); node.type = "text"; node.value = value ?? ""; node.placeholder = placeholder; node.spellcheck = false; return node; }
+ function durationInput(seconds, onChange) {
+ const wrap = el("span", undefined, "cache-rule-duration"), number = el("input"); number.type = "number"; number.min = 0; number.step = 1;
+ let unit = "s"; for (const [name, size] of [...durationUnits].reverse()) if ((seconds || 0) >= size && (seconds || 0) % size === 0) { unit = name; break; }
+ number.value = Math.round((seconds || 0) / Object.fromEntries(durationUnits)[unit]);
+ const units = select(durationUnits.map(([name]) => [name, t(`cacheRuleUnit${name.toUpperCase()}`)]), unit, t("cacheRuleDurationUnit"));
+ const emit = () => onChange(Math.max(0, Math.round(Number(number.value) || 0) * Object.fromEntries(durationUnits)[units.value]));
+ number.addEventListener("input", emit); units.addEventListener("change", emit);
+ wrap.append(number, units); return wrap;
+ }
+ function create(options = {}) {
+ const scope = options.scope === "vhost" ? "vhost" : "global", vhostId = options.vhostId || "";
+ let rules = (options.rules || []).map(normalize), open = new Set(), ignoreGlobal = !!options.ignoreGlobal;
+ const root = el("div", undefined, `cache-rules cache-rules-${scope}`);
+ const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
+ const toolbar = el("div", undefined, "cache-rules-toolbar");
+ if (scope === "vhost") { const docs = el("a", t("cacheRulesDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FCACHE.md§ion=cache-rules-vcl-style"; docs.target = "_blank"; docs.rel = "noopener noreferrer"; root.append(docs); }
+ const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
+ templates.classList.add("cache-rules-templates");
+ const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
+ const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
+ const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
+ toolbar.append(templates, importButton, exportButton, addButton);
+ const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; ignoreBox.id = "vh-cache-ignore-global-rules";
+ ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
+ const notices = el("div", undefined, "cache-rules-notices");
+ const list = el("div", undefined, "cache-rules-list");
+ const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty");
+ const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
+ const importText = document.createElement("textarea"); importText.rows = 10; importText.spellcheck = false; importText.placeholder = "sub vcl_recv {\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}";
+ const importRun = el("button", t("cacheRulesImportRun"), "primary"); importRun.type = "button";
+ const importCancel = el("button", t("cancel"), "outline"); importCancel.type = "button";
+ const importResult = el("div", undefined, "cache-rules-import-result");
+ const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importCancel);
+ importBox.append(el("p", t("cacheRulesImportHelp"), "fine"), importText, importActions, importResult);
+ const exportBox = el("details", undefined, "cache-rules-export"); const exportSummary = el("summary", t("cacheRulesVclPreview")); const exportPre = el("pre", "", "metrics-example mono cache-rules-vcl");
+ exportBox.append(exportSummary, exportPre);
+ const tester = buildTester();
+ root.append(toolbar);
+ if (scope === "vhost") root.append(ignoreWrap);
+ root.append(notices, importBox, list, empty, exportBox, tester.node);
+ for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
+ root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
+ function taken() { return new Set(rules.map(rule => rule.id)); }
+ function renderNotices() {
+ notices.replaceChildren();
+ if (scope !== "vhost") return;
+ const globals = applicableGlobals(vhostId);
+ if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; }
+ if (globals.length) notices.append(el("p", t("cacheRulesGlobalApply").replace("{count}", globals.length).replace("{names}", globals.slice(0, 6).map(rule => rule.name || rule.id).join(", ") + (globals.length > 6 ? "…" : "")), "fine"));
+ for (const note of conflictsFor(rules, globals)) notices.append(el("p", note, "fine cache-rules-notice"));
+ }
+ function render() {
+ list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index)));
+ empty.hidden = rules.length > 0;
+ addButton.disabled = rules.length >= MAX_RULES;
+ exportPre.textContent = exportVcl(rules);
+ renderNotices();
+ }
+ function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); }
+ function ruleCard(rule, index) {
+ const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index;
+ card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); });
+ card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
+ card.addEventListener("dragover", event => { event.preventDefault(); card.classList.add("is-drop"); });
+ card.addEventListener("dragleave", () => card.classList.remove("is-drop"));
+ card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); });
+ const head = el("div", undefined, "cache-rule-head");
+ const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag");
+ const toggle = el("input"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled"));
+ toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); });
+ const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none";
+ title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary"));
+ title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); });
+ const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`;
+ const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits");
+ const actions = el("span", undefined, "cache-rule-actions");
+ const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1));
+ const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1));
+ const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); });
+ const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); });
+ actions.append(up, down, copy, remove);
+ head.append(grip, toggle, title, hitCount, actions);
+ card.append(head);
+ if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
+ if (open.has(rule.id)) card.append(ruleEditor(rule));
+ return card;
+ }
+ function ruleEditor(rule) {
+ const body = el("div", undefined, "cache-rule-body");
+ const grid = el("div", undefined, "cache-rule-grid");
+ const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96;
+ name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); });
+ const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
+ id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
+ const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
+ stage.addEventListener("change", () => { rule.stage = stage.value; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
+ const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
+ match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
+ const stop = el("input"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
+ const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; };
+ const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop")));
+ grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
+ body.append(grid);
+ if (scope === "global") {
+ const vhostItems = (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, title: vhost.name || vhost.id, detail: (vhost.frontend?.hosts || []).slice(0, 3).join(", ") }));
+ const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
+ picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
+ picker.addEventListener("change", changed);
+ const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine"));
+ body.append(field);
+ }
+ const conditions = el("div", undefined, "cache-rule-section");
+ conditions.append(el("h4", t("cacheRuleConditions")));
+ const conditionRows = el("div", undefined, "cache-rule-rows");
+ rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
+ if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
+ const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button";
+ addCondition.disabled = rule.conditions.length >= 16;
+ addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
+ conditions.append(conditionRows, addCondition);
+ const actionsSection = el("div", undefined, "cache-rule-section");
+ actionsSection.append(el("h4", t("cacheRuleActions")));
+ const actionRows = el("div", undefined, "cache-rule-rows");
+ rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index)));
+ const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button";
+ addAction.disabled = rule.actions.length >= 16;
+ addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
+ actionsSection.append(actionRows, addAction);
+ const preview = el("pre", "", "metrics-example mono cache-rule-vcl");
+ const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); };
+ body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview);
+ const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview);
+ body.append(conditions, actionsSection, previewWrap);
+ syncPreview();
+ return body;
+ }
+ function conditionRow(rule, condition, index) {
+ const row = el("div", undefined, "cache-rule-row");
+ const fields = Object.keys(FIELDS).filter(field => FIELDS[field].stages.includes(rule.stage));
+ const field = select(fields.map(value => [value, fieldLabel(value)]), condition.field, t("cacheRuleField"));
+ const name = textInput(condition.name, t("cacheRuleNamePlaceholderField"), "cache-rule-name"); name.hidden = !FIELDS[condition.field].name;
+ const ops = FIELDS[condition.field].ops;
+ if (!ops.includes(condition.operator)) condition.operator = ops[0];
+ const operator = select(ops.map(value => [value, opLabel(value)]), condition.operator, t("cacheRuleOperator"));
+ const values = textInput((condition.values || []).join(", "), t(`cacheRuleValuesPlaceholder${condition.field === "status" ? "Status" : condition.field === "client_ip" ? "Cidr" : condition.field === "extension" ? "Extension" : condition.field === "method" ? "Method" : ""}`), "cache-rule-values");
+ values.hidden = condition.operator === "exists";
+ const negateLabel = el("label", undefined, "check cache-rule-negate"), negate = el("input"); negate.type = "checkbox"; negate.checked = !!condition.negate; negateLabel.append(negate, el("span", t("cacheRuleNegate")));
+ const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove"));
+ field.addEventListener("change", () => { condition.field = field.value; condition.operator = FIELDS[field.value].ops[0]; if (!FIELDS[field.value].name) delete condition.name; render(); changed(); });
+ name.addEventListener("input", () => { condition.name = name.value.trim(); changed(); });
+ operator.addEventListener("change", () => { condition.operator = operator.value; if (operator.value === "exists") condition.values = []; render(); changed(); });
+ values.addEventListener("input", () => { condition.values = operator.value === "regex" ? [values.value.trim()].filter(Boolean) : splitList(values.value); changed(); });
+ negate.addEventListener("change", () => { condition.negate = negate.checked; changed(); });
+ remove.addEventListener("click", () => { rule.conditions.splice(index, 1); render(); changed(); });
+ row.append(field, name, operator, values, negateLabel, remove);
+ return row;
+ }
+ function actionRow(rule, action, index) {
+ const row = el("div", undefined, "cache-rule-row");
+ const type = select(ACTIONS[rule.stage].map(value => [value, actionLabel(value)]), action.type, t("cacheRuleAction"));
+ const params = el("span", undefined, "cache-rule-params");
+ const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1;
+ type.addEventListener("change", () => { rule.actions[index] = { type: type.value }; render(); changed(); });
+ remove.addEventListener("click", () => { rule.actions.splice(index, 1); render(); changed(); });
+ const listInput = (key, placeholder) => { const node = textInput((action[key] || []).join(", "), placeholder); node.addEventListener("input", () => { action[key] = splitList(node.value); changed(); }); return node; };
+ const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; };
+ switch (action.type) {
+ case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break;
+ case "strip_query": {
+ const keepOnly = el("label", undefined, "check"), box = el("input"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly")));
+ box.addEventListener("change", () => { action.keep_only = box.checked; changed(); });
+ params.append(listInput("params", t("cacheRuleQueryParams")), keepOnly); break;
+ }
+ case "hash_header": params.append(nameInput("Accept-Language")); break;
+ case "hash_cookie": params.append(nameInput("lang")); break;
+ case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
+ case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
+ case "remove_header": params.append(nameInput("X-Powered-By")); break;
+ default: params.append(el("small", t(`cacheRuleActionHelp${action.type.split("_").map(p => p[0].toUpperCase() + p.slice(1)).join("")}`), "fine"));
+ }
+ row.append(type, params, remove);
+ return row;
+ }
+ function buildTester() {
+ const node = el("details", undefined, "cache-rules-tester");
+ node.append(el("summary", t("cacheRulesTester")));
+ const grid = el("div", undefined, "cache-rules-tester-grid");
+ const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
+ const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
+ const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...(envelope?.config?.vhosts || []).map(vhost => [vhost.id, vhost.name || vhost.id])], vhostId, t("cacheRulesTesterVhost"));
+ const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
+ const clientIp = textInput("", "203.0.113.10", "mono");
+ const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
+ const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 3; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
+ const run = el("button", t("cacheRulesTesterRun"), "primary"); run.type = "button";
+ const result = el("div", undefined, "cache-rules-tester-result");
+ const field = (key, control) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); return label; };
+ grid.append(field("cacheRuleFieldMethod", method), field("cacheRulesTesterUrl", url));
+ if (scope === "global") grid.append(field("cacheRulesTesterVhost", vhostSelect));
+ grid.append(field("cacheRulesTesterHeaders", headers), field("cacheRuleFieldClientIp", clientIp), field("cacheRuleFieldStatus", status), field("cacheRulesTesterResponseHeaders", responseHeaders));
+ const pairs = text => String(text || "").split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => { const at = line.indexOf(":"); return at > 0 ? [line.slice(0, at).trim(), line.slice(at + 1).trim()] : [line, ""]; });
+ run.addEventListener("click", async () => {
+ run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
+ try {
+ const body = { request: { method: method.value, url: url.value.trim(), headers: pairs(headers.value), client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
+ if (scope === "global") { body.global_rules = read(); body.vhost_id = vhostSelect.value || null; }
+ else { body.vhost_id = vhostId || null; body.vhost_rules = read(); body.ignore_global_rules = ignoreGlobal; if (!vhostId) body.vhost_id = null; }
+ renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(body) }));
+ } catch (error) { result.replaceChildren(el("p", error.message, "fine is-error")); }
+ finally { run.disabled = false; }
+ });
+ function renderResult(data) {
+ const items = [];
+ const line = (label, value, cls = "") => { const row = el("div", undefined, `cache-rules-result-line ${cls}`.trim()); row.append(el("span", label, "fine"), el("strong", value)); items.push(row); };
+ const names = matched => (matched || []).map(item => `${item.name || item.id} (${item.origin === "vhost" ? t("cacheRulesOriginVhost") : t("cacheRulesOriginGlobal")})`).join(", ") || "—";
+ const request = data.request || {};
+ line(t("cacheRulesResultDecision"), request.cacheable ? (data.response?.stored ? t("cacheRulesResultHit").replace("{ttl}", fmtDuration(data.response.ttl)).replace("{grace}", fmtDuration(data.response.grace)) : t("cacheRulesResultNotStored").replace("{reason}", data.response?.reason || "-")) : t("cacheRulesResultPass").replace("{reason}", request.reason || "-"), request.cacheable && data.response?.stored ? "is-ok" : "is-warn");
+ line(t("cacheRulesResultRequest"), names(request.matched));
+ line(t("cacheRulesResultKey"), `${data.host || "-"}${request.target || ""}${request.variant?.length ? ` + ${request.variant.join(", ")}` : ""}`);
+ if (request.cookie != null) line(t("cacheRulesResultCookie"), request.cookie || "—");
+ if (data.response) line(t("cacheRulesResultResponse"), names(data.response.matched));
+ if (data.deliver) line(t("cacheRulesResultDeliver"), [...(data.deliver.set || []).map(([k, v]) => `${k}: ${v}`), ...(data.deliver.remove || []).map(k => `−${k}`)].join(", ") || "—");
+ for (const item of [...(request.overridden || []), ...(data.response?.overridden || [])]) line(t("cacheRulesResultOverridden"), t("cacheRulesResultOverriddenText").replace("{winner}", item.winner).replace("{ignored}", item.ignored).replace("{aspect}", t(`cacheRuleAspect${item.aspect[0].toUpperCase()}${item.aspect.slice(1)}`)), "is-warn");
+ result.replaceChildren(...items);
+ }
+ const actions = el("div", undefined, "form-actions"); actions.append(run);
+ node.append(el("p", t("cacheRulesTesterHelp"), "fine"), grid, actions, result);
+ return { node };
+ }
+ function addRules(items) {
+ const ids = taken(); let added = 0;
+ for (const item of items) {
+ if (rules.length >= MAX_RULES) { toast(t("cacheRulesLimit"), true); break; }
+ const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
+ ids.add(rule.id); rules.push(rule); added++;
+ }
+ render(); if (added) changed();
+ return added;
+ }
+ templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); });
+ addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
+ importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (!importBox.hidden) importText.focus(); });
+ importCancel.addEventListener("click", () => { importBox.hidden = true; importResult.replaceChildren(); });
+ importRun.addEventListener("click", async () => {
+ importRun.disabled = true; importResult.replaceChildren();
+ try {
+ const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: importText.value }) });
+ const added = addRules(data.rules || []);
+ importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
+ if (data.warnings?.length) { const list = el("ul", undefined, "cache-rules-warnings"); for (const warning of data.warnings) list.append(el("li", warning)); importResult.append(el("p", t("cacheRulesImportWarnings"), "fine"), list); }
+ } catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
+ finally { importRun.disabled = false; }
+ });
+ exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
+ ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
+ function read() {
+ for (const rule of rules) {
+ if (!rule.actions.length) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
+ for (const c of rule.conditions) {
+ if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
+ if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
+ }
+ for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
+ }
+ return rules.map(rule => clean(rule, scope === "global"));
+ }
+ render();
+ void loadHits().then(render);
+ return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits: () => loadHits().then(render) };
+ }
+ return { create, exportVcl, TEMPLATES };
+})();
diff --git a/src/admin/web/certificate-api.js b/src/admin/web/certificate-api.js
index 2bdeb79..a385046 100644
--- a/src/admin/web/certificate-api.js
+++ b/src/admin/web/certificate-api.js
@@ -1,55 +1,101 @@
"use strict";
(() => {
+ const MAX_IDS = 32, ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
let certificateApiState = null, certificateApiLoading = false;
- let certificateApiEditingKey = null, certificateApiDetailsKey = null;
+ let certificateApiEditingKey = null, certificateApiPicker = null;
function certificateApiCredentials() {
const values = certificateApiState?.credentials;
if (Array.isArray(values)) return values;
if (certificateApiState?.configured && certificateApiState?.key_id) return [{ key_id: certificateApiState.key_id, comment: "", created_at: certificateApiState.created_at, last_used_at: certificateApiState.last_used_at }];
return [];
}
+ const storedCertificates = () => envelope?.config?.tls?.certificates || [];
+ const certificateById = id => storedCertificates().find(cert => cert.id === id);
+ function certificateHosts(cert) {
+ const inventory = typeof certificateInventory !== "undefined" && certificateInventory instanceof Map ? certificateInventory.get(cert.id) : null;
+ const names = inventory?.covered_hosts?.length ? inventory.covered_hosts : cert.covered_hosts?.length ? cert.covered_hosts : cert.hosts || [];
+ return names.map(String);
+ }
+ function pickerItems() {
+ return storedCertificates().map(cert => {
+ const names = certificateHosts(cert), managed = !!cert.issuer;
+ return {
+ id: cert.id, title: cert.id,
+ detail: `${names.slice(0, 4).join(", ")}${names.length > 4 ? ` +${names.length - 4}` : ""}${managed ? ` · ${t("certificateApiManagedReloadOnly")}` : ""}`,
+ search: names.join(" "), badge: managed ? "ACME" : "", badgeClass: "is-allow",
+ };
+ });
+ }
+ function createPicker(selected) {
+ const host = $("certificate-api-certificates");
+ certificateApiPicker = window.rustProxyChoicePicker.create({
+ className: "certificate-api-picker", selected, items: pickerItems(), limit: MAX_IDS, unknownDetail: "certificateApiCertificateNew",
+ labels: { choose: "certificateApiPickerChoose", selected: "certificateApiPickerSelected", none: "certificateApiPickerNone", search: "certificateApiPickerSearch", addHint: "certificateApiPickerAddHint", empty: "certificateApiPickerEmpty" },
+ custom: raw => {
+ const id = String(raw || "").trim(); if (!id) return null;
+ if (id === "*") throw new Error(t("certificateApiWildcardNotAllowed"));
+ if (!ID_PATTERN.test(id)) throw new Error(t("certificateApiCertificateIdInvalid").replace("{id}", id));
+ return { id, title: id, detail: certificateById(id) ? "" : t("certificateApiCertificateNew") };
+ },
+ });
+ certificateApiPicker.addEventListener("choicechange", syncCertificateHelp);
+ certificateApiPicker.addEventListener("choicechange", certificateApiExample);
+ host.replaceChildren(certificateApiPicker);
+ }
+ const selectedIds = () => certificateApiPicker?.read?.() || [];
+ const deployMode = () => $("certificate-api-allow-deploy").checked;
+ function syncCertificateHelp() {
+ const deploy = deployMode(), managed = selectedIds().filter(id => certificateById(id)?.issuer);
+ let text = t(deploy ? "certificateApiCertificatesDeployHelp" : "certificateApiCertificatesReloadHelp");
+ if (deploy && managed.length) text += ` ${t("certificateApiManagedWarning").replace("{ids}", managed.join(", "))}`;
+ $("certificate-api-certificates-help").textContent = text;
+ }
function clearCertificateApiSecret() {
$("certificate-api-secret").textContent = "";
$("certificate-api-secret-wrap").hidden = true;
}
- function showCertificateApiSecret(token) {
+ function showCertificateApiSecret(token, keyId) {
$("certificate-api-secret").textContent = token;
+ $("certificate-api-secret-title").textContent = t("certificateApiSecretTitle").replace("{key}", keyId || "");
$("certificate-api-secret-wrap").hidden = !token;
+ if (token) $("certificate-api-secret-wrap").scrollIntoView?.({ block: "nearest", behavior: "smooth" });
}
- function resetCertificateApiForm() {
+ function closeEditor() {
certificateApiEditingKey = null;
- $("certificate-api-key-id").value = "";
- $("certificate-api-key-id").readOnly = false;
- $("certificate-api-comment").value = "";
- $("certificate-api-certificate-ids").value = "";
- $("certificate-api-allow-deploy").checked = false;
- $("certificate-api-token").value = "";
- $("certificate-api-token-field").hidden = false;
- $("certificate-api-edit-note").hidden = true;
- $("certificate-api-cancel-edit").hidden = true;
- const submit = $("certificate-api-save");
- submit.dataset.i18n = "certificateApiRotate";
- submit.textContent = t("certificateApiRotate");
+ const form = $("certificate-api-form");
+ form.hidden = true;
+ $("certificate-api-card").insertBefore(form, $("certificate-api-credentials"));
+ $("certificate-api-new").disabled = false;
certificateApiExample();
}
- function beginCertificateApiEdit(credential) {
- certificateApiEditingKey = credential.key_id;
- certificateApiDetailsKey = credential.key_id;
- $("certificate-api-key-id").value = credential.key_id;
- $("certificate-api-key-id").readOnly = true;
- $("certificate-api-comment").value = credential.comment || "";
- $("certificate-api-certificate-ids").value = (credential.certificate_ids || []).join("\n");
- $("certificate-api-allow-deploy").checked = !!credential.allow_deploy;
+ function openEditor(credential = null) {
+ clearCertificateApiSecret();
+ certificateApiEditingKey = credential?.key_id || null;
+ const editing = !!credential, form = $("certificate-api-form");
+ $("certificate-api-editor-title").textContent = editing ? t("certificateApiEditTitle").replace("{key}", credential.key_id) : t("certificateApiNewTitle");
+ $("certificate-api-key-id").value = credential?.key_id || "";
+ $("certificate-api-key-id").readOnly = editing;
+ $("certificate-api-key-id").closest("label").hidden = editing;
+ $("certificate-api-comment").value = credential?.comment || "";
+ $("certificate-api-allow-deploy").checked = !!credential?.allow_deploy;
+ $("certificate-api-mode-reload").checked = !credential?.allow_deploy;
$("certificate-api-token").value = "";
- $("certificate-api-token-field").hidden = true;
- $("certificate-api-edit-note").hidden = false;
- $("certificate-api-cancel-edit").hidden = false;
- const submit = $("certificate-api-save");
- submit.dataset.i18n = "certificateApiSave";
- submit.textContent = t("certificateApiSave");
+ $("certificate-api-token-field").hidden = editing;
+ $("certificate-api-token-field").open = false;
+ $("certificate-api-edit-note").hidden = !editing;
+ const ids = credential?.certificate_ids || [], legacy = ids.includes("*");
+ $("certificate-api-legacy-note").textContent = legacy ? t("certificateApiLegacyWildcard") : "";
+ $("certificate-api-legacy-note").hidden = !legacy;
+ createPicker(ids.filter(id => id !== "*"));
+ syncCertificateHelp();
+ $("certificate-api-save").textContent = t(editing ? "certificateApiSave" : "certificateApiCreate");
+ const anchor = editing ? $("certificate-api-credentials").querySelector(`[data-key-id="${CSS.escape(credential.key_id)}"]`) : null;
+ if (anchor) anchor.append(form); else $("certificate-api-card").insertBefore(form, $("certificate-api-credentials"));
+ form.hidden = false;
+ $("certificate-api-new").disabled = !editing;
certificateApiExample();
- $("certificate-api-form").scrollIntoView?.({ block: "start", behavior: "smooth" });
- $("certificate-api-comment").focus?.();
+ form.scrollIntoView?.({ block: "nearest", behavior: "smooth" });
+ (editing ? $("certificate-api-comment") : $("certificate-api-key-id")).focus?.();
}
function setCertificateApiCredential(credential) {
if (!certificateApiState) return;
@@ -60,42 +106,28 @@
certificateApiState.configured = certificateApiState.credentials.length > 0;
}
function certificateApiExample() {
- const key = $("certificate-api-key-id").value.trim() || certificateApiCredentials()[0]?.key_id || "certbot-main";
- const enteredIds = $("certificate-api-certificate-ids").value.split(/[\n,]+/).map(value => value.trim()).filter(Boolean);
- const selected = enteredIds[0] || certificateApiCredentials()[0]?.certificate_ids?.find(value => value !== "*") || "CERTIFICATE_ID";
- const reload = `curl --fail --show-error --request POST \
- --header 'Authorization: Bearer $RUSTPROXY_CERT_TOKEN' \
- --header 'X-RustProxy-Certificate-Key: ${key}' \
+ const editing = !$("certificate-api-form").hidden;
+ const current = certificateApiCredentials()[0];
+ const key = (editing && $("certificate-api-key-id").value.trim()) || current?.key_id || "opnsense-acme";
+ const ids = editing ? selectedIds() : (current?.certificate_ids || []).filter(id => id !== "*");
+ const selected = ids[0] || "CERTIFICATE_ID", deploy = editing ? deployMode() : !!current?.allow_deploy;
+ const reload = `curl --fail --show-error --request POST \\
+ --header "Authorization: Bearer $RUSTPROXY_CERT_TOKEN" \\
+ --header 'X-RustProxy-Certificate-Key: ${key}' \\
${location.origin}/api/certificates/${selected}/reload`;
- if (!$("certificate-api-allow-deploy").checked) {
- $("certificate-api-curl").textContent = reload;
- return;
- }
- $("certificate-api-curl").textContent = `${reload}
+ $("certificate-api-curl").textContent = deploy ? `${reload}
-# Optional higher-privilege deploy for the same allowlisted certificate IDs:
-curl --fail --show-error --request POST \
- --header 'Authorization: Bearer $RUSTPROXY_CERT_TOKEN' \
- --header 'X-RustProxy-Certificate-Key: ${key}' \
- --header 'Content-Type: application/json' \
- --data @deploy.json \
- ${location.origin}/api/certificates/deploy`;
+curl --fail --show-error --request POST \\
+ --header "Authorization: Bearer $RUSTPROXY_CERT_TOKEN" \\
+ --header 'X-RustProxy-Certificate-Key: ${key}' \\
+ --header 'Content-Type: application/json' \\
+ --data '{"certificate_id":"${selected}","cert_pem":"…","key_pem":"…"}' \\
+ ${location.origin}/api/certificates/deploy` : reload;
}
- function certificateApiDetailNode(credential) {
- const detail = el("div", undefined, "certificate-api-details");
- const item = (label, value) => {
- const line = el("div", undefined, "certificate-api-detail-line");
- line.append(el("span", `${label}:`, "fine"), el("strong", String(value), "mono"));
- detail.append(line);
- };
- item(t("certificateApiKeyId"), credential.key_id);
- item(t("certificateApiComment"), credential.comment || "-");
- item(t("certificateApiCreatedAt"), formatDateTime(Number(credential.created_at) * 1000));
- item(t("certificateApiLastUsed"), credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed"));
- item(t("certificateApiPermissions"), credential.allow_deploy ? t("certificateApiScopeDeployReload") : t("certificateApiScopeReloadOnly"));
- item(t("certificateApiCertificateIds"), (credential.certificate_ids || []).join(", "));
- item(t("certificateApiTokenLabel"), t("certificateApiTokenHidden"));
- return detail;
+ function certificateChip(id) {
+ const cert = certificateById(id), chip = el("span", id, `certificate-api-chip${cert ? "" : " is-new"}${cert?.issuer ? " is-managed" : ""}`);
+ chip.title = id === "*" ? t("certificateApiLegacyWildcardShort") : cert ? certificateHosts(cert).join(", ") || id : t("certificateApiCertificateNew");
+ return chip;
}
function renderCertificateApi() {
const state = certificateApiState, target = $("certificate-api-credentials");
@@ -103,75 +135,67 @@ curl --fail --show-error --request POST \
const credentials = certificateApiCredentials(), max = Number(state.max_credentials) || 32;
$("certificate-api-status").textContent = credentials.length
? t("certificateApiConfiguredCount").replace("{count}", credentials.length).replace("{max}", max)
- : t("certificateApiDisabled");
+ : t("certificateApiEmpty");
$("certificate-api-revoke-all").disabled = !credentials.length;
- if (target) {
- target.replaceChildren();
- for (const credential of credentials) {
- const container = el("div", undefined, "certificate-api-credential-item");
- const row = el("div", undefined, "certificate-api-credential-row");
- const info = el("div", undefined, "certificate-api-credential-info");
- info.append(el("b", credential.key_id || "-", "mono"));
- if (credential.comment) info.append(el("span", credential.comment, "fine"));
- const scope = credential.allow_deploy ? t("certificateApiScopeDeployReload") : t("certificateApiScopeReloadOnly");
- const ids = Array.isArray(credential.certificate_ids) ? credential.certificate_ids.join(", ") : "-";
- info.append(el("span", `${scope} · ${t("certificateApiAllowedIds")}: ${ids}`, "fine mono"));
- const lastUsed = credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed");
- info.append(el("span", `${t("certificateApiLastUsed")}: ${lastUsed}`, "fine"));
- const actions = el("div", undefined, "certificate-api-row-actions");
- const path = `/api/certificate-api/${encodeURIComponent(credential.key_id)}`;
- const preview = action(t(certificateApiDetailsKey === credential.key_id ? "certificateApiHide" : "certificateApiView"), async () => {
- if (certificateApiDetailsKey === credential.key_id) { certificateApiDetailsKey = null; renderCertificateApi(); return; }
- preview.disabled = true;
- clearCertificateApiSecret();
- try {
- const data = await api(path);
- setCertificateApiCredential(data.credential);
- certificateApiDetailsKey = credential.key_id;
- renderCertificateApi();
- } catch (error) { toast(error.message, true); preview.disabled = false; }
- });
- const edit = action(t("certificateApiEdit"), async () => {
- edit.disabled = true;
- clearCertificateApiSecret();
- try {
- const data = await api(path);
- setCertificateApiCredential(data.credential);
- beginCertificateApiEdit(data.credential);
- renderCertificateApi();
- } catch (error) { toast(error.message, true); edit.disabled = false; }
- });
- const regenerate = action(t("certificateApiRegenerate"), async () => {
- if (!await appConfirm(t("certificateApiRegenerateConfirm").replace("{key}", credential.key_id), { danger: true })) return;
- regenerate.disabled = true;
- clearCertificateApiSecret();
- try {
- const data = await api(`${path}/regenerate`, { method: "POST" });
- setCertificateApiCredential(data.credential);
- showCertificateApiSecret(data.token || "");
- renderCertificateApi();
- toast(t("certificateApiRegenerated"));
- } catch (error) { toast(error.message, true); regenerate.disabled = false; }
- });
- const remove = action(t("certificateApiRevoke"), async () => {
- if (!await appConfirm(t("certificateApiRevokeOneConfirm").replace("{key}", credential.key_id), { danger: true })) return;
- remove.disabled = true;
- try {
- await api(path, { method: "DELETE" });
- certificateApiState.credentials = certificateApiCredentials().filter(value => value.key_id !== credential.key_id);
- certificateApiState.configured = certificateApiState.credentials.length > 0;
- if (certificateApiEditingKey === credential.key_id) resetCertificateApiForm();
- if (certificateApiDetailsKey === credential.key_id) certificateApiDetailsKey = null;
- clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
- } catch (error) { toast(error.message, true); remove.disabled = false; }
- });
- remove.classList.add("danger");
- actions.append(preview, edit, regenerate, remove);
- row.append(info, actions);
- container.append(row);
- if (certificateApiDetailsKey === credential.key_id) container.append(certificateApiDetailNode(credential));
- target.append(container);
- }
+ $("certificate-api-new").disabled = credentials.length >= max || ($("certificate-api-form").hidden === false && !certificateApiEditingKey);
+ const form = $("certificate-api-form"), editingForm = !form.hidden && certificateApiEditingKey;
+ if (editingForm) $("certificate-api-card").insertBefore(form, target);
+ target.replaceChildren();
+ for (const credential of credentials) {
+ const container = el("div", undefined, "certificate-api-credential-item"); container.dataset.keyId = credential.key_id;
+ const row = el("div", undefined, "certificate-api-credential-row");
+ const info = el("div", undefined, "certificate-api-credential-info");
+ const title = el("div", undefined, "certificate-api-credential-title");
+ title.append(el("b", credential.key_id || "-", "mono"));
+ title.append(el("span", t(credential.allow_deploy ? "certificateApiScopeDeployReload" : "certificateApiScopeReloadOnly"), `pill ${credential.allow_deploy ? "warn" : "live"}`));
+ if (credential.comment) title.append(el("span", credential.comment, "fine"));
+ const chips = el("div", undefined, "certificate-api-chips");
+ const ids = Array.isArray(credential.certificate_ids) ? credential.certificate_ids : [];
+ if (ids.length) ids.forEach(id => chips.append(certificateChip(id))); else chips.append(el("span", "-", "fine"));
+ const created = credential.created_at ? formatDateTime(Number(credential.created_at) * 1000) : "-";
+ const lastUsed = credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed");
+ info.append(title, chips, el("span", `${t("certificateApiCreatedAt")}: ${created} · ${t("certificateApiLastUsed")}: ${lastUsed}`, "fine"));
+ if (ids.includes("*")) info.append(el("span", t("certificateApiLegacyWildcardShort"), "fine certificate-api-legacy"));
+ const actions = el("div", undefined, "certificate-api-row-actions");
+ const path = `/api/certificate-api/${encodeURIComponent(credential.key_id)}`;
+ const edit = action(t("certificateApiEdit"), async () => {
+ if (certificateApiEditingKey === credential.key_id && !$("certificate-api-form").hidden) { closeEditor(); return; }
+ edit.disabled = true;
+ try {
+ const data = await api(path);
+ setCertificateApiCredential(data.credential);
+ renderCertificateApi();
+ openEditor(data.credential);
+ } catch (error) { toast(error.message, true); edit.disabled = false; }
+ });
+ const regenerate = action(t("certificateApiRegenerate"), async () => {
+ if (!await appConfirm(t("certificateApiRegenerateConfirm").replace("{key}", credential.key_id), { danger: true })) return;
+ regenerate.disabled = true;
+ try {
+ const data = await api(`${path}/regenerate`, { method: "POST" });
+ setCertificateApiCredential(data.credential);
+ closeEditor(); renderCertificateApi();
+ showCertificateApiSecret(data.token || "", credential.key_id);
+ toast(t("certificateApiRegenerated"));
+ } catch (error) { toast(error.message, true); regenerate.disabled = false; }
+ });
+ const remove = action(t("certificateApiRevoke"), async () => {
+ if (!await appConfirm(t("certificateApiRevokeOneConfirm").replace("{key}", credential.key_id), { danger: true })) return;
+ remove.disabled = true;
+ try {
+ await api(path, { method: "DELETE" });
+ certificateApiState.credentials = certificateApiCredentials().filter(value => value.key_id !== credential.key_id);
+ certificateApiState.configured = certificateApiState.credentials.length > 0;
+ if (certificateApiEditingKey === credential.key_id) closeEditor();
+ clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
+ } catch (error) { toast(error.message, true); remove.disabled = false; }
+ });
+ remove.classList.add("danger");
+ actions.append(edit, regenerate, remove);
+ row.append(info, actions);
+ container.append(row);
+ target.append(container);
+ if (editingForm && certificateApiEditingKey === credential.key_id) container.append(form);
}
certificateApiExample();
}
@@ -189,16 +213,18 @@ curl --fail --show-error --request POST \
try {
const keyId = $("certificate-api-key-id").value.trim();
const comment = $("certificate-api-comment").value.trim();
- const certificateIds = $("certificate-api-certificate-ids").value.split(/[\n,]+/).map(value => value.trim()).filter(Boolean);
- if (!certificateIds.length) throw fieldError($("certificate-api-certificate-ids"), t("certificateApiCertificateIdsRequired"));
- const allowDeploy = $("certificate-api-allow-deploy").checked;
+ const certificateIds = selectedIds();
+ const pickerNode = $("certificate-api-certificates");
+ if (!certificateApiEditingKey && keyId && !/^[A-Za-z0-9_-]{3,64}$/.test(keyId)) throw fieldError($("certificate-api-key-id"), t("certificate_api.invalid_key_id"));
+ if (!certificateIds.length) throw fieldError(pickerNode, t("certificateApiCertificateIdsRequired"));
+ if (certificateIds.length > MAX_IDS) throw fieldError(pickerNode, t("certificateApiCertificateIdsTooMany"));
+ const allowDeploy = deployMode();
if (certificateApiEditingKey) {
const result = await api(`/api/certificate-api/${encodeURIComponent(certificateApiEditingKey)}`, {
method: "PATCH", body: JSON.stringify({ comment, certificate_ids: certificateIds, allow_deploy: allowDeploy })
});
setCertificateApiCredential(result.credential);
- resetCertificateApiForm();
- renderCertificateApi();
+ closeEditor(); renderCertificateApi();
toast(t("certificateApiSaved"));
} else {
const token = $("certificate-api-token").value.trim();
@@ -206,37 +232,39 @@ curl --fail --show-error --request POST \
method: "PUT", body: JSON.stringify({ key_id: keyId || null, token: token || null, comment, certificate_ids: certificateIds, allow_deploy: allowDeploy })
});
certificateApiState = { ...result }; delete certificateApiState.token; delete certificateApiState.credential;
- resetCertificateApiForm();
- showCertificateApiSecret(result.token || "");
- renderCertificateApi();
+ closeEditor(); renderCertificateApi();
+ showCertificateApiSecret(result.token || "", result.credential?.key_id || keyId);
toast(t("certificateApiRotated"));
}
} catch (error) { showFieldError(error, $("certificate-api-form")); toast(error.message, true); }
finally { button.disabled = false; }
});
- $("certificate-api-cancel-edit").addEventListener("click", resetCertificateApiForm);
+ $("certificate-api-new").addEventListener("click", () => openEditor(null));
+ $("certificate-api-cancel-edit").addEventListener("click", () => { closeEditor(); renderCertificateApi(); });
+ $("certificate-api-secret-copy").addEventListener("click", async () => {
+ const value = $("certificate-api-secret").textContent;
+ try { await navigator.clipboard.writeText(value); toast(t("copied")); }
+ catch { const range = document.createRange(); range.selectNodeContents($("certificate-api-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
+ });
$("certificate-api-revoke-all").addEventListener("click", async () => {
if (!await appConfirm(t("certificateApiRevokeAllConfirm"), { danger: true })) return;
const button = $("certificate-api-revoke-all"); button.disabled = true;
try {
await api("/api/certificate-api", { method: "DELETE" });
certificateApiState = { configured: false, credentials: [], max_credentials: certificateApiState?.max_credentials || 32, scopes: certificateApiState?.scopes || [] };
- certificateApiDetailsKey = null;
- resetCertificateApiForm(); clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
+ closeEditor(); clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
} catch (error) { toast(error.message, true); }
finally { button.disabled = false; }
});
$("certificate-api-key-id").addEventListener("input", certificateApiExample);
- $("certificate-api-certificate-ids").addEventListener("input", certificateApiExample);
- $("certificate-api-allow-deploy").addEventListener("change", certificateApiExample);
+ for (const id of ["certificate-api-allow-deploy", "certificate-api-mode-reload"]) $(id).addEventListener("change", () => { syncCertificateHelp(); certificateApiExample(); });
window.rustProxyCertificateApi = {
render: renderCertificateApi,
load: loadCertificateApi,
reset() {
certificateApiState = null;
certificateApiLoading = false;
- certificateApiDetailsKey = null;
- resetCertificateApiForm();
+ closeEditor();
clearCertificateApiSecret();
$("certificate-api-credentials").replaceChildren();
}
diff --git a/src/admin/web/css/00-tokens.css b/src/admin/web/css/00-tokens.css
index 983df64..f359ce2 100644
--- a/src/admin/web/css/00-tokens.css
+++ b/src/admin/web/css/00-tokens.css
@@ -79,6 +79,9 @@
--traffic-h2: var(--chart-secondary);
--traffic-h3: var(--chart-tertiary);
--ui-scale: 1;
+ --rp-vw: calc(1vw / var(--ui-scale, 1));
+ --rp-vh: calc(1vh / var(--ui-scale, 1));
+ --rp-dvh: calc(1dvh / var(--ui-scale, 1));
--ui-field-font-size: 12px;
--ui-field-pad-y: 6px;
--ui-field-pad-x: 8px;
diff --git a/src/admin/web/css/10-base.css b/src/admin/web/css/10-base.css
index faa9938..711d131 100644
--- a/src/admin/web/css/10-base.css
+++ b/src/admin/web/css/10-base.css
@@ -153,7 +153,7 @@ html[data-interface-icons="true"] .nav>span:first-of-type,
h1 {
margin: 0;
- font-size: calc(clamp(32px, 3.6vw, 52px));
+ font-size: calc(clamp(32px, calc(3.6 * var(--rp-vw)), 52px));
line-height: 1.1;
font-weight: 520;
letter-spacing: -2px;
@@ -566,7 +566,7 @@ button.is-saving {
position: fixed;
bottom: 26px;
right: 26px;
- max-width: calc(min(580px, 100vw - 40px));
+ max-width: calc(min(580px, calc(100 * var(--rp-vw)) - 40px));
background: var(--toast-bg);
color: var(--toast-text);
border: 1px solid var(--toast-line);
@@ -759,7 +759,7 @@ progress::-moz-progress-bar {
#pool-search,
#bo-search {
- width: calc(min(250px, 30vw));
+ width: calc(min(250px, calc(30 * var(--rp-vw))));
min-width: 170px;
}
@@ -769,7 +769,7 @@ progress::-moz-progress-bar {
inset: auto 18px 18px auto;
margin: 0;
width: max-content;
- max-width: calc(min(520px, 100vw - 28px));
+ max-width: calc(min(520px, calc(100 * var(--rp-vw)) - 28px));
padding: 12px 16px;
color: var(--text);
background: var(--panel);
@@ -796,11 +796,11 @@ progress::-moz-progress-bar {
background: var(--bg);
border: 1px solid var(--line);
padding: 0;
- max-width: calc(100vw - 24px);
+ max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
box-shadow: 0 18px 70px var(--shadow-strong);
border-radius: var(--rp-radius-surface, 7px);
- width: calc(min(1040px, 100vw - 24px));
- max-height: calc(100dvh - 28px);
+ width: calc((calc(min(1040px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
overflow: hidden;
}
@@ -809,11 +809,11 @@ progress::-moz-progress-bar {
background: var(--bg);
border: 1px solid var(--line);
padding: 0;
- max-width: calc(100vw - 24px);
- max-height: calc(100dvh - 28px);
+ max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
box-shadow: 0 18px 70px var(--shadow-strong);
border-radius: var(--rp-radius-surface, 7px);
- width: 1180px;
+ width: calc((1180px) / var(--ui-scale, 1));
overflow: visible;
}
@@ -822,11 +822,11 @@ progress::-moz-progress-bar {
background: var(--bg);
border: 1px solid var(--line);
padding: 0;
- max-width: calc(100vw - 24px);
- max-height: calc(100dvh - 28px);
+ max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
box-shadow: 0 18px 70px var(--shadow-strong);
border-radius: var(--rp-radius-surface, 7px);
- width: 960px;
+ width: calc((960px) / var(--ui-scale, 1));
overflow: auto;
}
@@ -923,7 +923,7 @@ progress::-moz-progress-bar {
}
#cache-object-scroll {
- max-height: calc(min(49vh, 520px));
+ max-height: calc(min(calc(49 * var(--rp-vh)), 520px));
overflow: auto;
scrollbar-gutter: stable;
}
@@ -965,8 +965,8 @@ dialog .vh-form,
}
#location-help-dialog {
- width: calc(min(760px, 100vw - 28px));
- max-height: calc(min(82vh, 760px));
+ width: calc((calc(min(760px, 100vw - 28px))) / var(--ui-scale, 1));
+ max-height: calc((calc(min(82vh, 760px))) / var(--ui-scale, 1));
}
#location-help-body {
@@ -1041,7 +1041,7 @@ dialog .vh-form,
#vhost-search,
#web-service-search,
#stream-search {
- width: calc(min(260px, 32vw));
+ width: calc(min(260px, calc(32 * var(--rp-vw))));
min-width: 180px;
}
@@ -1324,7 +1324,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
z-index: 40;
top: calc(100% + 7px);
right: 0;
- width: calc(min(360px, 100vw - 44px));
+ width: calc(min(360px, calc(100 * var(--rp-vw)) - 44px));
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 6px);
@@ -1348,8 +1348,8 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
}
.about-dialog {
- width: calc(min(640px, 100vw - 24px));
- max-height: calc(100vh - 24px);
+ width: calc((calc(min(640px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-height: calc((calc(100vh - 24px)) / var(--ui-scale, 1));
overflow: auto;
}
diff --git a/src/admin/web/css/20-shell.css b/src/admin/web/css/20-shell.css
index ddd01c7..a337a60 100644
--- a/src/admin/web/css/20-shell.css
+++ b/src/admin/web/css/20-shell.css
@@ -23,6 +23,9 @@ html.app-loading .shell {
#certificate-api-cancel-edit[hidden],
#certificate-api-edit-note[hidden],
#certificate-api-token-field[hidden],
+#certificate-api-form[hidden],
+#certificate-api-secret-wrap[hidden],
+#certificate-api-legacy-note[hidden],
html:not(.app-loading) .app-startup,
html.app-startup-failed .app-startup-message,
html.app-startup-failed .app-startup-spinner,
@@ -247,7 +250,7 @@ nav {
}
.app-health-dialog {
- width: min(620px, calc(100vw - 24px));
+ width: calc((min(620px, calc(100vw - 24px))) / var(--ui-scale, 1));
}
.app-health-card {
@@ -403,7 +406,7 @@ main {
}
.login-section h1 {
- font-size: calc(clamp(42px, 5vw, 68px));
+ font-size: calc(clamp(42px, calc(5 * var(--rp-vw)), 68px));
letter-spacing: -3px;
max-width: 640px;
}
@@ -487,7 +490,7 @@ main {
}
.app-confirm-dialog {
- width: calc(min(520px, 100vw - 28px));
+ width: calc((calc(min(520px, 100vw - 28px))) / var(--ui-scale, 1));
max-width: none;
padding: 0;
border: 1px solid var(--line);
@@ -528,7 +531,7 @@ main {
}
.auth-page {
- min-height: 100vh;
+ min-height: calc(100 * var(--rp-vh));
}
.auth-top {
@@ -636,7 +639,7 @@ main {
right: 14px;
bottom: 14px;
z-index: 900;
- width: calc(min(330px, 100vw - 28px));
+ width: calc(min(330px, calc(100 * var(--rp-vw)) - 28px));
padding: 0;
border: 1px solid var(--border-hover);
border-radius: var(--rp-radius-surface, 0);
@@ -706,7 +709,7 @@ main {
.draft-dock-list {
display: grid;
gap: 0;
- max-height: calc(min(42vh, 360px));
+ max-height: calc(min(calc(42 * var(--rp-vh)), 360px));
overflow: auto;
}
diff --git a/src/admin/web/css/30-overview.css b/src/admin/web/css/30-overview.css
index 463a13e..1311bf4 100644
--- a/src/admin/web/css/30-overview.css
+++ b/src/admin/web/css/30-overview.css
@@ -46,7 +46,7 @@ html[data-theme=cream] :is(.card, .stat, dialog) {
font-weight: 450;
letter-spacing: -1px;
line-height: 1.3;
- font-size: calc(clamp(20px, 1.8vw, 26px));
+ font-size: calc(clamp(20px, calc(1.8 * var(--rp-vw)), 26px));
margin: 4px 0;
}
@@ -1638,7 +1638,7 @@ html[data-chart-style] :is(#workspace, dialog) svg polyline {
display: flex;
flex-wrap: wrap;
gap: 7px;
- max-height: calc(min(30vh, 240px));
+ max-height: calc(min(calc(30 * var(--rp-vh)), 240px));
overflow-y: auto;
padding: 10px 12px;
border-top: 1px solid var(--line);
@@ -2349,8 +2349,8 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
}
.overview-presets-dialog {
- width: calc(min(730px, 100vw - 24px));
- max-height: calc(100dvh - 24px);
+ width: calc((calc(min(730px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 24px)) / var(--ui-scale, 1));
overflow-y: auto;
}
@@ -2887,7 +2887,7 @@ html[data-table-density=compact] .bo-stack { margin-top: 3px; }
.docker-load-name { overflow: hidden; color: var(--text); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
.docker-load-bar { display: grid; grid-template-columns: auto 1fr; align-items: center; gap: 4px; min-width: 0; }
.docker-load-bar>small { color: var(--muted); font: 9px var(--mono); }
-.docker-load-bar>i { display: block; height: 5px; overflow: hidden; border-radius: 3px; background: var(--line); }
+.docker-load-bar>i { display: block; height: 5px; overflow: hidden; border-radius: var(--rp-progress-radius, 0px); background: var(--line); }
.docker-load-bar>i>b { display: block; height: 100%; border-radius: inherit; background: var(--green); }
.docker-load-bar>i.is-warn>b { background: var(--accent); }
.docker-load-bar>i.is-high>b { background: var(--red); }
diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css
index 361d827..8ddfc9a 100644
--- a/src/admin/web/css/40-editors.css
+++ b/src/admin/web/css/40-editors.css
@@ -1562,7 +1562,7 @@ html.app-loading,
.vhost-backend-popup {
position: fixed;
z-index: 1600;
- max-height: calc(min(360px, 100dvh - 24px));
+ max-height: calc(min(360px, calc(100 * var(--rp-dvh)) - 24px));
overflow: auto;
padding: 12px;
background: var(--panel);
diff --git a/src/admin/web/css/50-settings.css b/src/admin/web/css/50-settings.css
index e3d8faa..e49ca2c 100644
--- a/src/admin/web/css/50-settings.css
+++ b/src/admin/web/css/50-settings.css
@@ -367,7 +367,7 @@
}
.docker-toolbar input[type=search] {
- width: calc(min(280px, 38vw));
+ width: calc(min(280px, calc(38 * var(--rp-vw))));
box-sizing: border-box;
height: var(--toolbar-control-height);
min-height: var(--toolbar-control-height);
@@ -528,7 +528,7 @@
}
.audit-dialog .table-scroll {
- max-height: calc(min(68dvh, 680px));
+ max-height: calc((calc(min(68dvh, 680px))) / var(--ui-scale, 1));
overflow: auto;
border-top: 1px solid var(--line);
}
@@ -980,19 +980,6 @@
gap: 4px;
}
-.certificate-api-details {
- display: grid;
- gap: 7px;
- padding: 10px 12px;
- border-top: 1px solid var(--line);
-}
-
-.certificate-api-detail-line {
- display: grid;
- gap: 4px;
- grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr);
- overflow-wrap: anywhere;
-}
.certificate-api-credential-row {
display: flex;
@@ -1508,7 +1495,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.docker-system-item { display: grid; gap: 2px; min-width: 0; padding: 7px 9px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 8px); background: var(--panel); }
.docker-system-item>span { color: var(--muted); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; }
.docker-system-item>strong { font: 600 12px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.docker-system-meter { display: block; height: 4px; margin-top: 3px; overflow: hidden; border-radius: 3px; background: var(--line); }
+.docker-system-meter { display: block; height: 4px; margin-top: 3px; overflow: hidden; border-radius: var(--rp-progress-radius, 0px); background: var(--line); }
.docker-system-meter>b { display: block; height: 100%; background: var(--green); border-radius: inherit; }
.docker-system-meter.is-warn>b { background: var(--accent); }
.docker-system-meter.is-high>b { background: var(--red); }
@@ -1535,8 +1522,376 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
.docker-alert-editor>summary { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; cursor: pointer; font-weight: 600; font-size: 13px; }
.docker-alert-editor>summary small { font-weight: 400; }
.docker-alert-grid { margin-top: 10px; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); }
-.docker-agent-test-row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; margin: 0 0 10px; }
-.docker-agent-test-result.is-ok { color: var(--green); }
-.docker-agent-test-result.is-error { color: var(--red); overflow-wrap: anywhere; }
+.docker-agent-test-wrap { position: relative; display: inline-flex; }
+.docker-agent-test-wrap>.docker-agent-test { min-height: 32px; box-sizing: border-box; }
+.docker-agent-test-result { position: absolute; top: calc(100% + 8px); right: 0; z-index: 30; width: max-content; max-width: min(360px, calc(80 * var(--rp-vw))); padding: 8px 11px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel); box-shadow: 0 8px 24px var(--shadow-mid); font-size: 12px; line-height: 1.4; color: var(--text); overflow-wrap: anywhere; cursor: pointer; }
+.docker-agent-test-result::before { content: ""; position: absolute; top: -6px; right: 18px; width: 10px; height: 10px; background: inherit; border-left: 1px solid var(--line); border-top: 1px solid var(--line); transform: rotate(45deg); }
+.docker-agent-test-result[hidden] { display: none; }
+.docker-agent-test-result.is-running { color: var(--muted); }
+.docker-agent-test-result.is-ok { border-color: var(--green); color: var(--green); }
+.docker-agent-test-result.is-error { border-color: var(--red); color: var(--red); }
.docker-label-badge { align-self: center; }
-.docker-container-state { display: inline-flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
+.docker-container-state { display: flex; flex-wrap: wrap; gap: 5px 6px; align-items: center; margin-top: 2px; }
+.docker-container-state .docker-container-pill { font-size: 11px; }
+.docker-container-state .docker-container-pill.muted { color: var(--muted); }
+.docker-container-state .docker-container-uptime { font-weight: 400; opacity: .8; }
+.docker-container-state .docker-container-chip { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); font-size: 11px; line-height: 1.5; color: var(--text); background: var(--panel); }
+.docker-container-state .docker-container-chip-label { color: var(--muted); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; }
+.docker-container-state .docker-container-chip>b { font-weight: 600; font-variant-numeric: tabular-nums; }
+.docker-container-state .docker-container-chip-bar { position: relative; width: 38px; height: 4px; border-radius: var(--rp-progress-radius, 0px); background: var(--line); overflow: hidden; }
+.docker-container-state .docker-container-chip-bar>i { position: absolute; inset: 0 auto 0 0; border-radius: var(--rp-progress-radius, 0px); background: var(--green); }
+.docker-container-state .docker-container-chip.is-warn { border-color: var(--warn-line); }
+.docker-container-state .docker-container-chip.is-warn .docker-container-chip-bar>i { background: var(--accent); }
+.docker-container-state .docker-container-chip.is-warn>b { color: var(--accent); }
+.docker-container-state .docker-container-chip.is-danger { border-color: var(--danger-line-strong); }
+.docker-container-state .docker-container-chip.is-danger .docker-container-chip-bar>i { background: var(--red); }
+.docker-container-state .docker-container-chip.is-danger>b { color: var(--red); }
+.docker-target-hint { display: block; margin-top: 4px; }
+.docker-label-help { display: flex; gap: 6px; align-items: flex-start; }
+.docker-label-help>span { flex: 1 1 auto; 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; border-collapse: collapse; font-size: 13px; }
+#location-help-body .docker-label-table td { padding: 5px 8px; border-bottom: 1px solid var(--line); vertical-align: top; white-space: normal; overflow: visible; text-overflow: clip; max-width: none; font-family: inherit; line-height: 1.45; }
+#location-help-body .docker-label-table td:first-child { width: 1%; white-space: nowrap; }
+.docker-label-example-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 12px; }
+.docker-label-example-head>h3 { margin: 0; }
+.docker-label-example { margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--bg, transparent); overflow: auto; font-size: 12px; line-height: 1.5; }
+.docker-certificate-hint.is-warn { color: var(--accent); }
+
+.certificate-api-card>.card-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; }
+.certificate-api-heading-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+.certificate-api-secret { margin-top: 12px; padding: 12px; border: 1px solid var(--green); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
+.certificate-api-secret-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 8px; }
+.certificate-api-secret pre { margin: 0; user-select: all; overflow-wrap: anywhere; white-space: pre-wrap; }
+.certificate-api-editor { display: grid; gap: 12px; margin-top: 12px; padding: 14px; border: 1px solid var(--accent); border-radius: var(--rp-radius-surface, 0px); background: var(--panel); }
+.certificate-api-credential-item>.certificate-api-editor { margin: 0 9px 9px; }
+.certificate-api-editor>h3 { margin: 0; font-size: 15px; }
+.certificate-api-editor>.fine { margin: 0; }
+.certificate-api-editor-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 14px; }
+.certificate-api-editor-grid>label { display: grid; gap: 5px; margin: 0; }
+.certificate-api-editor-grid>label[hidden] { display: none; }
+.certificate-api-mode { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 8px; margin: 0; padding: 0; border: 0; }
+.certificate-api-mode>legend { padding: 0; margin-bottom: 6px; font-size: 13px; }
+.certificate-api-mode-option { display: flex; gap: 10px; align-items: flex-start; margin: 0 !important; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel2); cursor: pointer; }
+.certificate-api-mode-option:has(input:checked) { border-color: var(--accent); }
+.certificate-api-mode-option>input { margin-top: 3px; }
+.certificate-api-mode-option>span { display: grid; gap: 3px; min-width: 0; }
+.certificate-api-certificates-field { display: grid; gap: 6px; }
+.certificate-api-certificates-field>.fine { margin: 0; }
+#certificate-api-legacy-note { color: var(--accent); }
+.certificate-api-token-field>summary { cursor: pointer; font-size: 13px; }
+.certificate-api-token-field>input { margin-top: 8px; width: 100%; max-width: 520px; }
+.certificate-api-token-field>.fine { margin: 6px 0 0; }
+.certificate-api-credential-title { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }
+.certificate-api-chips { display: flex; flex-wrap: wrap; gap: 5px; }
+.certificate-api-chip { padding: 1px 8px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); font-family: var(--mono, monospace); font-size: 11px; line-height: 1.6; color: var(--text); }
+.certificate-api-chip.is-new { border-style: dashed; color: var(--muted); }
+.certificate-api-chip.is-managed { border-color: var(--green); }
+.certificate-api-legacy { color: var(--accent); }
+.certificate-api-example { margin-top: 14px; }
+.certificate-api-example>summary { cursor: pointer; font-size: 13px; }
+#panel-settings [data-restart]>span[data-restart-badge]::after { content: attr(data-restart-badge); display: inline-block; margin-left: 7px; padding: 0 5px; border: 1px solid var(--warn-line); border-radius: var(--rp-radius-control, 0px); color: var(--accent); font-size: 9.5px; font-weight: 600; letter-spacing: .05em; line-height: 1.5; text-transform: uppercase; vertical-align: 1px; }
+#panel-settings .help-clamp { cursor: pointer; }
+#panel-settings .help-clamp:not(.is-open) { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }
+#panel-settings .help-clamp:hover, #panel-settings .help-clamp:focus-visible { color: var(--text); }
+#panel-settings .settings-page form.card>.settings-save-bar { position: sticky; bottom: 0; z-index: 6; margin-top: 14px; margin-bottom: 0; padding: 10px 0; border-top: 1px solid var(--line); background: var(--panel); align-items: center; }
+#panel-settings .settings-save-bar.has-unsaved::before { content: attr(data-unsaved-label); order: 99; margin-left: auto; color: var(--accent); font-size: 12px; }
+.settings-section { display: grid; gap: 10px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--line); }
+.settings-section>.subheading { margin: 0; }
+.settings-section>.fine, .settings-section>.check { margin: 0 !important; }
+.settings-chip-field { display: grid; gap: 5px; }
+.settings-token-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.global-policy-summary { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0 4px; }
+.global-policy-summary:empty { display: none; }
+.global-policy-chip { display: inline-flex; gap: 6px; align-items: center; min-height: 0; padding: 4px 10px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel2); color: var(--muted); font-size: 12px; cursor: pointer; }
+.global-policy-chip>b { font-weight: 600; font-size: 11px; }
+.global-policy-chip.is-on { border-color: var(--green); color: var(--text); }
+.global-policy-chip.is-on>b { color: var(--green); }
+.global-policy-heading h3 .global-policy-state { margin-left: 8px; font-size: 10px; vertical-align: 2px; }
+.global-policy-section.is-off .global-policy-heading>.fine { opacity: .75; }
+.country-picker-host { min-width: 0; }
+.named-listener-row.listener-card { padding: 0; background: var(--panel2); }
+.listener-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; width: 100%; min-height: 0; padding: 10px 12px; border: 0; background: none; color: var(--text); text-align: left; cursor: pointer; }
+.listener-card-chevron::before { content: "▾"; display: inline-block; color: var(--muted); transition: transform .15s; }
+.listener-card.is-collapsed .listener-card-chevron::before { transform: rotate(-90deg); }
+.listener-card-title { display: inline-flex; gap: 8px; align-items: baseline; }
+.listener-card-id { color: var(--muted); font-size: 11px; }
+.listener-card-addresses { display: inline-flex; flex-wrap: wrap; gap: 4px; }
+.listener-card-badges { display: inline-flex; flex-wrap: wrap; gap: 4px; margin-left: auto; }
+.listener-card-badges>.pill { font-size: 10px; }
+.listener-card-body { padding: 4px 12px 12px; border-top: 1px solid var(--line); }
+.listener-card.is-collapsed>.listener-card-body { display: none; }
+#listeners-form>.listener-active-summary { margin: 10px 0 4px; }
+#global-policy-summary>.global-policy-chip { width: auto; flex: 0 0 auto; justify-content: flex-start; margin: 0; }
+.certificate-api-mode>label.certificate-api-mode-option { display: flex !important; flex-direction: row; grid-template-columns: none; }
+.cache-rules { display: grid; gap: 10px; margin-top: 8px; }
+.cache-rules-toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.cache-rules-toolbar>.cache-rules-templates { width: auto; min-width: 220px; }
+.cache-rules-toolbar>.primary { margin-left: auto; }
+.cache-rules-notices { display: grid; gap: 4px; }
+.cache-rules-notices:empty { display: none; }
+.cache-rules-notice { color: var(--accent); margin: 0; }
+.cache-rules-list { display: grid; gap: 6px; }
+.cache-rule { border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
+.cache-rule.is-open { border-color: var(--accent); }
+.cache-rule.is-disabled .cache-rule-title { opacity: .55; }
+.cache-rule.is-dragging { opacity: .5; }
+.cache-rule.is-drop { border-style: dashed; border-color: var(--accent); }
+.cache-rule-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; }
+.cache-rule-grip { cursor: grab; color: var(--muted); user-select: none; }
+.cache-rule-title { display: flex; flex: 1 1 auto; flex-wrap: wrap; align-items: center; gap: 4px 10px; min-width: 0; min-height: 0; padding: 0; border: 0; background: none; color: var(--text); text-align: left; cursor: pointer; }
+.cache-rule-title>b { font-weight: 600; }
+.cache-rule-title>.cache-rule-summary { overflow-wrap: anywhere; }
+.cache-rule-stage { font-size: 10px; }
+.cache-rule-hits { white-space: nowrap; }
+.cache-rule-actions { display: inline-flex; gap: 2px; }
+.cache-rule-note { padding: 0 10px 8px 34px; }
+.cache-rule-body { display: grid; gap: 12px; padding: 10px 12px 12px; border-top: 1px solid var(--line); }
+.cache-rule-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px 14px; align-items: end; }
+.cache-rule-field { display: grid; gap: 5px; margin: 0 !important; min-width: 0; }
+.cache-rule-field>small { margin: 0; }
+.cache-rule-stop { margin: 0 !important; }
+.cache-rule-section { display: grid; gap: 6px; }
+.cache-rule-section>h4 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
+.cache-rule-rows { display: grid; gap: 6px; }
+.cache-rule-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
+.cache-rule-row>select { width: auto; min-width: 150px; }
+.cache-rule-row>.cache-rule-name { width: 140px; }
+.cache-rule-row>.cache-rule-values { flex: 1 1 220px; min-width: 160px; }
+.cache-rule-row>.cache-rule-params { display: flex; flex: 1 1 260px; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
+.cache-rule-params>input[type=text] { flex: 1 1 160px; min-width: 120px; }
+.cache-rule-negate { margin: 0 !important; }
+.cache-rule-duration { display: inline-flex; gap: 4px; }
+.cache-rule-duration>input { width: 100px; }
+.cache-rule-duration>select { width: auto; }
+.cache-rule-vcl, .cache-rules-vcl { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
+.cache-rules-import { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
+.cache-rules-import>textarea { font-family: var(--mono); font-size: 12px; }
+.cache-rules-warnings { margin: 0; padding-left: 18px; color: var(--accent); font-size: 12px; }
+.cache-rules-export>summary, .cache-rules-tester>summary { cursor: pointer; font-size: 13px; }
+.cache-rules-tester { padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); }
+.cache-rules-tester-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 14px; margin-top: 8px; }
+.cache-rules-tester-grid textarea { font-family: var(--mono); font-size: 12px; }
+.cache-rules-tester-result { display: grid; gap: 4px; margin-top: 8px; }
+.cache-rules-result-line { display: grid; grid-template-columns: minmax(140px, 200px) minmax(0, 1fr); gap: 10px; overflow-wrap: anywhere; }
+.cache-rules-result-line.is-ok>strong { color: var(--green); }
+.cache-rules-result-line.is-warn>strong { color: var(--accent); }
+.cache-rules .is-ok { color: var(--green); }
+.cache-rules .is-error { color: var(--red); }
+.vh-cache-rules { display: grid; gap: 6px; margin-top: 6px; padding-top: 10px; border-top: 1px solid var(--line); }
+.vh-cache-rules>h4 { margin: 0; }
+.cache-rule-actions { flex: 0 0 auto; }
+.cache-rule-actions>button { white-space: nowrap; flex-direction: row; }
+.cache-rule-grid { align-items: start; }
+.docs-links { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 4px 0 0; font-size: 12px; }
+.docs-link { font-size: 12px; justify-self: start; }
+
+.system-info-page {
+ display: grid;
+ gap: var(--ui-gap);
+}
+
+.system-info-page > .card,
+.system-info-page > .stats-grid {
+ margin: 0;
+}
+
+.system-info-page .card-heading h2 {
+ overflow-wrap: anywhere;
+}
+
+.system-info-chips {
+ margin: 4px 0 0;
+}
+
+.system-info-stats > .stat {
+ display: flex;
+ flex-direction: column;
+}
+
+.system-info-stats > .stat svg {
+ display: block;
+ width: 100%;
+ height: 34px;
+ margin-top: auto;
+ padding-top: 6px;
+}
+
+.system-info-stats > .stat .pr-meter {
+ display: block;
+ flex: 0 0 auto;
+ width: 100%;
+ margin-top: auto;
+}
+
+.system-info-columns {
+ display: grid;
+ grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr);
+ gap: var(--ui-gap);
+ align-items: stretch;
+}
+
+.system-info-columns > .card {
+ margin: 0;
+ min-width: 0;
+}
+
+.system-info-page .pr-row {
+ align-items: center;
+}
+
+.system-info-split {
+ height: 8px;
+}
+
+.system-info-split i,
+.system-info-legend i {
+ display: block;
+}
+
+.system-info-split .h,
+.system-info-legend .h {
+ background: var(--chart-secondary);
+}
+
+.system-info-split .t,
+.system-info-legend .t {
+ background: var(--chart-senary);
+}
+
+.system-info-split .a,
+.system-info-legend .a {
+ background: var(--chart-accent);
+}
+
+.system-info-split .f,
+.system-info-legend .f {
+ background: var(--chart-tertiary);
+}
+
+.system-info-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 14px;
+ margin: 4px 0 6px;
+ color: var(--muted);
+ font: 10px var(--mono);
+}
+
+.system-info-legend > span {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.system-info-legend i {
+ width: 8px;
+ height: 8px;
+ border-radius: var(--rp-progress-radius, 0);
+}
+
+.system-info-legend b {
+ color: var(--text);
+ font-weight: 500;
+}
+
+.system-info-network td code {
+ padding: 0;
+ background: none;
+}
+
+.system-info-idle {
+ margin-top: 8px;
+}
+
+.system-info-idle summary {
+ cursor: pointer;
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.system-info-chain {
+ align-items: center;
+ margin: 6px 0 10px;
+}
+
+.system-info-chain > span {
+ color: var(--text-subtle);
+ font: 11px var(--mono);
+}
+
+.system-info-chain .pr-chip.is-ready {
+ border-color: var(--pill-live-line);
+}
+
+.system-info-chain .pr-chip.is-ready dd {
+ color: var(--green);
+}
+
+.system-info-chain .pr-chip.is-missing {
+ border-color: var(--danger-line);
+}
+
+.system-info-chain .pr-chip.is-missing dd {
+ color: var(--red);
+}
+
+.system-info-copy-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ margin-left: auto;
+}
+
+.system-info-copy-row dd {
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.system-info-copy-row code {
+ padding: 0;
+ background: none;
+ white-space: normal;
+}
+
+.system-info-copy-row button {
+ padding: 3px 8px;
+ font-size: 10px;
+}
+
+.system-info-footer {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+}
+
+.system-info-footer .pr-chips {
+ margin: 0;
+}
+
+.system-info-clipboard {
+ position: fixed;
+ opacity: 0;
+ pointer-events: none;
+}
+
+@media (max-width: 1100px) {
+ .system-info-columns {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+@media (max-width: 700px) {
+ .system-info-page .pr-cols {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+.stats-grid.cache-stats.system-info-stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+}
diff --git a/src/admin/web/css/60-monitoring.css b/src/admin/web/css/60-monitoring.css
index 712bc13..de64dbb 100644
--- a/src/admin/web/css/60-monitoring.css
+++ b/src/admin/web/css/60-monitoring.css
@@ -29,7 +29,7 @@
z-index: 80;
inset-inline-end: 0;
top: calc(100% + 4px);
- width: calc(min(190px, 100vw - 24px));
+ width: calc(min(190px, calc(100 * var(--rp-vw)) - 24px));
overflow: visible;
padding: 4px;
display: grid;
@@ -121,7 +121,7 @@
}
.logs-dialog .table-scroll {
- max-height: calc(min(60dvh, 580px));
+ max-height: calc((calc(min(60dvh, 580px))) / var(--ui-scale, 1));
overflow: auto;
border-top: 1px solid var(--line);
}
@@ -152,13 +152,13 @@
position: fixed;
inset: auto 12px 10px auto;
margin: 0;
- width: calc(min(1180px, 100vw - 24px));
- max-height: 46dvh;
+ width: calc((calc(min(1180px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-height: calc((46dvh) / var(--ui-scale, 1));
z-index: 20;
}
.logs-dialog.docked .table-scroll {
- max-height: calc(46dvh - 160px);
+ max-height: calc((calc(46dvh - 160px)) / var(--ui-scale, 1));
}
.cache-toolbar {
@@ -443,7 +443,7 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
}
.cache-operation-dialog {
- width: calc(min(920px, 100vw - 32px));
+ width: calc((calc(min(920px, 100vw - 32px))) / var(--ui-scale, 1));
}
.transform-applied-key,
@@ -495,16 +495,16 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
}
.config-history-dialog {
- width: calc(min(1180px, 100vw - 24px));
- max-width: calc(100vw - 24px);
- max-height: calc(100dvh - 28px);
+ width: calc((calc(min(1180px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
overflow: hidden;
}
.config-history-dialog[open] {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
- height: calc(min(820px, 100dvh - 28px));
+ height: calc((calc(min(820px, 100dvh - 28px))) / var(--ui-scale, 1));
}
.config-history-layout {
@@ -663,7 +663,7 @@ button.config-history-day.is-selected,
}
.file-logs-table {
- max-height: 62vh;
+ max-height: calc(62 * var(--rp-vh));
}
.file-logs-table thead th {
@@ -727,7 +727,7 @@ button.config-history-day.is-selected,
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
- max-height: 24vh;
+ max-height: calc(24 * var(--rp-vh));
margin-top: 5px;
line-height: 1.28;
}
@@ -767,7 +767,7 @@ button.config-history-day.is-selected,
inset-inline-end: 0;
display: grid;
gap: 7px;
- width: calc(min(420px, 100vw - 36px));
+ width: calc(min(420px, calc(100 * var(--rp-vw)) - 36px));
padding: 12px;
border: 1px solid var(--line);
background: var(--panel2);
@@ -792,7 +792,7 @@ button.config-history-day.is-selected,
}
.file-log-column-picker .log-column-options {
- width: calc(min(360px, 100vw - 24px));
+ width: calc(min(360px, calc(100 * var(--rp-vw)) - 24px));
max-height: 420px;
overflow: auto;
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -895,8 +895,8 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
}
.cache-varnish-info .metric-info-popover {
- width: calc(min(440px, 100vw - 56px));
- max-height: calc(min(65vh, 450px));
+ width: calc(min(440px, calc(100 * var(--rp-vw)) - 56px));
+ max-height: calc(min(calc(65 * var(--rp-vh)), 450px));
overflow-y: auto;
}
@@ -908,9 +908,9 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
}
.cache-maintenance-info .metric-info-popover {
- max-height: calc(min(60vh, 420px));
+ max-height: calc(min(calc(60 * var(--rp-vh)), 420px));
overflow-y: auto;
- width: calc(min(440px, 100vw - 56px));
+ width: calc(min(440px, calc(100 * var(--rp-vw)) - 56px));
}
.cache-maintenance-info .metric-info-popover code {
@@ -1049,9 +1049,9 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
}
.config-history-json-dialog {
- width: calc(min(1200px, 100vw - 24px));
- max-width: calc(100vw - 24px);
- max-height: calc(100dvh - 28px);
+ width: calc((calc(min(1200px, 100vw - 24px))) / var(--ui-scale, 1));
+ max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
+ max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
overflow: auto;
}
@@ -1068,7 +1068,7 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
background: var(--panel);
border: 0;
overflow: auto;
- max-height: 68dvh;
+ max-height: calc(68 * var(--rp-dvh));
font: 11px/1.5 var(--mono);
}
diff --git a/src/admin/web/css/70-responsive.css b/src/admin/web/css/70-responsive.css
index 569b208..cb8531c 100644
--- a/src/admin/web/css/70-responsive.css
+++ b/src/admin/web/css/70-responsive.css
@@ -173,7 +173,7 @@
}
.config-history-browser {
- max-height: calc(min(300px, 38dvh));
+ max-height: calc(min(300px, calc(38 * var(--rp-dvh))));
overflow-y: auto;
margin-bottom: 10px;
}
@@ -298,7 +298,7 @@
}
.vhost-dialog {
- max-width: calc(100vw - 12px);
+ max-width: calc((calc(100vw - 12px)) / var(--ui-scale, 1));
}
.sidebar .brand {
@@ -512,7 +512,7 @@
}
#panel-filelogs .file-log-search-help-popover {
- width: calc(min(320px, 100vw - 54px));
+ width: calc(min(320px, calc(100 * var(--rp-vw)) - 54px));
}
#panel-filelogs .file-log-aggregate-form,
@@ -1023,7 +1023,7 @@
}
.logs-dialog .table-scroll {
- max-height: 50dvh;
+ max-height: calc((50dvh) / var(--ui-scale, 1));
}
.log-tools select {
@@ -1032,11 +1032,11 @@
}
.logs-dialog.docked {
- max-height: 55dvh;
+ max-height: calc((55dvh) / var(--ui-scale, 1));
}
.logs-dialog.docked .table-scroll {
- max-height: calc(55dvh - 230px);
+ max-height: calc((calc(55dvh - 230px)) / var(--ui-scale, 1));
}
.page-editor,
@@ -1176,7 +1176,7 @@
}
.config-history-json-columns pre {
- max-height: 38dvh;
+ max-height: calc(38 * var(--rp-dvh));
}
.appearance-settings-grid.dashboard-appearance-grid>.dashboard-density-setting {
@@ -1282,9 +1282,9 @@
}
.backend-column-options {
- width: min(330px, calc(100vw - 32px));
+ width: min(330px, calc(calc(100 * var(--rp-vw)) - 32px));
min-width: 0;
- max-width: calc(100vw - 32px);
+ max-width: calc(calc(100 * var(--rp-vw)) - 32px);
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@@ -1481,7 +1481,7 @@
@media (max-width:480px) {
.page-intro-title-row h1 {
- font-size: calc(clamp(18px, 5vw, 24px));
+ font-size: calc(clamp(18px, calc(5 * var(--rp-vw)), 24px));
letter-spacing: -.6px;
}
@@ -1548,7 +1548,7 @@
.log-column-options {
top: auto;
bottom: calc(100% + 4px);
- width: calc(min(360px, 100vw - 24px));
+ width: calc(min(360px, calc(100 * var(--rp-vw)) - 24px));
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@@ -1642,11 +1642,11 @@
}
html[data-dashboard-density=normal] #panel-overview .dashboard-overview-grid.is-aligned>.stat strong {
- font-size: calc(clamp(20px, 5.8vw, 26px));
+ font-size: calc(clamp(20px, calc(5.8 * var(--rp-vw)), 26px));
}
html[data-dashboard-density=compact] #panel-overview .dashboard-overview-grid.is-aligned>.stat strong {
- font-size: calc(clamp(19px, 5vw, 22px));
+ font-size: calc(clamp(19px, calc(5 * var(--rp-vw)), 22px));
}
#panel-overview .dashboard-overview-grid.is-aligned>.card:not(.pool-card):where(:not([data-dashboard-span])) {
@@ -1755,7 +1755,7 @@
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-acl-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-protocol-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-timeout-editor { margin-top: 10px; }
-.docker-service-editor>summary:focus-visible, .docker-acl-editor>summary:focus-visible, .docker-protocol-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; border-radius: 4px; }
+.docker-service-editor>summary:focus-visible, .docker-acl-editor>summary:focus-visible, .docker-protocol-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; border-radius: var(--rp-radius-control, 0px); }
.vh-tabs { gap: 2px; padding: 4px 0 0; border-bottom: 1px solid var(--line); margin-bottom: 12px; }
.vh-tabs button { font-size: 12px; padding: 8px 12px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--muted); margin-bottom: -1px; }
diff --git a/src/admin/web/docker.js b/src/admin/web/docker.js
index b51f6c9..af03062 100644
--- a/src/admin/web/docker.js
+++ b/src/admin/web/docker.js
@@ -95,7 +95,7 @@
const field = el("div", undefined, "docker-field docker-alias-field host-chip-field"), box = el("div", undefined, "host-chip-editor docker-alias-editor"), inputNode = input("", "text", "docker-alias-input");
field.append(el("span", t("dockerAliases"))); inputNode.maxLength = 253; inputNode.placeholder = "alias1 / app.example.com"; inputNode.setAttribute("aria-label", t("dockerAliasAdd"));
const aliasDomain = el("select", undefined, "docker-alias-domain"); aliasDomain.setAttribute("aria-label", t("dockerAliasDomain")); aliasDomain.title = t("dockerAliasDomain");
- const fillAliasDomains = () => { const current = aliasDomain.value; aliasDomain.replaceChildren(); const master = el("option", `.${scope.master() || "…"} (${t("dockerDomainMasterShort")})`); master.value = ""; aliasDomain.append(master); for (const domain of scope.domains) { const option = el("option", `.${domain}`); option.value = domain; aliasDomain.append(option); } aliasDomain.value = [...aliasDomain.options].some(option => option.value === current) ? current : ""; };
+ const fillAliasDomains = () => { const current = aliasDomain.value; aliasDomain.replaceChildren(); const master = el("option", `.${scope.master() || "…"} (${t("dockerDomainMasterShort")})`); master.value = ""; aliasDomain.append(master); const masterName = scope.master(); for (const domain of scope.domains) { if (domain === masterName) continue; const option = el("option", `.${domain}`); option.value = domain; aliasDomain.append(option); } aliasDomain.value = [...aliasDomain.options].some(option => option.value === current) ? current : ""; aliasDomain.hidden = aliasDomain.options.length < 2; };
fillAliasDomains();
const values = [];
const normalize = raw => {
@@ -213,20 +213,43 @@
const items = (envelope?.config?.tls?.certificates || []).map(cert => { const names = certificateNames(cert); return { id: cert.id, title: cert.id, detail: names.slice(0, 4).join(", ") + (names.length > 4 ? ` +${names.length - 4}` : ""), search: names.join(" "), badge: cert.issuer ? "ACME" : "", badgeClass: "is-allow" }; });
return window.rustProxyChoicePicker.create({ className: "docker-agent-certificates", selected, items, limit: MAX_CERTIFICATES, unknownDetail: "dockerCertificateUnknown", labels: { choose: "dockerCertificatesChoose", selected: "dockerCertificatesSelected", none: "dockerCertificatesNone", empty: "dockerCertificatesEmpty" } });
}
- function detectedAddresses(agentId) { return (obs(agentId)?.inventory?.addresses || []).map(address => { const details = [address.interface, address.scope, address.source].filter(Boolean).join(" · "); return [address.ip, details ? `${address.ip} (${details})` : address.ip]; }); }
+ function addressGroup(address, primary) {
+ const sources = String(address.source || "").split(/[\s,]+/).filter(Boolean);
+ if (address.ip === primary || sources.some(source => ["override", "route", "public_api"].includes(source))) return "recommended";
+ if (sources.includes("bridge")) return "bridge";
+ return "host";
+ }
+ function detectedAddresses(agentId) {
+ const inventory = obs(agentId)?.inventory || {}, primary = inventory.public_ip || "";
+ return (inventory.addresses || []).map(address => {
+ const details = [address.interface, address.scope, address.source].filter(Boolean).join(" · ");
+ return { ip: address.ip, label: details ? `${address.ip} (${details})` : address.ip, group: addressGroup(address, primary), primary: address.ip === primary };
+ });
+ }
function targetIpControl(agent, current) {
const wrap = el("div", undefined, "docker-target-control"), select = el("select", undefined, "docker-agent-target"), custom = input("", "text", "docker-agent-target-custom mono");
custom.placeholder = "10.0.0.20 / 2001:db8::20"; custom.maxLength = 45; custom.spellcheck = false;
const auto = el("option", t("dockerTargetAutoDetected")); auto.value = ""; select.append(auto);
const detected = detectedAddresses(agent?.id);
- for (const [ip, label] of detected) { const option = el("option", label); option.value = ip; select.append(option); }
+ for (const [group, key] of [["recommended", "dockerTargetGroupRecommended"], ["host", "dockerTargetGroupHost"], ["bridge", "dockerTargetGroupBridge"]]) {
+ const items = detected.filter(item => item.group === group); if (!items.length) continue;
+ const holder = el("optgroup"); holder.label = t(key);
+ for (const item of items) { const option = el("option", item.primary ? `★ ${item.label}` : item.label); option.value = item.ip; holder.append(option); }
+ select.append(holder);
+ }
const customOption = el("option", t("dockerTargetCustom")); customOption.value = CUSTOM_IP; select.append(customOption);
current = String(current || "");
- if (!current) select.value = ""; else if (detected.some(([ip]) => ip === current)) select.value = current; else { select.value = CUSTOM_IP; custom.value = current; }
- const sync = () => { custom.hidden = select.value !== CUSTOM_IP; custom.required = select.value === CUSTOM_IP; };
+ if (!current) select.value = ""; else if (detected.some(item => item.ip === current)) select.value = current; else { select.value = CUSTOM_IP; custom.value = current; }
+ const hint = el("small", "", "fine docker-target-hint");
+ const sync = () => {
+ custom.hidden = select.value !== CUSTOM_IP; custom.required = select.value === CUSTOM_IP;
+ const chosen = detected.find(item => item.ip === select.value);
+ hint.textContent = chosen?.group === "bridge" ? t("dockerTargetBridgeHint") : "";
+ hint.hidden = !hint.textContent;
+ };
select.addEventListener("change", () => { sync(); if (select.value === CUSTOM_IP) custom.focus(); }); sync();
if (!detected.length) wrap.title = t("dockerTargetNoDetected");
- wrap.append(select, custom);
+ wrap.append(select, custom, hint);
return { node: wrap, read() { if (select.value !== CUSTOM_IP) return select.value || null; const value = custom.value.trim(); if (!value) throw fieldError(custom, t("dockerTargetCustomRequired")); return value; } };
}
function percent(part, total) { return total > 0 ? Math.max(0, Math.min(100, part / total * 100)) : 0; }
@@ -294,6 +317,38 @@
}
function renderSettingsDiagnostics() { document.querySelectorAll("#docker-agent-settings-list .docker-agent-diagnostics").forEach(renderAgentDiagnostics); }
+ const LABEL_EXAMPLE = `services:
+ shop:
+ image: nginx:alpine
+ ports:
+ - "8080:80"
+ labels:
+ rustproxy.enable: "true"
+ rustproxy.host: "shop"
+ rustproxy.domain: "apps.example.com"
+ rustproxy.aliases: "sklep, www.shop.apps.example.com"
+ rustproxy.port: "80"
+ rustproxy.scheme: "http"
+ rustproxy.force_ssl: "true"
+ rustproxy.websockets: "true"
+ rustproxy.cache: "false"
+ rustproxy.compression: "true"
+ rustproxy.preserve_host: "true"`;
+ function openLabelHelp() {
+ const dialog = $("location-help-dialog"), title = $("location-help-title"), body = $("location-help-body"); if (!dialog || !title || !body) return;
+ title.textContent = t("dockerLabelHelpTitle");
+ const table = el("table", undefined, "docker-label-table"), tbody = el("tbody");
+ for (const [label, key] of [["rustproxy.enable", "dockerLabelHelpEnable"], ["rustproxy.host", "dockerLabelHelpHost"], ["rustproxy.domain", "dockerLabelHelpDomain"], ["rustproxy.aliases", "dockerLabelHelpAliases"], ["rustproxy.port", "dockerLabelHelpPort"], ["rustproxy.scheme", "dockerLabelHelpScheme"], ["rustproxy.force_ssl", "dockerLabelHelpForceSsl"], ["rustproxy.websockets", "dockerLabelHelpWebsockets"], ["rustproxy.cache", "dockerLabelHelpCache"], ["rustproxy.compression", "dockerLabelHelpCompression"], ["rustproxy.preserve_host", "dockerLabelHelpPreserveHost"]]) {
+ const tr = el("tr"), name = el("td"); name.append(el("code", label)); tr.append(name, el("td", t(key))); tbody.append(tr);
+ }
+ table.append(tbody);
+ const pre = el("pre", undefined, "docker-label-example"), code = el("code", LABEL_EXAMPLE); pre.append(code);
+ const copy = el("button", t("copyEntry"), "outline docker-label-copy"); copy.type = "button"; copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(LABEL_EXAMPLE); toast(t("copied")); } catch { const range = document.createRange(); range.selectNodeContents(code); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); } });
+ const exampleHead = el("div", undefined, "docker-label-example-head"); exampleHead.append(el("h3", t("dockerLabelHelpExample")), copy);
+ const docs = el("a", t("dockerLabelHelpDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FDOCKER_DISCOVERY.md§ion=publishing-from-container-labels"; docs.target = "_blank"; docs.rel = "noopener noreferrer";
+ body.replaceChildren(el("p", t("dockerLabelHelpIntro"), "location-doc-intro"), table, exampleHead, pre, el("p", t("dockerLabelHelpNote"), "fine"), docs);
+ dialog.showModal();
+ }
function agentSettingsRow(agent = null, options = {}) {
const value = agent || { id: "", name: "", enabled: true, endpoint: "https://127.0.0.1:9876", token: "", tls_fingerprint_sha256: null, domains: [], poll_interval_seconds: 30, certificate_ids: [], acl_profile_id: null, default_target_ip: null, listener_ids: [firstListener()], assignments: [] };
const row = el("div", undefined, "docker-agent-settings entity"); row.dataset.originalId = agent?.id || ""; row._assignments = structuredClone(value.assignments || []);
@@ -301,7 +356,9 @@
const enabled = input("", "checkbox", "docker-agent-enabled"); enabled.checked = value.enabled !== false;
const enabledLabel = el("label", undefined, "check"); enabledLabel.append(enabled, el("span", t("enabled")));
const state = agent ? obs(agent.id) : null, stateBadge = el("span", state?.ok ? t("dockerConnected") : state ? t("dockerError") : t("dockerWaiting"), `pill docker-agent-status-badge ${state?.ok ? "live" : ""}`.trim());
- const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("docker-agents-form"); }), actions = el("div", undefined, "entity-actions docker-agent-heading-actions"); actions.append(enabledLabel, stateBadge, remove); head.append(title, actions);
+ const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("docker-agents-form"); }), actions = el("div", undefined, "entity-actions docker-agent-heading-actions");
+ const testWrap = el("span", undefined, "docker-agent-test-wrap"), testButton = el("button", t("dockerTestConnection"), "outline docker-agent-test"), testResult = el("div", "", "docker-agent-test-result"); testButton.type = "button"; testResult.hidden = true; testResult.setAttribute("role", "status"); testWrap.append(testButton, testResult);
+ actions.append(enabledLabel, stateBadge, testWrap, remove); head.append(title, actions);
const id = input(value.id, "text", "docker-agent-id"); id.maxLength = 64; id.required = true; id.pattern = "[A-Za-z0-9_\\-]{1,64}"; if (agent) id.readOnly = true;
const name = input(value.name, "text", "docker-agent-name"); name.maxLength = 96; name.required = true;
name.addEventListener("input", () => { titleText.textContent = name.value.trim() || id.value.trim() || t("dockerAgentNew"); });
@@ -350,18 +407,23 @@
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"); labelPublish.checked = value.label_publish === true;
- const labelField = checkboxField("dockerLabelPublish", labelPublish); labelField.append(el("small", t("dockerLabelPublishHelp"), "fine"));
- const testButton = el("button", t("dockerTestConnection"), "outline docker-agent-test"), testResult = el("small", "", "fine docker-agent-test-result"); testButton.type = "button";
+ 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);
+ labelHelp.append(el("span", t("dockerLabelPublishHelp")), labelInfo); labelField.append(labelHelp);
+ let closeBubble = null;
+ const showBubble = (text, kind) => {
+ testResult.textContent = text; testResult.className = `docker-agent-test-result${kind ? ` is-${kind}` : ""}`; testResult.hidden = false;
+ if (!closeBubble) { closeBubble = event => { if (!testWrap.contains(event.target)) { testResult.hidden = true; document.removeEventListener("pointerdown", closeBubble); closeBubble = null; } }; document.addEventListener("pointerdown", closeBubble); }
+ };
+ testResult.addEventListener("click", () => { testResult.hidden = true; });
testButton.addEventListener("click", async () => {
- testButton.disabled = true; testResult.className = "fine docker-agent-test-result"; testResult.textContent = t("dockerTestRunning");
+ testButton.disabled = true; showBubble(t("dockerTestRunning"), "running");
try {
const data = await api("/api/docker/test", { method: "POST", body: JSON.stringify({ endpoint: endpoint.value.trim().replace(/\/$/, ""), token: token.value, tls_fingerprint_sha256: fingerprint.value.trim() || null }) });
- if (data.ok) { testResult.classList.add("is-ok"); testResult.textContent = t("dockerTestOk").replace("{host}", data.hostname || "-").replace("{version}", data.agent_version || "-").replace("{services}", data.services ?? 0).replace("{ms}", data.elapsed_ms ?? "-"); }
- else { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${data.error || "-"}`; }
- } catch (error) { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${error.message}`; }
+ if (data.ok) showBubble(t("dockerTestOk").replace("{host}", data.hostname || "-").replace("{version}", data.agent_version || "-").replace("{services}", data.services ?? 0).replace("{ms}", data.elapsed_ms ?? "-"), "ok");
+ else showBubble(`${t("dockerTestFailed")}: ${data.error || "-"}`, "error");
+ } catch (error) { showBubble(`${t("dockerTestFailed")}: ${error.message}`, "error"); }
finally { testButton.disabled = false; }
});
- const testRow = el("div", undefined, "docker-agent-test-row"); testRow.append(testButton, testResult);
const grid = el("div", undefined, "field-grid docker-agent-grid");
const idField = labeled("dockerAgentId", id);
grid.append(labeled("dockerAgentName", name), idField, labeled("dockerAgentEndpoint", endpoint, t("dockerAgentEndpointHelp")), labeled("dockerAgentToken", token), labeled("dockerTlsFingerprint", fingerprint, t("dockerTlsFingerprintHelp")), labeled("dockerPollInterval", poll, t("dockerPollIntervalHelp")), domainsField, certificateField, labeled("dockerDefaultTarget", target.node, t("dockerDefaultTargetHelp")), defaultAclField, labelField);
@@ -369,7 +431,7 @@
const listenerControl = window.rustProxyIntegrations.bindings(listenerField, value.listener_ids || [], !agent); listenerField.querySelector(".listener-choices")?.classList.add("docker-agent-listener-choices"); row._readListeners = listenerControl.read; grid.append(listenerField);
const security = el("div", undefined, "docker-agent-security"), secBadge = el("span", "", "pill docker-agent-security-badge"), secHint = el("span", "", "fine docker-agent-security-hint"); security.append(secBadge, secHint);
const diagnostics = el("div", undefined, "docker-agent-diagnostics"); diagnostics.dataset.agentId = agent?.id || ""; renderAgentDiagnostics(diagnostics);
- endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, provision, diagnostics, security, testRow, grid); updateSecurityBadge(row);
+ endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, provision, diagnostics, security, grid); updateSecurityBadge(row);
window.rustProxyAutoId.attach(id, { elements: [name], taken: () => [...(cfg().agents || []).map(item => item.id), ...[...document.querySelectorAll("#docker-agent-settings-list .docker-agent-id")].filter(node => node !== id).map(node => node.value.trim())].filter(Boolean) });
return row;
}
@@ -618,6 +680,35 @@
const saved = await saveSection("docker-agents", current); if (saved) row.classList.remove("is-dirty"); return saved;
}
+ function shortUptime(started) {
+ const since = Date.parse(started || ""); if (!Number.isFinite(since)) return "";
+ let seconds = Math.max(0, Math.floor((Date.now() - since) / 1000)); const days = Math.floor(seconds / 86400); seconds %= 86400; const hours = Math.floor(seconds / 3600), minutes = Math.floor(seconds % 3600 / 60);
+ return days ? `${days}d ${hours}h` : hours ? `${hours}h ${minutes}m` : `${minutes}m`;
+ }
+ function containerChip(label, value, cls = "", ratio = null) {
+ const chip = el("span", undefined, `docker-container-chip ${cls}`.trim()); chip.append(el("span", label, "docker-container-chip-label"), el("b", value));
+ if (ratio != null) { const bar = el("span", undefined, "docker-container-chip-bar"), fill = el("i"); const pct = Math.max(0, Math.min(100, ratio * 100)); fill.style.width = `${pct.toFixed(1)}%`; if (pct >= 90) chip.classList.add("is-danger"); else if (pct >= 75) chip.classList.add("is-warn"); bar.append(fill); chip.append(bar); }
+ return chip;
+ }
+ function containerStateLine(container) {
+ const line = el("span", undefined, "docker-container-state"), state = String(container.state || "");
+ if (state) {
+ const stateCls = state === "running" ? "live" : ["restarting", "exited", "dead", "removing"].includes(state) ? "danger" : "warn";
+ const pill = el("span", state, `pill docker-container-pill ${stateCls}`); const uptime = state === "running" ? shortUptime(container.started_at) : "";
+ if (uptime) pill.append(el("small", ` ${uptime}`, "docker-container-uptime"));
+ if (container.started_at) pill.title = `${t("dockerContainerStarted")}: ${new Date(container.started_at).toLocaleString()}`;
+ line.append(pill);
+ }
+ if (container.health) {
+ const healthText = { healthy: t("dockerContainerHealthy"), unhealthy: t("dockerContainerUnhealthy"), starting: t("dockerContainerHealthStarting"), none: t("dockerContainerNoHealthcheck") }[container.health] || container.health;
+ const healthCls = { healthy: "live", unhealthy: "danger", starting: "warn" }[container.health] || "muted";
+ const pill = el("span", healthText, `pill docker-container-pill docker-container-health ${healthCls}`); if (container.health === "none") pill.title = t("dockerContainerNoHealthcheckHelp"); line.append(pill);
+ }
+ if (container.cpu_percent != null) { const cpu = Number(container.cpu_percent); line.append(containerChip("CPU", `${cpu.toFixed(1)}%`, "", cpu / 100)); }
+ if (container.memory_bytes != null) { const used = Number(container.memory_bytes), limit = Number(container.memory_limit_bytes || 0); const chip = containerChip("RAM", bytes(used), "", limit ? used / limit : null); if (limit) chip.title = `${bytes(used)} / ${bytes(limit)} (${percent(used, limit).toFixed(1)}%)`; line.append(chip); }
+ if (container.restart_count != null) { const restarts = Number(container.restart_count); const chip = containerChip(t("dockerContainerRestarts"), fmt(restarts), restarts > 0 ? "is-warn" : ""); line.append(chip); }
+ return line;
+ }
function assignmentRow(agent, inventory, service, assignment, stale = false) {
const key = assignment?.service_key || service.key, row = el("article", undefined, "docker-service-row"); row.dataset.key = key; row.dataset.viewKey = viewKey(agent.id, key); if (assignment?.from_labels) row.dataset.fromLabels = "1";
const runtime = runtimeFor(agent.id, key), member = runtime?.members?.[0], technicalName = service?.technical_name || assignment?.service_key || "";
@@ -638,16 +729,7 @@
if (issue) { const badge = el("span", t("dockerLabelIssue"), "pill warn docker-label-badge"); badge.title = issue.error; meta.append(badge); }
const container = service?.container;
if (container && (container.state || container.health || container.cpu_percent != null || container.memory_bytes != null)) {
- const stateLine = el("span", undefined, "docker-container-state"), healthCls = container.health === "unhealthy" || ["restarting", "exited", "dead"].includes(container.state) ? "danger" : container.health === "healthy" ? "live" : "";
- const healthText = { healthy: t("dockerContainerHealthy"), unhealthy: t("dockerContainerUnhealthy"), starting: t("dockerContainerHealthStarting"), none: t("dockerContainerNoHealthcheck") }[container.health] || container.health;
- if (container.state || container.health) { const pill = el("span", [container.state, healthText].filter(Boolean).join(" · "), `pill ${healthCls}`.trim()); if (container.health === "none") pill.title = t("dockerContainerNoHealthcheckHelp"); stateLine.append(pill); }
- const parts = [];
- if (container.cpu_percent != null) parts.push(`CPU ${Number(container.cpu_percent).toFixed(1)}%`);
- if (container.memory_bytes != null) parts.push(`RAM ${bytes(Number(container.memory_bytes))}${container.memory_limit_bytes ? ` / ${bytes(Number(container.memory_limit_bytes))}` : ""}`);
- if (container.restart_count != null) parts.push(`${t("dockerContainerRestarts")}: ${fmt(container.restart_count)}`);
- if (parts.length) stateLine.append(el("small", parts.join(" · "), "fine"));
- if (container.started_at) stateLine.title = `${t("dockerContainerStarted")}: ${container.started_at}`;
- meta.append(stateLine);
+ meta.append(containerStateLine(container));
}
const visibility = el("button", "", "quiet docker-view-toggle"); visibility.type = "button";
const syncVisibility = () => { visibility.textContent = t(hiddenVhosts.has(row.dataset.viewKey) ? "dockerUnhideVhost" : "dockerHideVhost"); }; syncVisibility(); visibility.addEventListener("click", () => { const key = row.dataset.viewKey; if (hiddenVhosts.has(key)) hiddenVhosts.delete(key); else hiddenVhosts.add(key); saveHidden(); syncVisibility(); applyViewFilters(); });
@@ -698,8 +780,14 @@
const certificateBar = el("div", undefined, "docker-service-certificate-bar");
const certificateHint = el("small", "", "fine docker-certificate-hint"); certificateBar.append(mismatchLabel, certificateHint);
const syncCertificateHint = () => {
- const ids = agentCertificates(agent); if (!ids.length) { certificateHint.textContent = t("dockerCertificateHintAuto"); return; }
- const hosts = [expandedHost(host.value.trim() || technical, domainSelect.value), ...aliases.peek().map(alias => expandedHost(alias, domainSelect.value))].filter(Boolean);
+ const ids = agentCertificates(agent), hosts = [expandedHost(host.value.trim() || technical, domainSelect.value), ...aliases.peek().map(alias => expandedHost(alias, domainSelect.value))].filter(Boolean);
+ certificateHint.classList.remove("is-warn");
+ if (!ids.length) {
+ const all = (envelope?.config?.tls?.certificates || []).map(cert => cert.id), uncovered = hosts.filter(name => !pickCertificate(all, [name])), picked = hosts.length ? pickCertificate(all, hosts.slice(0, 1)) : "";
+ if (uncovered.length) { certificateHint.textContent = t("dockerCertificateHintAutoMissing").replace("{hosts}", uncovered.join(", ")); certificateHint.classList.add("is-warn"); }
+ else certificateHint.textContent = picked ? t("dockerCertificateHintAutoMatched").replace("{id}", picked) : t("dockerCertificateHintAuto");
+ return;
+ }
const picked = pickCertificate(ids, hosts);
certificateHint.textContent = picked ? t("dockerCertificateHintMatched").replace("{id}", picked) : t(certMismatch.checked ? "dockerCertificateHintForced" : "dockerCertificateHintGeneric").replace("{id}", ids[0]);
};
diff --git a/src/admin/web/docs.css b/src/admin/web/docs.css
index de593bb..1468712 100644
--- a/src/admin/web/docs.css
+++ b/src/admin/web/docs.css
@@ -415,4 +415,4 @@ html[data-corner-style=extra] {
.swagger-ui input,
.swagger-ui textarea {
border-radius: var(--rp-docs-radius-control, 0);
-}
\ No newline at end of file
+}.reader-target { outline: 2px solid var(--accent, #f69b74); outline-offset: 4px; transition: outline-color 1s; }
diff --git a/src/admin/web/docs.js b/src/admin/web/docs.js
index e40f62d..f03f5a5 100644
--- a/src/admin/web/docs.js
+++ b/src/admin/web/docs.js
@@ -99,12 +99,16 @@
const parsed = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(token); const anchor = document.createElement("a");
anchor.textContent = parsed[1]; const target = parsed[2].trim();
if (/^https?:\/\//i.test(target)) { anchor.href = target; anchor.target = "_blank"; anchor.rel = "noreferrer"; }
- else if (target.startsWith("#")) { anchor.href = target; }
+ else if (target.startsWith("#")) {
+ const section = target.slice(1);
+ anchor.href = `#doc=${encodeURIComponent(basePath)}§ion=${encodeURIComponent(section)}`;
+ anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(basePath, true, section); });
+ }
else {
- const resolved = normalizeDocPath(basePath, target);
+ const resolved = normalizeDocPath(basePath, target), section = target.includes("#") ? target.slice(target.indexOf("#") + 1) : "";
if (docsByPath.has(resolved)) {
- anchor.href = `#doc=${encodeURIComponent(resolved)}`;
- anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(resolved, true); });
+ anchor.href = `#doc=${encodeURIComponent(resolved)}${section ? `§ion=${encodeURIComponent(section)}` : ""}`;
+ anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(resolved, true, section); });
} else { anchor.href = target; }
}
parent.append(anchor);
@@ -114,6 +118,14 @@
if (offset < text.length) parent.append(document.createTextNode(text.slice(offset)));
}
+ function headingSlug(text) {
+ return String(text || "").trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");
+ }
+ function scrollToSection(section) {
+ if (!section) { element("docs-reader-content").scrollTop = 0; return; }
+ const node = element("docs-reader-content").querySelector(`[id="${CSS.escape(section)}"]`);
+ if (node) { node.scrollIntoView({ block: "start" }); node.classList.add("reader-target"); setTimeout(() => node.classList.remove("reader-target"), 1600); }
+ }
function renderMarkdown(documentInfo) {
const target = element("docs-reader-content"); target.replaceChildren();
const lines = documentInfo.content.replaceAll("\r\n", "\n").split("\n");
@@ -139,7 +151,7 @@
}
table = null;
const heading = /^(#{1,4})\s+(.+)$/.exec(line);
- if (heading) { flushParagraph(); closeList(); const h = document.createElement(`h${heading[1].length}`); appendInline(h, heading[2], documentInfo.path); target.append(h); continue; }
+ if (heading) { flushParagraph(); closeList(); const h = document.createElement(`h${heading[1].length}`); appendInline(h, heading[2], documentInfo.path); h.id = headingSlug(h.textContent); target.append(h); continue; }
const bullet = /^\s*[-*]\s+(.+)$/.exec(line), ordered = /^\s*\d+\.\s+(.+)$/.exec(line);
if (bullet || ordered) {
flushParagraph(); const tag = ordered ? "ol" : "ul";
@@ -170,10 +182,11 @@
}
if (!root.children.length) { const empty = document.createElement("div"); empty.className = "reader-empty"; empty.textContent = t("docsReaderEmpty"); root.append(empty); }
}
- function selectDocument(path, updateHash = false) {
+ function selectDocument(path, updateHash = false, section = "") {
const item = docsByPath.get(path) || docsByPath.get("docs/README.md") || documents[0]; if (!item) return;
- currentDocument = item; renderReaderList(); renderMarkdown(item);
- if (updateHash) history.replaceState(null, "", `#doc=${encodeURIComponent(item.path)}`);
+ if (currentDocument !== item) { currentDocument = item; renderReaderList(); renderMarkdown(item); }
+ if (updateHash) history.replaceState(null, "", `#doc=${encodeURIComponent(item.path)}${section ? `§ion=${encodeURIComponent(section)}` : ""}`);
+ requestAnimationFrame(() => scrollToSection(section));
}
function selectTab(tab) {
@@ -201,9 +214,14 @@
window.document.querySelectorAll("[data-i18n]").forEach(n => n.textContent = t(n.dataset.i18n)); window.document.querySelectorAll("[data-i18n-placeholder]").forEach(n => n.placeholder = t(n.dataset.i18nPlaceholder));
session = info; spec = documentSpec; documents = Array.isArray(docBundle.documents) ? docBundle.documents : []; docsByPath = new Map(documents.map(item => [item.path, item]));
element("docs-session").textContent = `${t("docsAccount")}: ${session.username}`; element("docs-error").textContent = "";
- const hash = new URLSearchParams(location.hash.replace(/^#/, "")).get("doc"); selectDocument(hash && docsByPath.has(hash) ? hash : "docs/README.md"); selectTab("reader");
+ const params = new URLSearchParams(location.hash.replace(/^#/, "")), hash = params.get("doc"); currentDocument = null; selectTab("reader"); selectDocument(hash && docsByPath.has(hash) ? hash : "docs/README.md", false, params.get("section") || "");
} catch (error) { if (mine === epoch) { clear(); element("docs-error").textContent = error.message; } }
}
+ window.addEventListener("hashchange", () => {
+ if (!session) return;
+ const params = new URLSearchParams(location.hash.replace(/^#/, "")), path = params.get("doc");
+ if (path && docsByPath.has(path)) { selectTab("reader"); selectDocument(path, false, params.get("section") || ""); }
+ });
document.addEventListener("visibilitychange", () => { if (!document.hidden && session) void checkSession().catch(() => expired()); });
window.addEventListener("pageshow", event => { if (event.persisted) { clear(); void boot(); } });
setInterval(() => { if (!document.hidden && session) void checkSession().catch(() => expired()); }, 30000);
diff --git a/src/admin/web/index.html b/src/admin/web/index.html
index ce31231..9b02ff6 100644
--- a/src/admin/web/index.html
+++ b/src/admin/web/index.html
@@ -279,75 +279,127 @@
Process
- i
-
-
RSS is the real process
- footprint. HOT/transient cache values are RustProxy-accounted
- allocations; transform memory is a conservative active reservation.
- Non-cache RSS is RSS minus accounted cache and includes transforms,
- connections, TLS, logging, Tokio/runtime state, allocator overhead and
- other buffers, so these rows are not all additive.
-
-
+
i
+
+
RSS is the real process
+ footprint. HOT/transient cache values are RustProxy-accounted
+ allocations; transform memory is a conservative active reservation.
+ Non-cache RSS is RSS minus accounted cache and includes transforms,
+ connections, TLS, logging, Tokio/runtime state, allocator overhead and
+ other buffers, so these rows are not all additive.
+
+
-
-
Platform -
-
OS threads -
-
Process start -
-
Uptime -
+
+
Platform
+ -
+
+
+
OS threads
+ -
+
+
+
Process start
+ -
+
+
+
Uptime
+ -
+
Load
-
CPU (100% = 1 core) -
-
RSS total
-
File descriptors / limit -
-
cgroup RAM / limit -
+
+
CPU (100% = 1 core)
+ -
+
+
+
RSS total
+
+
+
+
File descriptors / limit
+ -
+
+
+
cgroup RAM / limit
+ -
+
Memory
-
+
-
Anonymous RSS
-
File-backed / shared RSS
-
Non-cache process RSS -
-
Virtual memory / limit -
-
Data address space / swap -
+
+
Anonymous RSS
+
+
+
+
File-backed / shared RSS
+
+
+
+
Non-cache process RSS
+ -
+
+
+
Virtual memory / limit
+ -
+
+
+
Data address space / swap
+ -
+
-
Process CPU history -
-
+ Process CPU
+ history -
+
-
+
+
-
Process RSS history
-
+ Process RSS
+ history
+
-
+
-
File descriptors history -
-
+ File
+ descriptors history -
+
-
+
-
OS threads history -
-
+ OS threads
+ history -
+
-
+
@@ -357,49 +409,112 @@
Memory breakdown
- i
+ i
-
Splits the process RSS into cached object data, the cache's own bookkeeping (index, keys, headers), short-lived cache buffers, memory the allocator keeps free for reuse (fragmentation; an upper bound, part of it may already be returned to the kernel), program code and mapped files, and everything else (connections, TLS, runtime, logs, GeoIP). For comparison, Varnish documents about 1 KiB of per-object overhead outside its storage size. A steadily rising "outside cache" trend while the cache is full suggests a leak; a flat one means overhead or fragmentation.
+
Splits the process RSS into
+ cached object data, the cache's own bookkeeping (index, keys, headers),
+ short-lived cache buffers, memory the allocator keeps free for reuse
+ (fragmentation; an upper bound, part of it may already be returned to
+ the kernel), program code and mapped files, and everything else
+ (connections, TLS, runtime, logs, GeoIP). For comparison, Varnish
+ documents about 1 KiB of per-object overhead outside its storage size. A
+ steadily rising "outside cache" trend while the cache is full suggests a
+ leak; a flat one means overhead or fragmentation.
-
RSS / cache -
-
Overhead / object -
-
HOT objects -
-
Fragmentation -
+
+
RSS / cache
+ -
+
+
+
Overhead / object
+ -
+
+
+
HOT objects
+ -
+
+
+
Fragmentation
+ -
+
-
-
+
+
- Cache data (object bodies) - -
- Cache bookkeeping - -
- Cache buffers (fills, queues) - -
- Free, held by allocator - -
- Code and mapped files - -
- Rest of process - -
+ Cache
+ data (object bodies) - -
+ Cache
+ bookkeeping - -
+ Cache
+ buffers (fills, queues) - -
+ Free, held by allocator - -
+ Code and
+ mapped files - -
+
+ Rest of
+ process - -
Allocator
-
Heap (arenas) -
-
In use -
-
Free, held -
-
Large blocks (mmap) · count -
+
+
Heap (arenas)
+ -
+
+
+
In use
+ -
+
+
+
Free, held
+ -
+
+
+
Large blocks (mmap) · count
+ -
+
- Allocator statistics are available only with the default glibc allocator.
+ Allocator statistics are available only
+ with the default glibc allocator.
- Outside cache -
-
+ Outside
+ cache -
+
-
+
-
+
@@ -421,98 +536,100 @@
-
-
-
-
Platform
- -
-
-
-
CPU (100% = 1 core)
- -
-
-
-
File descriptors / limit
- -
-
-
-
OS threads
- -
-
-
-
Virtual memory / limit
- -
-
-
-
Process start
- -
-
-
-
Uptime
- -
-
-
-
RSS total
-
-
-
-
HOT cache RAM / limit
- -
-
-
-
Cache transient RAM / limit
- -
-
-
-
Transform reserved RAM / budget
- -
-
-
-
Active transforms / limit
- -
-
-
-
Non-cache process RSS
-
-
-
-
Anonymous RSS
-
-
-
-
File-backed / shared RSS
-
-
-
-
Data address space / swap
- -
-
-
-
cgroup RAM / limit
- -
-
+
+
+
Platform
+ -
+
+
+
CPU (100% = 1 core)
+ -
+
+
+
File descriptors / limit
+ -
+
+
+
OS threads
+ -
+
+
+
Virtual memory / limit
+ -
+
+
+
Process start
+ -
+
+
+
Uptime
+ -
+
+
+
RSS total
+
+
+
+
HOT cache RAM / limit
+ -
+
+
+
Cache transient RAM / limit
+ -
+
+
+
Transform reserved RAM / budget
+ -
+
+
+
Active transforms / limit
+ -
+
+
+
Non-cache process RSS
+
+
+
+
Anonymous RSS
+
+
+
+
File-backed / shared RSS
+
+
+
+
Data address space / swap
+ -
+
+
+
cgroup RAM / limit
+ -
+
-
-
Process CPU
- history -
-
-
-
-
+
+
Process
+ CPU
+ history -
+
+
+
+
+
+
+
Process
+ RSS
+ history
+
+
+
+
+
-
-
Process RSS
- history
-
-
-
-
-
-
@@ -585,10 +702,10 @@
Search
backends
+ data-i18n-placeholder="backendSearchPlaceholder" id="bo-search" type="search" />
Sort
- by
+ by
↑
@@ -663,19 +780,26 @@
Traffic/s
- Req/s
- HTTP codes
- p95 / p99
- HTTP
+ codes
+ p95 /
+ p99
+ Cache
- Probe
- Error causes
- Error
+ causes
+ Protocol
Client
@@ -715,7 +839,8 @@
Latency
Traffic/s
Req/s
- HTTP codes
+ HTTP codes
+
p95 / p99
Cache
Probe
@@ -827,8 +952,9 @@
aria-expanded="false" disabled>Expand all statisticsDocker agents
settings Hide disabled Show hidden
+ id="docker-hide-disabled" type="button" disabled>Hide disabledShow
+ hidden
@@ -973,8 +1099,9 @@
Display name
- Profile ID
+ Profile ID
@@ -1597,9 +1724,10 @@
Saved in SQLite. Changes take effect on the
next process start; the administration listener is configured separately.
+
+
Add listener
Privileged ports may need CAP_NET_BIND_SERVICE.
Do not run the whole application as root.
-
-
Save listeners
@@ -2292,14 +2426,16 @@
Docker agents
LIVE APPLY
- Configure one agent per Docker or Podman host.
+
Configure one agent per Docker or Podman
+ host.
Paste the provisioning code printed by "rustproxy-docker-agent provision-code" to
fill in the endpoint, token and pinned certificate at once. Each agent has its own
domains, certificates and optional default backend IP.
- Add
- Docker agent Paste provisioning code
+ Add
+ Docker agent Paste provisioning code
Save and connect agents
@@ -2336,6 +2472,8 @@
backend on all public HTTP vhosts, redirects and 404 hosts. Per-vhost
restrictions remain active; a local allow cannot bypass a global block.
Administration and TCP/UDP Streams are excluded.
+
Country access
@@ -2352,10 +2490,10 @@
Allow listed only
-
ISO country codes (one per
- line)
+
Countries
@@ -2595,9 +2733,20 @@
data-i18n="cacheTabCold" type="button">Cold cache
Static & diagnostics
+ Rules
+
-Fallback TTL for public
+ Fallback TTL for public
responses (0 = off)
- Memory and limits
-
+
Memory and
+ limits
+
Memory sizing
-
@@ -2707,7 +2857,7 @@
When HOT memory is above the target,
only entries idle for the configured age are removed in bounded passes. Active
objects are not purged.
-
+
-
-
System information
-
API Refresh now
+
System information
+
- - Copy diagnostics Refresh
+ now
- Read-only information from the
- authenticated system-info API. Unavailable metrics are not estimated.
+
- Operating system and hardware
-
+
+
+
Architecture
+ -
+
+
+
Kernel
+ -
+
+
+
Logical CPUs
+ -
+
+
+
RAM
+ -
+
+
+
Swap
+ -
+
+
+
System uptime
+ -
+
+
+
RustProxy uptime
+ -
+
+
-
-
-
ACME / Python environment
-
- Versions refer to the interpreter and
- tools actually selected for certificate management, not an arbitrary Python
- installation.
-
-
-
-
-
Data locations
-
-
+
+
System CPU - -
+
+
+
+
+
+
RustProxy CPU - 100% = 1 core
+
+
+
+
+
+
Load average - -
+
RAM used / total - -
+
File descriptors /
+ limit - -
+
+
+
+
+
RustProxy process -
+
+ Resident memory
+
+
+ HOT cache -
+ Transient -
+ Anonymous -
+ File-backed
+ -
+
+
+
+ Budgets
+
+
+
HOT cache / limit
+ -
+
+
+
Transient / limit
+ -
+
+
+
Transforms in flight / budget
+
+ -
+
+
+
+
+ Process
+
+
+
Process start
+ -
+
+
+
Virtual memory
+ -
+
+
+
Swap
+ -
+
+
+
Disk read / written
+ -
+
+
+
cgroup RAM / limit
+ -
+
+
+
+
+
+
+
+
Network -
+
+
+
+ -
+
+
+
+
RX
+ / TX history -
+
+
+
+
+
+
RX TX
+
+
+
+
+
+
+
Certificate toolchain -
+
+
+
+
Python
+ -
+
+ →
+
+
pip
+ -
+
+ →
+
+
Certbot
+ -
+
+
+ -
+
+
+
Managed environment
+
+
-Copy
+
+
+
+
+
+
+
Data locations
+
+
+
+
Data directory
+
+
-Copy
+
+
+
+
+
+
+
-
+
-
Certificate API SCOPED TOKENS
+
Certificate API
+
New
+ key Revoke all tokens
- Separate Key ID + Bearer Token
- credentials are reload-only by default and restricted to explicit certificate IDs.
- Deploy is optional; tokens cannot read configuration or use other administration
- APIs.
+ Keys for certificate automation.
+ Certificate API documentation OPNsense ACME client integration
- Edit the settings below without changing the bearer token. Key ID cannot be
- changed.
- Key ID
- Comment
- Allowed certificate
- IDs
- List one or more
- certificate IDs separated by commas or new lines. The token can act only on these
- IDs.
- Also allow deploy
- Leave disabled for Certbot
- renewal hooks. Reload-only is the recommended least-privilege mode.
- Bearer
- token (optional custom
- value)
- Each cleartext token is shown only
- after generation/rotation. RustProxy stores only its hash.
- Generate / rotate token Cancel
- edit Revoke all tokens
-
-
Copy this token now
+
+
Copy
+
Copy this token now
+
+
+ The token does not change.
+
+ Key ID
+ Comment
+
+
+ Permissions
+ Reload only Certbot /
+ acme.sh hooks
+ Deploy and
+ reload Uploads
+ certificates
+
+
+
Allowed certificates
+
+
+
+
+
+ Custom token (optional)
+
+
+ Leave empty to generate
+ a strong token.
+
+ Cancel
+
-
External automation sends the Key ID
- header and Bearer token over HTTPS (or loopback HTTP). Reload tokens use the
- targeted
- /api/certificates/{id}/reload endpoint; token access cannot trigger global reload.
-
-
-
+
+ Usage example
+ External automation sends the
+ Key ID header and Bearer token over HTTPS.
+
+
+
@@ -3535,36 +3899,67 @@
type="button">Administration audit
-
+
API tokens (RO/RW)
+
New
+ token
- Generate independent API tokens
- with read-only or read-write access, restricted to your client IP/CIDR. Existing
- browser login remains available. Non-loopback requests require HTTPS.
-
- Description
- Permissions
- Read only (RO)
- Read and write (RW)
-
-
- Allowed source IP/CIDR (one per
- line)
- Generate API token
+ Tokens for external API clients.
+
+ API
+ tokens documentation
+
+
+
Copy
+
+
Copy the token now.
+
+
+ New API token
+
+ Description
+
+
+ Permissions
+ Read only (RO) Status,
+ metrics, configuration read
+ Read and write
+ (RW) Also changes
+ configuration
+
+
+
Allowed source addresses
+
+
IP or CIDR, Enter after
+ each.
+
+ Generate API token Cancel
- Copy the
- token now — it will not be displayed again
-
-
-
- curl -H 'Authorization: Bearer $RUSTPROXY_API_TOKEN' https://panel.example.com/api/config
+
+
+ Usage example (curl)
+
+
Validate, save and apply
- Discard changes Cancel
+ Discard
+ changes Cancel
@@ -4471,7 +4868,8 @@ log_errors = On
Validate,
save and apply Discard changes Cancel
+ type="button">Discard changesCancel
Private IP binding is not authentication. Keep firewall/ACL rules.
HSTS preload is opt-in; affinity cookies are not login sessions.
@@ -4496,8 +4894,8 @@ log_errors = On
Redirect hosts do not contact a backend. Global host ACLs
still apply. Avoid self-referential rules that can create browser redirect loops.
@@ -4554,8 +4953,8 @@ log_errors = On
@@ -4623,7 +5023,8 @@ log_errors = On
Validate,
save and apply Discard changes Cancel
+ type="button">Discard changes
Cancel
Changing a stream listener requires a RustProxy restart.
@@ -4689,17 +5090,18 @@ log_errors = On
diff --git a/src/admin/web/integrations.js b/src/admin/web/integrations.js
index c166546..7b760a2 100644
--- a/src/admin/web/integrations.js
+++ b/src/admin/web/integrations.js
@@ -60,7 +60,7 @@
input.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,]/.test(value.trim())) return; event.preventDefault(); try { consume(value); } catch (error) { toast(error.message, true); } });
box.append(input); wrapper.append(box, label("p", locked.size ? "listenerStartupLocked" : "listenerAddressesHelp", "fine")); parent.append(wrapper);
for (const value of initial) { try { add(value, false); } catch { } }
- const read = () => { if (input.value.trim()) consume(input.value); return [...values]; }; read.input = input; return read;
+ const read = () => { if (input.value.trim()) consume(input.value); return [...values]; }; read.input = input; read.peek = () => [...values]; return read;
}
const h2Defaults = { idle_timeout_seconds: 300, max_connection_lifetime_seconds: 0, drain_timeout_seconds: 10 };
const effectiveHttp2Settings = binding => ({ ...h2Defaults, ...(envelope?.config.http2 || {}), ...(binding?.http2_settings || {}) });
@@ -116,7 +116,17 @@
}
function addRow(item = { id: `listener-${$("named-listener-rows").children.length + 1}`, name: "", scope: "internal", enabled: true, binding: { address: "127.0.0.1:8181", tls: false, http2: false, http2_settings: null, h2c: false, http3: null } }) {
if ($("named-listener-rows").children.length >= 64) { toast(t("listenerLimit"), true); return; }
- const row = el("fieldset", undefined, "named-listener-row"); row.append(label("legend", "listenerEndpoint")); const grid = el("div", undefined, "vh-grid"); row.append(grid); const b = item.binding || {};
+ const fresh = !item.id || !(envelope?.config.listeners?.endpoints || []).some(endpoint => endpoint.id === item.id);
+ const row = el("fieldset", undefined, `named-listener-row listener-card${fresh ? "" : " is-collapsed"}`);
+ const head = el("button", undefined, "listener-card-head"); head.type = "button"; head.dataset.uiIconName = "none";
+ const headTitle = el("span", undefined, "listener-card-title"), headBadges = el("span", undefined, "listener-card-badges"), headAddresses = el("span", undefined, "listener-card-addresses");
+ head.append(el("span", "", "listener-card-chevron"), headTitle, headAddresses, headBadges);
+ const body = el("div", undefined, "listener-card-body");
+ row.append(head, body);
+ const expand = open => { row.classList.toggle("is-collapsed", !open); head.setAttribute("aria-expanded", String(open)); };
+ head.addEventListener("click", () => expand(row.classList.contains("is-collapsed")));
+ head.setAttribute("aria-expanded", String(fresh));
+ const grid = el("div", undefined, "vh-grid"); body.append(grid); const b = item.binding || {};
const id = field(grid, "listener-id", "listenerId", item.id, "text", { required: true, maxLength: 64, pattern: "[A-Za-z0-9_\\-]{1,64}" });
const name = field(grid, "listener-name", "listenerName", item.name, "text", { maxLength: 96 });
const scope = field(grid, "listener-scope", "listenerScope", item.scope || "internal", "select", { values: [["internal", "listenerInternal"], ["public", "listenerPublic"]] });
@@ -127,7 +137,7 @@
const enabled = field(grid, "listener-enabled", "vhEnabled", item.enabled !== false, "checkbox");
const tls = field(grid, "listener-tls", "vhTls", !!b.tls, "checkbox"); const h2 = field(grid, "listener-h2", "vhHttp2", b.tls && b.http2 !== false, "checkbox"); const h2c = field(grid, "listener-h2c", "listenerH2c", !b.tls && !!b.h2c, "checkbox");
const preservedHttp2 = effectiveHttp2Settings(b);
- const protocolActions = el("div", undefined, "listener-protocol-settings-actions vh-wide"); row.append(protocolActions);
+ const protocolActions = el("div", undefined, "listener-protocol-settings-actions vh-wide"); body.append(protocolActions);
const h2Settings = button(protocolActions, "h2Configure", () => {
window.rustProxySettings?.select("connections");
window.rustProxySettings?.selectHttpTab?.("http2");
@@ -146,25 +156,40 @@
h2.disabled = !tls.checked; h2c.disabled = tls.checked; h3.disabled = !tls.checked;
h2Settings.hidden = !((tls.checked && h2.checked) || (!tls.checked && h2c.checked));
h3Settings.hidden = !tls.checked || !h3.checked;
+ syncHead();
+ };
+ const syncHead = () => {
+ headTitle.replaceChildren(el("b", name.value.trim() || id.value.trim() || "-"), el("code", id.value.trim(), "listener-card-id"));
+ let addresses = []; try { addresses = readAddresses.peek ? readAddresses.peek() : []; } catch { }
+ headAddresses.replaceChildren(...addresses.map(value => el("span", value, "certificate-api-chip")));
+ const badges = [[scope.value === "public" ? t("listenerPublic") : t("listenerInternal"), scope.value === "public" ? "warn" : ""]];
+ if (tls.checked) badges.push(["TLS", "live"]);
+ badges.push(["H1", ""]);
+ if ((tls.checked && h2.checked) || (!tls.checked && h2c.checked)) badges.push([tls.checked ? "H2" : "h2c", ""]);
+ if (tls.checked && h3.checked) badges.push(["H3", ""]);
+ if (!enabled.checked) badges.push([t("vhDisabled"), "danger"]);
+ headBadges.replaceChildren(...badges.map(([text, cls]) => el("span", text, `pill ${cls}`.trim())));
};
for (const input of [tls, h2, h2c, h3]) input.addEventListener("change", sync);
+ for (const type of ["input", "change", "keyup"]) row.addEventListener(type, syncHead); body.addEventListener("click", () => setTimeout(syncHead));
sync();
- const removeButton = button(row, "remove", () => { if (startupLocked) return; const users = (envelope?.config.vhosts || []).filter(v => v.frontend.listener_ids?.includes(id.value.trim())); if (users.length) { toast(`${t("listenerInUse")}: ${users.map(v => v.id).join(", ")}`, true); return; } row.remove(); setSettingsDirty("listeners-form"); });
+ const removeButton = button(body, "remove", () => { if (startupLocked) return; const users = (envelope?.config.vhosts || []).filter(v => v.frontend.listener_ids?.includes(id.value.trim())); if (users.length) { toast(`${t("listenerInUse")}: ${users.map(v => v.id).join(", ")}`, true); return; } row.remove(); setSettingsDirty("listeners-form"); });
if (startupLocked) {
row.classList.add("listener-startup-locked");
enabled.disabled = true;
tls.disabled = true;
removeButton.disabled = true;
removeButton.title = t("listenerStartupLocked");
- row.append(label("p", "listenerStartupLocked", "fine"));
+ body.append(label("p", "listenerStartupLocked", "fine"));
}
- row.read = () => {
+ const readRow = () => {
const addresses = readAddresses();
if (!addresses.length || addresses.length > 16 || new Set(addresses).size !== addresses.length) throw fieldError(readAddresses.input, t("listenerAddressesInvalid"));
if (addresses.length > 1 && addresses.some(value => /^0\.0\.0\.0:/.test(value) || /^\[?::\]?:/.test(value))) throw fieldError(readAddresses.input, t("listenerAddressesExplicit"));
const http2Enabled = (tls.checked && h2.checked) || (!tls.checked && h2c.checked);
return { id: id.value.trim(), name: name.value.trim(), scope: scope.value, enabled: enabled.checked, binding: { address: addresses[0], tls: tls.checked, http2: tls.checked && h2.checked, http2_settings: http2Enabled ? preservedHttp2 : null, h2c: !tls.checked && h2c.checked, http3: tls.checked && h3.checked ? (preservedHttp3 || { ...h3Defaults }) : null }, additional_addresses: addresses.slice(1) };
};
+ row.read = () => { try { return readRow(); } catch (error) { expand(true); throw error; } };
$("named-listener-rows").append(row);
}
$("add-named-listener").addEventListener("click", () => { addRow(); setSettingsDirty("listeners-form"); });
diff --git a/src/admin/web/prometheus-token.js b/src/admin/web/prometheus-token.js
index 39eed4b..4c7913b 100644
--- a/src/admin/web/prometheus-token.js
+++ b/src/admin/web/prometheus-token.js
@@ -3,7 +3,9 @@ window.rustProxyPrometheusToken = (() => {
let isConfigured = false;
const hideSecret = () => { $("prom-token-secret").textContent = ""; $("prom-token-secret-wrap").hidden = true; };
function showStatus() {
- $("prom-token-status").textContent = t(isConfigured ? "promTokenConfigured" : "promTokenMissing");
+ $("prom-token-status").textContent = t(isConfigured ? "promTokenConfigured" : "promTokenMissingShort");
+ $("prom-token-status").className = `pill ${isConfigured ? "live" : "warn"}`;
+ $("prom-token-status").title = isConfigured ? "" : t("promTokenMissing");
$("prom-token-revoke").disabled = !isConfigured;
}
async function refresh() {
@@ -25,11 +27,15 @@ window.rustProxyPrometheusToken = (() => {
finally { button.disabled = false; }
});
$("prom-token-revoke").addEventListener("click", async () => {
- if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return;
+ if (!(await appConfirm(t("promTokenRevokeConfirm"), { danger: true }))) return;
try {
await api("/api/prometheus-token", { method: "DELETE" });
isConfigured = false; hideSecret(); showStatus(); window.rustProxySettings?.render?.();
} catch (error) { toast(error.message, true); }
});
+ $("prom-token-secret-copy").addEventListener("click", async () => {
+ try { await navigator.clipboard.writeText($("prom-token-secret").textContent); toast(t("copied")); }
+ catch { const range = document.createRange(); range.selectNodeContents($("prom-token-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
+ });
return { configured: () => isConfigured, refresh, hideSecret, reset() { isConfigured = false; hideSecret(); showStatus(); } };
})();
diff --git a/src/admin/web/settings.js b/src/admin/web/settings.js
index 8344cdb..0844ee9 100644
--- a/src/admin/web/settings.js
+++ b/src/admin/web/settings.js
@@ -71,16 +71,6 @@
const target = $("api-tokens-card");
if (target) { target.scrollIntoView({ block: "start" }); target.focus({ preventScroll: true }); }
}
- $("api-tokens-security-link")?.addEventListener("click", event => {
- if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
- event.preventDefault();
- select("security");
- if (typeof location !== "undefined" && ["http:", "https:"].includes(location.protocol)) {
- const url = new URL($("api-tokens-security-link").href);
- history.replaceState({ ...(history.state || {}), panel: "settings", settingsTab: "security" }, "", `${url.pathname}${url.search}${url.hash}`);
- }
- scrollToApiTokens();
- });
const policyTabs = [...document.querySelectorAll("[data-policy-settings-tab]")].filter(button => typeof button.addEventListener === "function" && typeof button.setAttribute === "function");
function selectPolicyTab(name, focus = false) {
if (!policyTabs.some(button => button.dataset.policySettingsTab === name)) return;
@@ -170,7 +160,7 @@
if (!envelope) return; const p = { ...defaults, ...envelope.config.prometheus };
if (!settingsDirty.has("prometheus-form")) {
$("prom-enabled").checked = p.enabled; $("prom-listen").value = p.listen; $("prom-path").value = p.path;
- $("prom-cidrs").value = p.allowed_cidrs.join("\n"); $("prom-trusted-no-token").checked = !!p.allow_trusted_network_without_token;
+ $("prom-cidrs").replaceChildren(window.rustProxyChipInput.create({ className: "prom-cidr-editor", values: p.allowed_cidrs, placeholder: "127.0.0.0/8 / 10.0.0.0/24", label: t("prometheusCidrs"), limit: 64, validate: value => window.rustProxyChipInput.validCidr(value) && (value.includes("/") ? value : value.includes(":") ? `${value}/128` : `${value}/32`), invalidMessage: t("apiTokenCidrInvalid") })); $("prom-trusted-no-token").checked = !!p.allow_trusted_network_without_token;
for (const [id, key] of [["system", "include_system"], ["vhosts", "include_vhosts"], ["traffic", "include_traffic"], ["backends", "include_backends"], ["docker-vhosts", "include_docker_vhosts"], ["domains", "include_cache_domains"], ["streams", "include_streams"], ["logging", "include_logging"]]) $(`prom-${id}`).checked = p[key];
}
const status = latestStatus?.prometheus;
@@ -209,40 +199,7 @@
$("admin-listen").disabled = listenLocked; $("admin-listen-lock-note").hidden = !listenLocked;
const syncAdminTls = () => { $("admin-certificate").disabled = !$("admin-tls").checked; }; syncAdminTls();
$("admin-status").textContent = adminStatus?.restart_required ? t("restartPending") : adminStatus?.active?.tls ? `${t("administrationActiveHttps")}: ${adminStatus.active.listen}` : `${t("administrationActiveHttp")}: ${adminStatus?.active?.listen || latestStatus?.admin_listen || "-"}`;
- const runtime = latestStatus?.runtime || {};
- const system = latestStatus?.system || {};
- const hasMetric = value => value !== null && value !== undefined && Number.isFinite(Number(value));
- const humanCount = value => hasMetric(value) ? Number(value).toLocaleString(locale()) : t("unavailable");
- const humanBytes = value => hasMetric(value) ? bytes(Number(value)) : t("unavailable");
- const humanUptime = value => hasMetric(value) ? uptime(Number(value)) : t("unavailable");
- const percent = value => hasMetric(value) ? `${Number(value).toLocaleString(locale(), { maximumFractionDigits: 1 })}%` : t("unavailable");
- const ram = hasMetric(system.memory_used_bytes) || hasMetric(system.memory_total_bytes)
- ? `${humanBytes(system.memory_used_bytes)} / ${humanBytes(system.memory_total_bytes)}` : t("unavailable");
- for (const [id, value] of [
- ["runtime-platform", runtime.platform],
- ["runtime-operating-system", runtime.operating_system],
- ["runtime-kernel-version", runtime.kernel_version],
- ["runtime-architecture", runtime.architecture],
- ["runtime-logical-cpus", humanCount(system.logical_cpus)],
- ["runtime-cpu-usage", percent(system.cpu_percent)],
- ["runtime-system-memory", ram],
- ["runtime-system-uptime", humanUptime(system.system_uptime_seconds)],
- ["runtime-statistics-source", runtime.statistics_source],
- ["runtime-data-directory", runtime.data_directory],
- ["runtime-database-path", runtime.database_path]
- ]) { const node = $(id); if (node) node.textContent = value ?? t("unavailable"); }
- const certificateRuntime = runtime.certificate_runtime || {};
- const availability = flag => flag === true ? t("runtimeAvailable") : flag === false ? t("runtimeUnavailable") : t("unavailable");
- const modeLabel = certificateRuntime.status === "unavailable" ? t("certificateRuntimeUnavailable") : certificateRuntime.status === "ready" && certificateRuntime.mode === "managed" ? t("certificateRuntimeManaged") : certificateRuntime.status === "ready" && certificateRuntime.mode === "system" ? t("certificateRuntimeSystem") : t("certificateRuntimePreparing");
- const versioned = (flag, version) => version && flag === true ? `${availability(flag)} · ${version}` : availability(flag);
- for (const [id, value] of [
- ["runtime-acme-mode", modeLabel],
- ["runtime-acme-status", certificateRuntime.message ? t(certificateRuntime.message) : t("unavailable")],
- ["runtime-python", versioned(certificateRuntime.python, certificateRuntime.python_version)],
- ["runtime-pip", versioned(certificateRuntime.pip, certificateRuntime.pip_version)],
- ["runtime-certbot", versioned(certificateRuntime.certbot, certificateRuntime.certbot_version)],
- ["runtime-acme-directory", certificateRuntime.managed_directory]
- ]) { const node = $(id); if (node) node.textContent = value || t("unavailable"); }
+ window.rustProxySystemInfo?.render(latestStatus);
const policy = envelope.config.tls?.policy || { tls12: true, tls13: true, cipher_suites: [] };
if (!settingsDirty.has("tls-policy-form")) { $("tls-policy-12").checked = policy.tls12 !== false; $("tls-policy-13").checked = policy.tls13 !== false; $("tls-policy-ciphers").value = (policy.cipher_suites || []).join("\n"); $("tls-policy-pqc").checked = policy.post_quantum === true; }
@@ -281,7 +238,7 @@
});
bindSettingsForm("prometheus-form", next => {
next.prometheus = {
- enabled: $("prom-enabled").checked, listen: $("prom-listen").value.trim(), path: $("prom-path").value.trim(), allowed_cidrs: $("prom-cidrs").value.split(/[\n,]/).map(v => v.trim()).filter(Boolean), bearer_token_env: envelope?.config?.prometheus?.bearer_token_env || null, allow_trusted_network_without_token: $("prom-trusted-no-token").checked,
+ enabled: $("prom-enabled").checked, listen: $("prom-listen").value.trim(), path: $("prom-path").value.trim(), allowed_cidrs: $("prom-cidrs").firstElementChild?.read?.() || [], bearer_token_env: envelope?.config?.prometheus?.bearer_token_env || null, allow_trusted_network_without_token: $("prom-trusted-no-token").checked,
include_system: $("prom-system").checked, include_vhosts: $("prom-vhosts").checked, include_traffic: $("prom-traffic").checked, include_backends: $("prom-backends").checked, include_docker_vhosts: $("prom-docker-vhosts").checked, include_cache_domains: $("prom-domains").checked, include_streams: $("prom-streams").checked, include_logging: $("prom-logging").checked
};
}, "prometheus");
@@ -303,6 +260,24 @@
const text = await response.text(); if (epoch !== authEpoch || !authenticated) return; $("prom-preview-output").textContent = text.slice(0, 262144); $("prom-preview-output").hidden = false;
} catch (error) { if (epoch === authEpoch) toast(error.message, true); } finally { button.disabled = false; }
});
+ const HELP_CLAMP_LENGTH = 220;
+ function decorateSettings() {
+ const panel = $("panel-settings"); if (!panel) return;
+ 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.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)); };
+ node.addEventListener("click", event => { if (event.target.closest("a, button")) return; toggle(); });
+ node.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); toggle(); } });
+ });
+ }
+ let decorateQueued = false;
+ const queueDecorate = () => { if (decorateQueued) return; decorateQueued = true; requestAnimationFrame(() => { decorateQueued = false; decorateSettings(); }); };
+ if (typeof MutationObserver === "function" && $("panel-settings")) new MutationObserver(queueDecorate).observe($("panel-settings"), { childList: true, subtree: true });
+ queueDecorate();
window.rustProxySettings = { select, selectHttpTab, syncLocation, render, refreshSearch: applySettingsSearch, current: () => active, scrollToApiTokens, reset() { if (search) search.value = ""; applySettingsSearch(); select(validTab(rememberedTab) ? rememberedTab : "appearance", false, false); selectPolicyTab("block-allow"); selectCacheTab("general"); selectLoggingTab("outputs"); selectHttpTab("http2"); window.rustProxyCertificateApi?.reset(); window.rustProxyApiTokens?.reset?.(); window.rustProxyPrometheusToken?.reset?.(); $("prom-preview-output").textContent = ""; $("prom-preview-output").hidden = true; } };
select(active); render();
})();
diff --git a/src/admin/web/system-info.js b/src/admin/web/system-info.js
new file mode 100644
index 0000000..6584bbd
--- /dev/null
+++ b/src/admin/web/system-info.js
@@ -0,0 +1,245 @@
+(() => {
+ "use strict";
+ const HISTORY = 60;
+ const history = { sampled: null, cpu: [], process: [], rx: [], tx: [] };
+ let latest = null;
+ const known = value => value !== null && value !== undefined && value !== "" && Number.isFinite(Number(value));
+ const na = () => t("unavailable");
+ const size = value => known(value) ? bytes(Number(value)) : na();
+ const count = value => known(value) ? Number(value).toLocaleString(locale()) : na();
+ const percent = value => known(value) ? `${Number(value).toLocaleString(locale(), { maximumFractionDigits: 1 })}%` : na();
+ const ratio = (part, whole) => known(part) && known(whole) && Number(whole) > 0 ? Math.max(0, Math.min(100, Number(part) / Number(whole) * 100)) : 0;
+ const rate = value => known(value) ? `${bytes(Number(value))}/s` : na();
+ const setText = (id, value) => { const node = $(id); if (node) node.textContent = value ?? na(); };
+ const setMeter = (id, value) => {
+ const node = $(id); if (!node) return;
+ node.style.width = `${Math.max(0, Math.min(100, value))}%`;
+ node.classList.toggle("is-high", value >= 90);
+ };
+ const push = (list, value) => { list.push(known(value) ? Number(value) : 0); if (list.length > HISTORY) list.shift(); };
+ const points = (values, max) => {
+ if (values.length < 2) return "0,58 300,58";
+ const top = Math.max(max || 0, ...values, 1e-9);
+ return values.map((value, index) => `${(index / (values.length - 1) * 300).toFixed(1)},${(58 - value / top * 52).toFixed(1)}`).join(" ");
+ };
+ const shared = name => {
+ try {
+ const value = { cpu: () => systemSamples, process: () => processCpuSamples, rx: () => networkRxSamples, tx: () => networkTxSamples }[name]();
+ return Array.isArray(value) ? value : [];
+ } catch { return []; }
+ };
+ const series = name => { const own = history[name], overview = shared(name); return overview.length > own.length ? overview.slice(-HISTORY) : own; };
+ const setLine = (id, values, max) => { const node = $(id); if (node) node.setAttribute("points", points(values, max)); };
+
+ function record(system) {
+ const sampled = system.sampled_at_ms ?? null;
+ if (sampled === null || sampled === history.sampled) return;
+ history.sampled = sampled;
+ push(history.cpu, system.cpu_percent);
+ push(history.process, system.process_cpu_percent);
+ push(history.rx, system.network_rx_bytes_per_second);
+ push(history.tx, system.network_tx_bytes_per_second);
+ }
+
+ function liveState() {
+ const options = window.rustProxyRefresh?.current?.() || {};
+ return options.live_enabled !== false && Number(options.system_info_seconds) > 0;
+ }
+
+ function renderHost(status, runtime, system) {
+ setText("system-info-title", runtime.operating_system || t("systemInformation"));
+ const environment = system.environment ? `${t("systemInfoEnvironment")}: ${system.environment}. ` : "";
+ setText("system-info-help", `${environment}${t("systemInformationHelp")}`);
+ const live = liveState(), pill = $("system-info-live");
+ if (pill) { pill.textContent = t(live ? "systemInfoLive" : "systemInfoManual"); pill.classList.toggle("live", live); }
+ const note = $("system-info-refresh-note"); if (note) note.hidden = live;
+ const age = known(system.sampled_at_ms) ? Math.max(0, Math.round((Date.now() - Number(system.sampled_at_ms)) / 1000)) : null;
+ setText("system-info-sample-age", age === null ? "-" : t("systemInfoSampledAgo").replace("{seconds}", String(age)));
+ setText("runtime-architecture", runtime.architecture || na());
+ setText("runtime-kernel-version", runtime.kernel_version || na());
+ setText("runtime-logical-cpus", count(system.logical_cpus));
+ setText("system-info-ram-total", size(system.memory_total_bytes));
+ setText("system-info-swap", known(system.system_swap_total_bytes) && Number(system.system_swap_total_bytes) > 0
+ ? `${size(system.system_swap_used_bytes)} / ${size(system.system_swap_total_bytes)}` : t("systemInfoNone"));
+ setText("runtime-system-uptime", known(system.system_uptime_seconds) ? uptime(Number(system.system_uptime_seconds)) : na());
+ const started = Number(system.process_start_time_seconds), sampled = Number(system.sampled_at_ms);
+ setText("system-info-process-uptime", known(system.process_start_time_seconds) && known(system.sampled_at_ms) ? uptime(sampled / 1000 - started) : na());
+ setText("system-info-version", status.version ? `v${status.version}` : "-");
+ }
+
+ function renderTiles(system, memory) {
+ setText("runtime-cpu-usage", percent(system.cpu_percent));
+ setText("system-info-cpu-note", known(system.logical_cpus) ? t("systemInfoCores").replace("{count}", count(system.logical_cpus)) : na());
+ setLine("system-info-cpu-line", series("cpu"), 100);
+ setText("system-info-process-cpu", percent(system.process_cpu_percent));
+ setLine("system-info-process-cpu-line", series("process"));
+ const load = Array.isArray(system.load_average) ? system.load_average : [];
+ setText("system-info-load", load.length ? fmt(load[0], 2) : na());
+ setText("system-info-load-note", load.length > 2 ? `5 min ${fmt(load[1], 2)} · 15 min ${fmt(load[2], 2)}` : t("systemInfoLoadUnavailable"));
+ setMeter("system-info-load-meter", load.length ? ratio(load[0], system.logical_cpus) : 0);
+ setText("runtime-system-memory", size(system.memory_used_bytes));
+ const rss = memory.process_rss_bytes ?? system.process_rss_bytes;
+ setText("system-info-memory-note", `${t("systemInfoOf")} ${size(system.memory_total_bytes)} · RustProxy ${ratio(rss, system.memory_used_bytes).toFixed(0)}%`);
+ setMeter("system-info-memory-meter", ratio(system.memory_used_bytes, system.memory_total_bytes));
+ setText("system-info-fds", count(system.open_fds));
+ setText("system-info-fds-note", t("systemInfoFdsNote").replace("{limit}", count(system.max_fds)).replace("{count}", count(system.process_threads)));
+ setMeter("system-info-fds-meter", ratio(system.open_fds, system.max_fds));
+ }
+
+ function renderProcess(system, memory) {
+ const rss = Number(memory.process_rss_bytes ?? system.process_rss_bytes) || 0;
+ setText("system-info-rss", size(memory.process_rss_bytes ?? system.process_rss_bytes));
+ const split = $("system-info-rss-split");
+ if (split) {
+ const parts = { h: memory.cache_hot_bytes, t: memory.cache_transient_bytes, a: system.process_rss_anon_bytes, f: system.process_rss_file_bytes };
+ for (const [name, value] of Object.entries(parts)) { const node = split.querySelector(`.${name}`); if (node) node.style.width = `${ratio(value, rss)}%`; }
+ }
+ setText("system-info-legend-hot", size(memory.cache_hot_bytes));
+ setText("system-info-legend-transient", size(memory.cache_transient_bytes));
+ setText("system-info-legend-anon", size(system.process_rss_anon_bytes));
+ setText("system-info-legend-file", size(system.process_rss_file_bytes));
+ setText("system-info-hot", `${size(memory.cache_hot_bytes)} / ${size(memory.cache_hot_limit_bytes)}`);
+ setMeter("system-info-hot-meter", ratio(memory.cache_hot_bytes, memory.cache_hot_limit_bytes));
+ setText("system-info-transient", `${size(memory.cache_transient_bytes)} / ${size(memory.cache_transient_limit_bytes)}`);
+ setMeter("system-info-transient-meter", ratio(memory.cache_transient_bytes, memory.cache_transient_limit_bytes));
+ setText("system-info-transforms", known(memory.transform_max_inflight) ? `${count(memory.transform_inflight)}/${count(memory.transform_max_inflight)} · ${size(memory.transform_budget_bytes)}` : na());
+ setMeter("system-info-transforms-meter", ratio(memory.transform_reserved_bytes, memory.transform_budget_bytes));
+ setText("system-info-started", known(system.process_start_time_seconds) ? formatDateTime(Number(system.process_start_time_seconds) * 1000) : na());
+ setText("system-info-virtual", size(system.process_virtual_memory_bytes));
+ setText("system-info-process-swap", size(system.process_swap_bytes));
+ setText("system-info-io", known(system.process_read_bytes) || known(system.process_write_bytes) ? `${size(system.process_read_bytes)} / ${size(system.process_write_bytes)}` : na());
+ setText("system-info-cgroup", known(system.cgroup_memory_max_bytes) ? `${size(system.cgroup_memory_current_bytes)} / ${size(system.cgroup_memory_max_bytes)}` : t("systemInfoNoLimit"));
+ }
+
+ function renderNetwork(system) {
+ setText("system-info-network-rate", known(system.network_rx_bytes_per_second) ? `↓ ${rate(system.network_rx_bytes_per_second)} · ↑ ${rate(system.network_tx_bytes_per_second)}` : na());
+ const interfaces = Array.isArray(system.network_interfaces) ? system.network_interfaces : [];
+ const active = interfaces.filter(item => Number(item.rx_bytes) > 0 || Number(item.tx_bytes) > 0);
+ const idle = interfaces.filter(item => !active.includes(item));
+ const body = $("system-info-network-rows");
+ if (body) {
+ const rows = active.map(item => {
+ const row = document.createElement("tr"), name = document.createElement("td"), code = document.createElement("code");
+ code.textContent = item.name; name.append(code);
+ const cells = [rate(item.rx_bytes_per_second), rate(item.tx_bytes_per_second), `${size(item.rx_bytes)} / ${size(item.tx_bytes)}`].map(value => { const cell = document.createElement("td"); cell.textContent = value; return cell; });
+ row.append(name, ...cells); return row;
+ });
+ if (!rows.length) { const row = document.createElement("tr"), cell = document.createElement("td"); cell.colSpan = 4; cell.className = "fine"; cell.textContent = t("systemInfoNoInterfaces"); row.append(cell); rows.push(row); }
+ body.replaceChildren(...rows);
+ }
+ const details = $("system-info-network-idle");
+ if (details) {
+ details.hidden = !idle.length;
+ setText("system-info-network-idle-summary", t("systemInfoIdleInterfaces").replace("{count}", String(idle.length)));
+ setText("system-info-network-idle-list", idle.map(item => item.name).join(", "));
+ }
+ const rx = series("rx"), tx = series("tx"), max = Math.max(...rx, ...tx, 1);
+ setLine("system-info-rx-line", rx, max);
+ setLine("system-info-tx-line", tx, max);
+ setText("system-info-network-history-value", known(system.network_rx_bytes_per_second) ? `${rate(system.network_rx_bytes_per_second)} / ${rate(system.network_tx_bytes_per_second)}` : na());
+ }
+
+ function renderToolchain(runtime) {
+ const certificate = runtime.certificate_runtime || {};
+ const mode = certificate.status === "unavailable" ? t("certificateRuntimeUnavailable")
+ : certificate.status === "ready" && certificate.mode === "managed" ? t("certificateRuntimeManaged")
+ : certificate.status === "ready" && certificate.mode === "system" ? t("certificateRuntimeSystem") : t("certificateRuntimePreparing");
+ const pill = $("runtime-acme-mode");
+ if (pill) { pill.textContent = mode; pill.classList.toggle("live", certificate.status === "ready"); }
+ for (const [tool, version] of [["python", "python_version"], ["pip", "pip_version"], ["certbot", "certbot_version"]]) {
+ const flag = certificate[tool];
+ setText(`runtime-${tool}`, flag === true ? (certificate[version] || t("runtimeAvailable")) : flag === false ? t("runtimeUnavailable") : na());
+ const chip = $(`system-info-${tool}-chip`);
+ if (chip) { chip.classList.toggle("is-ready", flag === true); chip.classList.toggle("is-missing", flag === false); }
+ }
+ setText("runtime-acme-status", certificate.message ? t(certificate.message) : na());
+ setText("runtime-acme-directory", certificate.managed_directory || na());
+ }
+
+ function renderSources(runtime) {
+ const list = $("runtime-statistics-source"); if (!list) return;
+ const sources = String(runtime.statistics_source || "").split("+").map(item => item.trim()).filter(Boolean);
+ list.replaceChildren(...(sources.length ? sources : [na()]).map(source => {
+ const chip = document.createElement("div"), label = document.createElement("dt"), value = document.createElement("dd");
+ chip.className = "pr-chip"; label.textContent = t("systemInfoSource"); value.textContent = source;
+ chip.append(label, value); return chip;
+ }));
+ }
+
+ function render(status) {
+ latest = status || {};
+ const runtime = latest.runtime || {}, system = latest.system || {}, memory = latest.memory_accounting || {};
+ record(system);
+ renderHost(latest, runtime, system);
+ renderTiles(system, memory);
+ renderProcess(system, memory);
+ renderNetwork(system);
+ renderToolchain(runtime);
+ setText("runtime-data-directory", runtime.data_directory || na());
+ setText("runtime-database-path", runtime.database_path || na());
+ renderSources(runtime);
+ }
+
+ function diagnostics() {
+ const status = latest || {}, runtime = status.runtime || {}, system = status.system || {}, memory = status.memory_accounting || {};
+ const certificate = runtime.certificate_runtime || {};
+ const load = Array.isArray(system.load_average) ? system.load_average.map(value => fmt(value, 2)).join(" / ") : na();
+ const interfaces = (system.network_interfaces || []).map(item => ` ${item.name}: rx ${size(item.rx_bytes)} (${rate(item.rx_bytes_per_second)}), tx ${size(item.tx_bytes)} (${rate(item.tx_bytes_per_second)})`);
+ return [
+ `RustProxy ${status.version || ""}`.trim(),
+ `Generated: ${new Date().toISOString()}`,
+ "",
+ "[host]",
+ `os: ${runtime.operating_system || na()}`,
+ `platform: ${runtime.platform || na()} · environment: ${system.environment || na()}`,
+ `kernel: ${runtime.kernel_version || na()} · arch: ${runtime.architecture || na()}`,
+ `cpus: ${count(system.logical_cpus)} · cpu: ${percent(system.cpu_percent)} · load: ${load}`,
+ `memory: ${size(system.memory_used_bytes)} / ${size(system.memory_total_bytes)} · swap: ${size(system.system_swap_used_bytes)} / ${size(system.system_swap_total_bytes)}`,
+ `uptime: ${known(system.system_uptime_seconds) ? uptime(Number(system.system_uptime_seconds)) : na()}`,
+ "",
+ "[process]",
+ `cpu: ${percent(system.process_cpu_percent)} · threads: ${count(system.process_threads)} · fds: ${count(system.open_fds)} / ${count(system.max_fds)}`,
+ `rss: ${size(memory.process_rss_bytes ?? system.process_rss_bytes)} (anon ${size(system.process_rss_anon_bytes)}, file ${size(system.process_rss_file_bytes)})`,
+ `hot cache: ${size(memory.cache_hot_bytes)} / ${size(memory.cache_hot_limit_bytes)} · transient: ${size(memory.cache_transient_bytes)} / ${size(memory.cache_transient_limit_bytes)}`,
+ `transforms: ${count(memory.transform_inflight)} / ${count(memory.transform_max_inflight)} · budget ${size(memory.transform_budget_bytes)}`,
+ `cgroup: ${size(system.cgroup_memory_current_bytes)} / ${size(system.cgroup_memory_max_bytes)}`,
+ `started: ${known(system.process_start_time_seconds) ? new Date(Number(system.process_start_time_seconds) * 1000).toISOString() : na()}`,
+ "",
+ "[network]",
+ ...(interfaces.length ? interfaces : [` ${na()}`]),
+ "",
+ "[certificates]",
+ `status: ${certificate.status || na()} · mode: ${certificate.mode || na()}`,
+ `python: ${certificate.python_version || na()} · pip: ${certificate.pip_version || na()} · certbot: ${certificate.certbot_version || na()}`,
+ "",
+ "[paths]",
+ `data: ${runtime.data_directory || na()}`,
+ `database: ${runtime.database_path || na()}`,
+ `acme: ${certificate.managed_directory || na()}`,
+ `sources: ${runtime.statistics_source || na()}`
+ ].join("\n");
+ }
+
+ async function copyText(value) {
+ try { await navigator.clipboard.writeText(value); return true; }
+ catch {
+ const area = document.createElement("textarea");
+ area.value = value; area.setAttribute("readonly", ""); area.className = "system-info-clipboard";
+ document.body.append(area); area.select();
+ const copied = document.execCommand("copy"); area.remove(); return copied;
+ }
+ }
+
+ $("system-info-copy")?.addEventListener("click", async () => {
+ if (await copyText(diagnostics())) toast(t("copied")); else toast(t("systemInfoCopyFailed"), true);
+ });
+ document.querySelectorAll("#settings-page-system-info [data-copy-from]").forEach(button => {
+ button.addEventListener("click", async () => {
+ const value = $(button.dataset.copyFrom)?.textContent || "";
+ if (!value || value === na()) return;
+ if (await copyText(value)) toast(t("copied")); else toast(t("systemInfoCopyFailed"), true);
+ });
+ });
+
+ window.rustProxySystemInfo = { render, diagnostics };
+})();
diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js
index 3da58d5..58da739 100644
--- a/src/admin/web/vhosts/core.js
+++ b/src/admin/web/vhosts/core.js
@@ -1,4 +1,5 @@
"use strict";
+let vhostCacheRulesEditor = null;
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null;
const chartHistory = new Map();
const backendTrafficHistory = new Map();
@@ -59,7 +60,7 @@ const defaults = () => ({
function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); }
function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); }
-function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) } }; }
+function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; }
function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; }
function collectTransform() {
const tri = name => str(name) === "" ? null : str(name) === "on";
diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js
index 5286e31..7845b84 100644
--- a/src/admin/web/vhosts/editor.js
+++ b/src/admin/web/vhosts/editor.js
@@ -528,6 +528,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
const forceTargets = field(unsafeCacheFields, "vh-cache-force-targets", "vhCacheForceTargets", (cache.unsafe_force?.targets || []).join("\n"), "textarea", { rows: 3, maxLength: 65536 });
const syncForceCache = () => { forceTargets.disabled = !forceCache.checked; }; forceCache.addEventListener("change", async () => { if (forceCache.checked && !(await appConfirm(t("vhCacheForceConfirm"), { danger: true }))) forceCache.checked = false; syncForceCache(); }); syncForceCache();
note(unsafeCacheFields, "vhCacheForceHelp");
+ const cacheRulesFields = el("div", undefined, "vh-wide vh-cache-rules"); cacheOptions.append(cacheRulesFields);
+ cacheRulesFields.append(el("h4", t("vhCacheRulesTitle")), el("p", t("vhCacheRulesHelp"), "fine"));
+ vhostCacheRulesEditor = window.rustProxyCacheRules.create({ scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true });
+ cacheRulesFields.append(vhostCacheRulesEditor.node);
if (editing) cacheOptions.append(button("vhPurgeCache", () => purge(editing)));
const syncCacheVisibility = () => {
const enabled = envelope?.config.cache?.enabled === true && cacheToggle.value !== "off";
diff --git a/src/cache/mod.rs b/src/cache/mod.rs
index 4ab8823..d946e2d 100644
--- a/src/cache/mod.rs
+++ b/src/cache/mod.rs
@@ -1,4 +1,6 @@
include!("model.rs");
+include!("rules.rs");
+include!("vcl.rs");
include!("stats.rs");
include!("lifecycle.rs");
include!("cold.rs");
diff --git a/src/cache/model/entry.rs b/src/cache/model/entry.rs
index 3c26e62..d5a3a57 100644
--- a/src/cache/model/entry.rs
+++ b/src/cache/model/entry.rs
@@ -1,5 +1,6 @@
impl Settings {
pub fn validate(&self) -> Result<()> {
+ validate_rules(&self.rules, true)?;
ensure!(
self.max_bytes >= 65_536,
"cache.max_bytes must be at least 64 KiB"
@@ -441,10 +442,18 @@ pub struct Overrides {
pub expose_resident_age: Option
,
pub expose_only_hits: Option,
pub unsafe_force: UnsafeForce,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub rules: Vec,
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub ignore_global_rules: bool,
}
impl Overrides {
pub fn resolve(&self, global: &Settings) -> Result {
+ self.resolve_for(global, "")
+ }
+ pub fn resolve_for(&self, global: &Settings, vhost_id: &str) -> Result {
self.unsafe_force.validate()?;
+ validate_rules(&self.rules, false)?;
let mut result = global.clone();
result.enabled = global.enabled && self.enabled.unwrap_or(true);
if let Some(value) = self.default_ttl_seconds {
@@ -488,6 +497,13 @@ impl Overrides {
result.expose_only_hits = value;
}
result.validate()?;
+ let compiled = CompiledRules::compile(
+ vhost_id,
+ &self.rules,
+ &global.rules,
+ self.ignore_global_rules,
+ )?;
+ result.compiled_rules = (!compiled.is_empty()).then(|| Arc::new(compiled));
Ok(result)
}
}
diff --git a/src/cache/model/settings.rs b/src/cache/model/settings.rs
index ef2eeca..acbf1a7 100644
--- a/src/cache/model/settings.rs
+++ b/src/cache/model/settings.rs
@@ -189,6 +189,10 @@ pub struct Settings {
pub expose_resident_age: bool,
pub expose_only_hits: bool,
pub via_header: Option,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub rules: Vec,
+ #[serde(skip)]
+ pub compiled_rules: Option>,
}
impl Default for Settings {
fn default() -> Self {
@@ -253,6 +257,8 @@ impl Default for Settings {
expose_resident_age: false,
expose_only_hits: false,
via_header: Some("RustProxy".into()),
+ rules: Vec::new(),
+ compiled_rules: None,
}
}
}
diff --git a/src/cache/policy/response.rs b/src/cache/policy/response.rs
index a449a5f..b1db84a 100644
--- a/src/cache/policy/response.rs
+++ b/src/cache/policy/response.rs
@@ -1,4 +1,10 @@
impl Plan {
+ pub fn ttl(&self) -> u64 {
+ self.ttl
+ }
+ pub fn grace(&self) -> u64 {
+ self.stale_while_revalidate
+ }
pub fn remaining_ttl(&self) -> u64 {
self.ttl.saturating_sub(self.initial_age.as_secs())
}
@@ -54,6 +60,26 @@ pub fn plan(
settings: &Settings,
response_delay: Duration,
) -> Option {
+ plan_with(
+ status,
+ headers,
+ settings,
+ response_delay,
+ &ResponseOverrides::NONE,
+ )
+}
+
+pub fn plan_with(
+ status: StatusCode,
+ headers: &HeaderMap,
+ settings: &Settings,
+ response_delay: Duration,
+ overrides: &ResponseOverrides,
+) -> Option {
+ if overrides.no_store {
+ return None;
+ }
+ let forced = overrides.ignore_cache_control;
if ["age", "date", "expires", "content-length"]
.iter()
.any(|name| headers.get_all(*name).iter().count() > 1)
@@ -86,22 +112,24 @@ pub fn plan(
}
let vary = vary_names(headers)?;
let control = directives(headers)?;
- if ["no-store", "private", "must-understand"]
- .iter()
- .any(|name| control.contains_key(*name))
+ if !forced
+ && ["no-store", "private", "must-understand"]
+ .iter()
+ .any(|name| control.contains_key(*name))
{
return None;
}
- if settings.varnish_compatible && surrogate_no_store(headers) {
+ if !forced && settings.varnish_compatible && surrogate_no_store(headers) {
return None;
}
let override_public_no_cache = settings.varnish_compatible
&& control.contains_key("no-cache")
&& control.contains_key("public")
&& settings.default_ttl_seconds > 0;
- let requires_revalidation = control.contains_key("no-cache") && !override_public_no_cache;
- let must_revalidate = control.contains_key("must-revalidate");
- let proxy_revalidate = control.contains_key("proxy-revalidate");
+ let requires_revalidation =
+ !forced && control.contains_key("no-cache") && !override_public_no_cache;
+ let must_revalidate = !forced && control.contains_key("must-revalidate");
+ let proxy_revalidate = !forced && control.contains_key("proxy-revalidate");
let parse_window = |name: &str| -> Option {
match control.get(name) {
None => Some(0),
@@ -122,7 +150,11 @@ pub fn plan(
Some(v) => httpdate::parse_http_date(v.to_str().ok()?).ok()?,
None => now,
};
- let declared_ttl = if override_public_no_cache {
+ let declared_ttl = if let Some(ttl) = overrides.ttl {
+ Some(ttl)
+ } else if forced {
+ (settings.default_ttl_seconds > 0).then_some(settings.default_ttl_seconds)
+ } else if override_public_no_cache {
Some(settings.default_ttl_seconds)
} else if let Some(value) = control.get("s-maxage").or_else(|| control.get("max-age")) {
Some(value.as_ref()?.parse::().ok()?)
@@ -163,6 +195,9 @@ pub fn plan(
{
stale_while_revalidate = settings.varnish_grace_seconds;
}
+ if let Some(grace) = overrides.grace {
+ stale_while_revalidate = grace;
+ }
if !requires_revalidation
&& initial_age.as_secs()
>= retention_deadline(
diff --git a/src/cache/rules.rs b/src/cache/rules.rs
new file mode 100644
index 0000000..3a0763f
--- /dev/null
+++ b/src/cache/rules.rs
@@ -0,0 +1,1192 @@
+pub const MAX_CACHE_RULES: usize = 128;
+const MAX_RULE_CONDITIONS: usize = 16;
+const MAX_RULE_ACTIONS: usize = 16;
+const MAX_RULE_VALUES: usize = 64;
+const MAX_RULE_VALUE_BYTES: usize = 512;
+const MAX_RULE_REGEX_BYTES: usize = 1 << 16;
+const MAX_RULE_TTL_SECONDS: u64 = 365 * 86_400;
+const PROTECTED_RULE_HEADERS: &[&str] = &[
+ "connection",
+ "content-length",
+ "content-encoding",
+ "content-range",
+ "date",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "set-cookie",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ "host",
+ "alt-svc",
+];
+
+fn yes_rule() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum RuleStage {
+ #[default]
+ Request,
+ Response,
+ Deliver,
+}
+
+impl RuleStage {
+ fn label(self) -> &'static str {
+ match self {
+ Self::Request => "request",
+ Self::Response => "response",
+ Self::Deliver => "deliver",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum RuleMatch {
+ #[default]
+ All,
+ Any,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConditionField {
+ Host,
+ Url,
+ Path,
+ Extension,
+ Method,
+ Query,
+ Header,
+ Cookie,
+ ClientIp,
+ Status,
+ ContentType,
+ ResponseHeader,
+}
+
+impl ConditionField {
+ fn needs_name(self) -> bool {
+ matches!(
+ self,
+ Self::Query | Self::Header | Self::Cookie | Self::ResponseHeader
+ )
+ }
+ fn response_only(self) -> bool {
+ matches!(
+ self,
+ Self::Status | Self::ContentType | Self::ResponseHeader
+ )
+ }
+ fn case_insensitive(self) -> bool {
+ matches!(
+ self,
+ Self::Host | Self::Method | Self::Extension | Self::ContentType
+ )
+ }
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConditionOperator {
+ Equals,
+ Prefix,
+ Suffix,
+ Contains,
+ Glob,
+ Regex,
+ Exists,
+ Cidr,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct RuleCondition {
+ pub field: ConditionField,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option,
+ pub operator: ConditionOperator,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub values: Vec,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub negate: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
+pub enum RuleAction {
+ Pass,
+ StripCookies {
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ keep: Vec,
+ },
+ StripQuery {
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ params: Vec,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ keep_only: bool,
+ },
+ HashHeader {
+ name: String,
+ },
+ HashCookie {
+ name: String,
+ },
+ Ttl {
+ seconds: u64,
+ },
+ Grace {
+ seconds: u64,
+ },
+ NoStore,
+ IgnoreCacheControl,
+ StripSetCookie,
+ SetHeader {
+ name: String,
+ value: String,
+ },
+ RemoveHeader {
+ name: String,
+ },
+}
+
+impl RuleAction {
+ fn stage(&self) -> RuleStage {
+ match self {
+ Self::Pass
+ | Self::StripCookies { .. }
+ | Self::StripQuery { .. }
+ | Self::HashHeader { .. }
+ | Self::HashCookie { .. } => RuleStage::Request,
+ Self::Ttl { .. }
+ | Self::Grace { .. }
+ | Self::NoStore
+ | Self::IgnoreCacheControl
+ | Self::StripSetCookie => RuleStage::Response,
+ Self::SetHeader { .. } | Self::RemoveHeader { .. } => RuleStage::Deliver,
+ }
+ }
+ fn aspect(&self) -> Option<&'static str> {
+ match self {
+ Self::Pass => Some("pass"),
+ Self::Ttl { .. } => Some("ttl"),
+ Self::Grace { .. } => Some("grace"),
+ Self::NoStore => Some("store"),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct Rule {
+ pub id: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub name: String,
+ #[serde(default = "yes_rule")]
+ pub enabled: bool,
+ #[serde(default)]
+ pub stage: RuleStage,
+ #[serde(default, rename = "match")]
+ pub match_mode: RuleMatch,
+ #[serde(default)]
+ pub conditions: Vec,
+ pub actions: Vec,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub stop: bool,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub vhosts: Vec,
+}
+
+fn rule_header_name(value: &str) -> Result {
+ let name = http::HeaderName::from_bytes(value.trim().as_bytes())
+ .map_err(|_| anyhow::anyhow!("invalid header name {value:?}"))?;
+ Ok(name)
+}
+
+fn valid_cookie_name(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 128
+ && value
+ .bytes()
+ .all(|byte| byte.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?={}".contains(&byte))
+}
+
+fn valid_query_pattern(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 128
+ && value
+ .bytes()
+ .all(|byte| byte.is_ascii_graphic() && byte != b'&' && byte != b'=' && byte != b'#')
+}
+
+pub fn validate_rules(rules: &[Rule], global: bool) -> Result<()> {
+ ensure!(
+ rules.len() <= MAX_CACHE_RULES,
+ "at most {MAX_CACHE_RULES} cache rules are supported"
+ );
+ let mut ids = HashSet::new();
+ for rule in rules {
+ compile_rule(rule, RuleOrigin::Global, "")?;
+ ensure!(
+ ids.insert(rule.id.as_str()),
+ "duplicate cache rule id {}",
+ rule.id
+ );
+ ensure!(
+ global || rule.vhosts.is_empty(),
+ "vhost cache rule {} cannot list vhosts",
+ rule.id
+ );
+ for vhost in &rule.vhosts {
+ ensure!(
+ crate::config::valid_id(vhost),
+ "cache rule {} lists an invalid vhost id",
+ rule.id
+ );
+ }
+ }
+ Ok(())
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RuleOrigin {
+ Vhost,
+ Global,
+}
+
+#[derive(Debug)]
+enum Matcher {
+ Exact(Vec),
+ Prefix(Vec),
+ Suffix(Vec),
+ Contains(Vec),
+ Glob(Vec>),
+ Regex(regex::Regex),
+ Exists,
+ Cidr(Vec),
+ Status(Vec<(u16, u16)>),
+}
+
+impl Matcher {
+ fn test(&self, value: &str) -> bool {
+ match self {
+ Self::Exact(values) => values.iter().any(|item| item == value),
+ Self::Prefix(values) => values.iter().any(|item| value.starts_with(item.as_str())),
+ Self::Suffix(values) => values.iter().any(|item| value.ends_with(item.as_str())),
+ Self::Contains(values) => values.iter().any(|item| value.contains(item.as_str())),
+ Self::Glob(patterns) => patterns.iter().any(|parts| glob_match(parts, value)),
+ Self::Regex(regex) => regex.is_match(value),
+ Self::Exists => true,
+ Self::Cidr(nets) => value
+ .parse::()
+ .is_ok_and(|ip| nets.iter().any(|net| net.contains(&ip))),
+ Self::Status(ranges) => value.parse::().is_ok_and(|code| {
+ ranges
+ .iter()
+ .any(|(low, high)| (*low..=*high).contains(&code))
+ }),
+ }
+ }
+}
+
+fn glob_parts(pattern: &str) -> Vec {
+ pattern.split('*').map(str::to_owned).collect()
+}
+
+fn glob_match(parts: &[String], value: &str) -> bool {
+ if parts.len() == 1 {
+ return parts[0] == value;
+ }
+ let (first, rest) = parts.split_first().unwrap_or((&parts[0], &[]));
+ let Some(mut remaining) = value.strip_prefix(first.as_str()) else {
+ return false;
+ };
+ let (last, middle) = rest.split_last().unwrap_or((&parts[0], &[]));
+ for part in middle {
+ match remaining.find(part.as_str()) {
+ Some(index) => remaining = &remaining[index + part.len()..],
+ None => return false,
+ }
+ }
+ remaining.len() >= last.len() && remaining.ends_with(last.as_str())
+}
+
+fn status_range(value: &str) -> Option<(u16, u16)> {
+ let value = value.trim().to_ascii_lowercase();
+ if value.len() == 3 && value.ends_with("xx") {
+ let class = value[..1]
+ .parse::()
+ .ok()
+ .filter(|class| (1..=5).contains(class))?;
+ return Some((class * 100, class * 100 + 99));
+ }
+ if let Some((low, high)) = value.split_once('-') {
+ let low = low.trim().parse::().ok()?;
+ let high = high.trim().parse::().ok()?;
+ return ((100..=599).contains(&low) && (low..=599).contains(&high)).then_some((low, high));
+ }
+ let code = value
+ .parse::()
+ .ok()
+ .filter(|code| (100..=599).contains(code))?;
+ Some((code, code))
+}
+
+#[derive(Debug)]
+struct CompiledCondition {
+ field: ConditionField,
+ name: Option,
+ header: Option,
+ matcher: Matcher,
+ negate: bool,
+}
+
+#[derive(Debug)]
+pub struct CompiledRule {
+ pub id: String,
+ pub name: String,
+ pub origin: RuleOrigin,
+ pub stage: RuleStage,
+ match_mode: RuleMatch,
+ conditions: Vec,
+ actions: Vec,
+ stop: bool,
+ counter: Arc,
+}
+
+fn compile_condition(condition: &RuleCondition, stage: RuleStage) -> Result {
+ ensure!(
+ !(condition.field.response_only() && stage == RuleStage::Request),
+ "response conditions cannot be used in request rules"
+ );
+ let name = condition
+ .name
+ .as_deref()
+ .map(str::trim)
+ .filter(|value| !value.is_empty());
+ ensure!(
+ condition.field.needs_name() == name.is_some(),
+ "condition {:?} {} a name",
+ condition.field,
+ if condition.field.needs_name() {
+ "needs"
+ } else {
+ "does not take"
+ }
+ );
+ let mut header = None;
+ if let Some(name) = name {
+ match condition.field {
+ ConditionField::Header | ConditionField::ResponseHeader => {
+ header = Some(rule_header_name(name)?)
+ }
+ ConditionField::Cookie => ensure!(valid_cookie_name(name), "invalid cookie name"),
+ ConditionField::Query => {
+ ensure!(valid_query_pattern(name), "invalid query parameter name")
+ }
+ _ => {}
+ }
+ }
+ ensure!(
+ condition.values.len() <= MAX_RULE_VALUES,
+ "too many condition values"
+ );
+ ensure!(
+ condition.values.iter().all(
+ |value| value.len() <= MAX_RULE_VALUE_BYTES && !value.chars().any(char::is_control)
+ ),
+ "condition values must be at most {MAX_RULE_VALUE_BYTES} bytes without control characters"
+ );
+ let fold = condition.field.case_insensitive();
+ let values: Vec = condition
+ .values
+ .iter()
+ .map(|value| {
+ if fold {
+ value.to_ascii_lowercase()
+ } else {
+ value.clone()
+ }
+ })
+ .collect();
+ let needs_values = condition.operator != ConditionOperator::Exists;
+ ensure!(
+ needs_values == !values.is_empty(),
+ "operator {:?} {} values",
+ condition.operator,
+ if needs_values {
+ "needs"
+ } else {
+ "does not take"
+ }
+ );
+ ensure!(
+ condition.operator != ConditionOperator::Exists || condition.field.needs_name(),
+ "exists is only available for query, header and cookie conditions"
+ );
+ ensure!(
+ (condition.operator == ConditionOperator::Cidr)
+ == (condition.field == ConditionField::ClientIp),
+ "client IP conditions use the cidr operator only"
+ );
+ let matcher = match condition.operator {
+ ConditionOperator::Equals if condition.field == ConditionField::Status => Matcher::Status(
+ values
+ .iter()
+ .map(|value| {
+ status_range(value).ok_or_else(|| anyhow::anyhow!("invalid status {value:?}"))
+ })
+ .collect::>()?,
+ ),
+ _ if condition.field == ConditionField::Status => {
+ anyhow::bail!("status conditions use the equals operator (200, 4xx, 500-599)")
+ }
+ ConditionOperator::Equals => Matcher::Exact(values),
+ ConditionOperator::Prefix => Matcher::Prefix(values),
+ ConditionOperator::Suffix => Matcher::Suffix(values),
+ ConditionOperator::Contains => Matcher::Contains(values),
+ ConditionOperator::Glob => {
+ Matcher::Glob(values.iter().map(|value| glob_parts(value)).collect())
+ }
+ ConditionOperator::Regex => {
+ let joined = if values.len() == 1 {
+ values[0].clone()
+ } else {
+ values
+ .iter()
+ .map(|value| format!("(?:{value})"))
+ .collect::>()
+ .join("|")
+ };
+ let regex = regex::RegexBuilder::new(&joined)
+ .case_insensitive(fold)
+ .size_limit(MAX_RULE_REGEX_BYTES * 16)
+ .dfa_size_limit(MAX_RULE_REGEX_BYTES * 16)
+ .build()
+ .map_err(|error| anyhow::anyhow!("invalid regular expression: {error}"))?;
+ Matcher::Regex(regex)
+ }
+ ConditionOperator::Exists => Matcher::Exists,
+ ConditionOperator::Cidr => Matcher::Cidr(
+ values
+ .iter()
+ .map(|value| {
+ let value = value.trim();
+ if value.contains('/') {
+ value
+ .parse::()
+ .map_err(|_| anyhow::anyhow!("invalid CIDR {value:?}"))
+ } else {
+ value
+ .parse::()
+ .map(ipnet::IpNet::from)
+ .map_err(|_| anyhow::anyhow!("invalid IP address {value:?}"))
+ }
+ })
+ .collect::>()?,
+ ),
+ };
+ Ok(CompiledCondition {
+ field: condition.field,
+ name: name.map(str::to_owned),
+ header,
+ matcher,
+ negate: condition.negate,
+ })
+}
+
+fn validate_action(action: &RuleAction) -> Result<()> {
+ match action {
+ RuleAction::StripCookies { keep } => {
+ ensure!(keep.len() <= MAX_RULE_VALUES, "too many cookie names");
+ ensure!(
+ keep.iter().all(|name| valid_cookie_name(name)),
+ "invalid cookie name"
+ );
+ }
+ RuleAction::StripQuery { params, keep_only } => {
+ ensure!(
+ !params.is_empty() || !keep_only,
+ "keep only needs at least one parameter"
+ );
+ ensure!(params.len() <= MAX_RULE_VALUES, "too many query parameters");
+ ensure!(
+ params.iter().all(|name| valid_query_pattern(name)),
+ "invalid query parameter pattern"
+ );
+ }
+ RuleAction::HashHeader { name } => {
+ let header = rule_header_name(name)?;
+ ensure!(
+ header != http::header::COOKIE && header != http::header::AUTHORIZATION,
+ "use hash cookie instead of hashing the whole Cookie or Authorization header"
+ );
+ }
+ RuleAction::HashCookie { name } => ensure!(valid_cookie_name(name), "invalid cookie name"),
+ RuleAction::Ttl { seconds } | RuleAction::Grace { seconds } => {
+ ensure!(
+ *seconds <= MAX_RULE_TTL_SECONDS,
+ "TTL and grace are limited to one year"
+ )
+ }
+ RuleAction::SetHeader { name, value } => {
+ let header = rule_header_name(name)?;
+ ensure!(
+ !PROTECTED_RULE_HEADERS.contains(&header.as_str()),
+ "header {header} cannot be changed by cache rules"
+ );
+ ensure!(
+ value.len() <= 1024 && HeaderValue::from_str(value).is_ok(),
+ "invalid header value"
+ );
+ }
+ RuleAction::RemoveHeader { name } => {
+ let header = rule_header_name(name)?;
+ ensure!(
+ !PROTECTED_RULE_HEADERS.contains(&header.as_str()),
+ "header {header} cannot be changed by cache rules"
+ );
+ }
+ RuleAction::Pass
+ | RuleAction::NoStore
+ | RuleAction::IgnoreCacheControl
+ | RuleAction::StripSetCookie => {}
+ }
+ Ok(())
+}
+
+static RULE_COUNTERS: std::sync::LazyLock>>> =
+ std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
+
+fn rule_counter(origin: RuleOrigin, scope: &str, id: &str) -> Arc {
+ let key = match origin {
+ RuleOrigin::Global => format!("global:{id}"),
+ RuleOrigin::Vhost => format!("vhost:{scope}:{id}"),
+ };
+ let mut counters = RULE_COUNTERS.lock().unwrap_or_else(|e| e.into_inner());
+ if counters.len() > 16_384 && !counters.contains_key(&key) {
+ counters.retain(|_, counter| Arc::strong_count(counter) > 1);
+ }
+ counters
+ .entry(key)
+ .or_insert_with(|| Arc::new(AtomicU64::new(0)))
+ .clone()
+}
+
+pub fn rule_hit_counts() -> BTreeMap {
+ RULE_COUNTERS
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .iter()
+ .map(|(key, counter)| (key.clone(), counter.load(Ordering::Relaxed)))
+ .collect()
+}
+
+fn compile_rule(rule: &Rule, origin: RuleOrigin, scope: &str) -> Result {
+ ensure!(
+ crate::config::valid_id(&rule.id),
+ "invalid cache rule id {:?}",
+ rule.id
+ );
+ ensure!(
+ rule.name.len() <= 96 && !rule.name.chars().any(char::is_control),
+ "cache rule names must be at most 96 characters"
+ );
+ ensure!(
+ rule.conditions.len() <= MAX_RULE_CONDITIONS,
+ "cache rule {} has too many conditions",
+ rule.id
+ );
+ ensure!(
+ !rule.actions.is_empty() && rule.actions.len() <= MAX_RULE_ACTIONS,
+ "cache rule {} needs 1-{MAX_RULE_ACTIONS} actions",
+ rule.id
+ );
+ for action in &rule.actions {
+ ensure!(
+ action.stage() == rule.stage,
+ "cache rule {}: action is not available in the {} stage",
+ rule.id,
+ rule.stage.label()
+ );
+ validate_action(action)
+ .map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
+ }
+ let conditions = rule
+ .conditions
+ .iter()
+ .map(|condition| compile_condition(condition, rule.stage))
+ .collect::>>()
+ .map_err(|error| anyhow::anyhow!("cache rule {}: {error}", rule.id))?;
+ Ok(CompiledRule {
+ id: rule.id.clone(),
+ name: rule.name.clone(),
+ origin,
+ stage: rule.stage,
+ match_mode: rule.match_mode,
+ conditions,
+ actions: rule.actions.clone(),
+ stop: rule.stop,
+ counter: rule_counter(origin, scope, &rule.id),
+ })
+}
+
+#[derive(Debug, Default)]
+pub struct CompiledRules {
+ request: Vec,
+ response: Vec,
+ deliver: Vec,
+}
+
+impl CompiledRules {
+ pub fn compile(
+ vhost_id: &str,
+ vhost: &[Rule],
+ global: &[Rule],
+ ignore_global: bool,
+ ) -> Result {
+ let mut compiled = Self::default();
+ let globals = global
+ .iter()
+ .filter(|rule| {
+ !ignore_global
+ && (rule.vhosts.is_empty() || rule.vhosts.iter().any(|id| id == vhost_id))
+ })
+ .map(|rule| (rule, RuleOrigin::Global));
+ for (rule, origin) in vhost
+ .iter()
+ .map(|rule| (rule, RuleOrigin::Vhost))
+ .chain(globals)
+ {
+ if !rule.enabled {
+ continue;
+ }
+ let item = compile_rule(rule, origin, vhost_id)?;
+ match item.stage {
+ RuleStage::Request => compiled.request.push(item),
+ RuleStage::Response => compiled.response.push(item),
+ RuleStage::Deliver => compiled.deliver.push(item),
+ }
+ }
+ Ok(compiled)
+ }
+ pub fn is_empty(&self) -> bool {
+ self.request.is_empty() && self.response.is_empty() && self.deliver.is_empty()
+ }
+ pub fn has_late_rules(&self) -> bool {
+ !self.response.is_empty() || !self.deliver.is_empty()
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct RuleRequest {
+ pub host: String,
+ pub path: String,
+ pub query: Option,
+ pub method: Method,
+ pub headers: HeaderMap,
+ pub client_ip: Option,
+}
+
+fn cookie_values(headers: &HeaderMap) -> impl Iterator- {
+ headers
+ .get_all(http::header::COOKIE)
+ .iter()
+ .filter_map(|value| value.to_str().ok())
+ .flat_map(|value| value.split(';'))
+ .filter_map(|pair| {
+ let pair = pair.trim();
+ if pair.is_empty() {
+ return None;
+ }
+ Some(pair.split_once('=').unwrap_or((pair, "")))
+ })
+}
+
+fn query_pairs(query: &str) -> impl Iterator
- {
+ query
+ .split('&')
+ .filter(|pair| !pair.is_empty())
+ .map(|pair| pair.split_once('=').unwrap_or((pair, "")))
+}
+
+fn query_name_matches(pattern: &str, name: &str) -> bool {
+ if pattern.contains('*') {
+ glob_match(&glob_parts(pattern), name)
+ } else {
+ pattern == name
+ }
+}
+
+impl CompiledCondition {
+ fn values<'a>(
+ &self,
+ request: &'a RuleRequest,
+ response: Option<(StatusCode, &'a HeaderMap)>,
+ ) -> Vec
> {
+ use std::borrow::Cow;
+ let name = self.name.as_deref().unwrap_or("");
+ match self.field {
+ ConditionField::Host => vec![Cow::Owned(request.host.to_ascii_lowercase())],
+ ConditionField::Url => vec![match &request.query {
+ Some(query) => Cow::Owned(format!("{}?{}", request.path, query)),
+ None => Cow::Borrowed(request.path.as_str()),
+ }],
+ ConditionField::Path => vec![Cow::Borrowed(request.path.as_str())],
+ ConditionField::Extension => {
+ let last = request.path.rsplit('/').next().unwrap_or("");
+ vec![Cow::Owned(
+ last.rsplit_once('.')
+ .map(|(_, ext)| ext.to_ascii_lowercase())
+ .unwrap_or_default(),
+ )]
+ }
+ ConditionField::Method => {
+ vec![Cow::Owned(request.method.as_str().to_ascii_lowercase())]
+ }
+ ConditionField::Query => request
+ .query
+ .as_deref()
+ .map(|query| {
+ query_pairs(query)
+ .filter(|(key, _)| query_name_matches(name, key))
+ .map(|(_, value)| Cow::Borrowed(value))
+ .collect()
+ })
+ .unwrap_or_default(),
+ ConditionField::Header => self
+ .header
+ .as_ref()
+ .map(|header| {
+ request
+ .headers
+ .get_all(header)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .map(Cow::Borrowed)
+ .collect()
+ })
+ .unwrap_or_default(),
+ ConditionField::Cookie => cookie_values(&request.headers)
+ .filter(|(key, _)| *key == name)
+ .map(|(_, value)| Cow::Borrowed(value))
+ .collect(),
+ ConditionField::ClientIp => request
+ .client_ip
+ .map(|ip| vec![Cow::Owned(ip.to_string())])
+ .unwrap_or_default(),
+ ConditionField::Status => response
+ .map(|(status, _)| vec![Cow::Owned(status.as_u16().to_string())])
+ .unwrap_or_default(),
+ ConditionField::ContentType => response
+ .and_then(|(_, headers)| headers.get(http::header::CONTENT_TYPE))
+ .and_then(|value| value.to_str().ok())
+ .map(|value| {
+ vec![Cow::Owned(
+ value
+ .split(';')
+ .next()
+ .unwrap_or("")
+ .trim()
+ .to_ascii_lowercase(),
+ )]
+ })
+ .unwrap_or_default(),
+ ConditionField::ResponseHeader => match (response, self.header.as_ref()) {
+ (Some((_, headers)), Some(header)) => headers
+ .get_all(header)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .map(Cow::Borrowed)
+ .collect(),
+ _ => Vec::new(),
+ },
+ }
+ }
+ fn matches(&self, request: &RuleRequest, response: Option<(StatusCode, &HeaderMap)>) -> bool {
+ let values = self.values(request, response);
+ let found = match self.matcher {
+ Matcher::Exists => !values.is_empty(),
+ _ => values.iter().any(|value| self.matcher.test(value)),
+ };
+ found != self.negate
+ }
+}
+
+impl CompiledRule {
+ fn matches(&self, request: &RuleRequest, response: Option<(StatusCode, &HeaderMap)>) -> bool {
+ if self.conditions.is_empty() {
+ return true;
+ }
+ match self.match_mode {
+ RuleMatch::All => self
+ .conditions
+ .iter()
+ .all(|condition| condition.matches(request, response)),
+ RuleMatch::Any => self
+ .conditions
+ .iter()
+ .any(|condition| condition.matches(request, response)),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct RuleMatchInfo {
+ pub id: String,
+ pub name: String,
+ pub origin: RuleOrigin,
+ pub stage: RuleStage,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct RuleOverride {
+ pub aspect: &'static str,
+ pub winner: String,
+ pub ignored: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct RequestRuleOutcome {
+ pub pass: Option,
+ pub strip_cookies: Option>,
+ pub query_edits: Vec<(Vec, bool)>,
+ pub hash: Vec,
+ pub matched: Vec,
+ pub overridden: Vec,
+}
+
+#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
+pub struct ResponseOverrides {
+ pub ttl: Option,
+ pub grace: Option,
+ pub no_store: bool,
+ pub ignore_cache_control: bool,
+ pub strip_set_cookie: bool,
+}
+
+impl ResponseOverrides {
+ pub const NONE: Self = Self {
+ ttl: None,
+ grace: None,
+ no_store: false,
+ ignore_cache_control: false,
+ strip_set_cookie: false,
+ };
+ pub fn is_none(&self) -> bool {
+ *self == Self::NONE
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct ResponseRuleOutcome {
+ pub overrides: ResponseOverrides,
+ pub matched: Vec,
+ pub overridden: Vec,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct DeliverRuleOutcome {
+ pub set: Vec<(String, String)>,
+ pub remove: Vec,
+ pub matched: Vec,
+}
+
+fn info(rule: &CompiledRule) -> RuleMatchInfo {
+ RuleMatchInfo {
+ id: rule.id.clone(),
+ name: rule.name.clone(),
+ origin: rule.origin,
+ stage: rule.stage,
+ }
+}
+
+fn claim(
+ owners: &mut HashMap<&'static str, String>,
+ overridden: &mut Vec,
+ aspect: &'static str,
+ rule: &CompiledRule,
+) -> bool {
+ let label = format!(
+ "{}:{}",
+ match rule.origin {
+ RuleOrigin::Vhost => "vhost",
+ RuleOrigin::Global => "global",
+ },
+ rule.id
+ );
+ match owners.get(aspect) {
+ Some(winner) => {
+ if winner != &label {
+ overridden.push(RuleOverride {
+ aspect,
+ winner: winner.clone(),
+ ignored: label,
+ });
+ }
+ false
+ }
+ None => {
+ owners.insert(aspect, label);
+ true
+ }
+ }
+}
+
+impl CompiledRules {
+ pub fn evaluate_request(&self, request: &RuleRequest, count: bool) -> RequestRuleOutcome {
+ let mut outcome = RequestRuleOutcome::default();
+ let mut owners = HashMap::new();
+ for rule in &self.request {
+ if !rule.matches(request, None) {
+ continue;
+ }
+ if count {
+ rule.counter.fetch_add(1, Ordering::Relaxed);
+ }
+ outcome.matched.push(info(rule));
+ for action in &rule.actions {
+ if let Some(aspect) = action.aspect() {
+ if !claim(&mut owners, &mut outcome.overridden, aspect, rule) {
+ continue;
+ }
+ }
+ match action {
+ RuleAction::Pass => outcome.pass = Some(rule.id.clone()),
+ RuleAction::StripCookies { keep } => match &mut outcome.strip_cookies {
+ Some(existing) => existing.retain(|name| keep.contains(name)),
+ None => outcome.strip_cookies = Some(keep.clone()),
+ },
+ RuleAction::StripQuery { params, keep_only } => {
+ outcome.query_edits.push((params.clone(), *keep_only))
+ }
+ RuleAction::HashHeader { name } => {
+ let value = rule_header_name(name)
+ .ok()
+ .map(|header| {
+ request
+ .headers
+ .get_all(&header)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .collect::>()
+ .join(",")
+ })
+ .unwrap_or_default();
+ outcome
+ .hash
+ .push(format!("h:{}={value}", name.to_ascii_lowercase()));
+ }
+ RuleAction::HashCookie { name } => {
+ let value = cookie_values(&request.headers)
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value)
+ .unwrap_or("");
+ outcome.hash.push(format!("c:{name}={value}"));
+ }
+ _ => {}
+ }
+ }
+ if rule.stop {
+ break;
+ }
+ }
+ outcome
+ }
+
+ pub fn evaluate_response(
+ &self,
+ request: &RuleRequest,
+ status: StatusCode,
+ headers: &HeaderMap,
+ count: bool,
+ ) -> ResponseRuleOutcome {
+ let mut outcome = ResponseRuleOutcome::default();
+ let mut owners = HashMap::new();
+ for rule in &self.response {
+ if !rule.matches(request, Some((status, headers))) {
+ continue;
+ }
+ if count {
+ rule.counter.fetch_add(1, Ordering::Relaxed);
+ }
+ outcome.matched.push(info(rule));
+ for action in &rule.actions {
+ if let Some(aspect) = action.aspect() {
+ if !claim(&mut owners, &mut outcome.overridden, aspect, rule) {
+ continue;
+ }
+ }
+ match action {
+ RuleAction::Ttl { seconds } => outcome.overrides.ttl = Some(*seconds),
+ RuleAction::Grace { seconds } => outcome.overrides.grace = Some(*seconds),
+ RuleAction::NoStore => outcome.overrides.no_store = true,
+ RuleAction::IgnoreCacheControl => outcome.overrides.ignore_cache_control = true,
+ RuleAction::StripSetCookie => outcome.overrides.strip_set_cookie = true,
+ _ => {}
+ }
+ }
+ if rule.stop {
+ break;
+ }
+ }
+ outcome
+ }
+
+ pub fn evaluate_deliver(
+ &self,
+ request: &RuleRequest,
+ status: StatusCode,
+ headers: &HeaderMap,
+ count: bool,
+ ) -> DeliverRuleOutcome {
+ let mut outcome = DeliverRuleOutcome::default();
+ for rule in &self.deliver {
+ if !rule.matches(request, Some((status, headers))) {
+ continue;
+ }
+ if count {
+ rule.counter.fetch_add(1, Ordering::Relaxed);
+ }
+ outcome.matched.push(info(rule));
+ for action in &rule.actions {
+ match action {
+ RuleAction::SetHeader { name, value } => {
+ outcome.set.push((name.to_ascii_lowercase(), value.clone()))
+ }
+ RuleAction::RemoveHeader { name } => {
+ outcome.remove.push(name.to_ascii_lowercase())
+ }
+ _ => {}
+ }
+ }
+ if rule.stop {
+ break;
+ }
+ }
+ outcome
+ }
+}
+
+impl RequestRuleOutcome {
+ pub fn rewrite_cookies(&self, headers: &mut HeaderMap) {
+ let Some(keep) = &self.strip_cookies else {
+ return;
+ };
+ let kept: Vec = cookie_values(headers)
+ .filter(|(name, _)| keep.iter().any(|item| item == name))
+ .map(|(name, value)| {
+ if value.is_empty() {
+ name.to_owned()
+ } else {
+ format!("{name}={value}")
+ }
+ })
+ .collect();
+ headers.remove(http::header::COOKIE);
+ if !kept.is_empty() {
+ if let Ok(value) = HeaderValue::from_str(&kept.join("; ")) {
+ headers.insert(http::header::COOKIE, value);
+ }
+ }
+ }
+ pub fn rewrite_query(&self, query: Option<&str>) -> Option> {
+ let query = query?;
+ if self.query_edits.is_empty() {
+ return None;
+ }
+ let kept: Vec<&str> = query
+ .split('&')
+ .filter(|pair| !pair.is_empty())
+ .filter(|pair| {
+ let name = pair.split_once('=').map(|(name, _)| name).unwrap_or(pair);
+ self.query_edits.iter().all(|(params, keep_only)| {
+ if params.is_empty() {
+ return false;
+ }
+ let listed = params
+ .iter()
+ .any(|pattern| query_name_matches(pattern, name));
+ if *keep_only {
+ listed
+ } else {
+ !listed
+ }
+ })
+ })
+ .collect();
+ let rewritten = (!kept.is_empty()).then(|| kept.join("&"));
+ (rewritten.as_deref() != Some(query)).then_some(rewritten)
+ }
+ pub fn hash_variant(&self) -> String {
+ self.hash.join("\n")
+ }
+}
+
+impl DeliverRuleOutcome {
+ pub fn apply(&self, headers: &mut HeaderMap) {
+ for name in &self.remove {
+ if let Ok(header) = http::HeaderName::from_bytes(name.as_bytes()) {
+ headers.remove(header);
+ }
+ }
+ for (name, value) in &self.set {
+ if let (Ok(header), Ok(value)) = (
+ http::HeaderName::from_bytes(name.as_bytes()),
+ HeaderValue::from_str(value),
+ ) {
+ headers.insert(header, value);
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct RuleContext {
+ pub rules: Arc,
+ pub request: RuleRequest,
+}
+
+impl RuleContext {
+ pub fn response_overrides(&self, status: StatusCode, headers: &HeaderMap) -> ResponseOverrides {
+ if self.rules.response.is_empty() {
+ return ResponseOverrides::NONE;
+ }
+ self.rules
+ .evaluate_response(&self.request, status, headers, true)
+ .overrides
+ }
+ pub fn deliver(&self, status: StatusCode, headers: &mut HeaderMap) {
+ if self.rules.deliver.is_empty() {
+ return;
+ }
+ let outcome = self
+ .rules
+ .evaluate_deliver(&self.request, status, headers, true);
+ outcome.apply(headers);
+ }
+}
+
+#[derive(Clone, Default)]
+pub struct RuleSink(Arc>>>);
+
+impl RuleSink {
+ pub fn set(&self, context: Arc) {
+ *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(context);
+ }
+ pub fn apply(&self, response: &mut Response) {
+ let context = self.0.lock().unwrap_or_else(|e| e.into_inner()).take();
+ if let Some(context) = context {
+ let status = response.status();
+ context.deliver(status, response.headers_mut());
+ }
+ }
+}
diff --git a/src/cache/rules_tests.rs b/src/cache/rules_tests.rs
new file mode 100644
index 0000000..1cc79eb
--- /dev/null
+++ b/src/cache/rules_tests.rs
@@ -0,0 +1,324 @@
+mod cache_rules_tests {
+ use super::*;
+
+ fn rule(json: serde_json::Value) -> Rule {
+ serde_json::from_value(json).unwrap()
+ }
+
+ fn request(path: &str, query: Option<&str>, headers: &[(&str, &str)]) -> RuleRequest {
+ let mut map = HeaderMap::new();
+ for (name, value) in headers {
+ map.append(
+ http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
+ HeaderValue::from_str(value).unwrap(),
+ );
+ }
+ RuleRequest {
+ host: "shop.example.test".into(),
+ path: path.into(),
+ query: query.map(str::to_owned),
+ method: Method::GET,
+ headers: map,
+ client_ip: Some("10.1.2.3".parse().unwrap()),
+ }
+ }
+
+ #[test]
+ fn request_rules_pass_strip_cookies_query_and_hash() {
+ let global = vec![
+ rule(
+ serde_json::json!({"id": "admin", "conditions": [{"field": "path", "operator": "prefix", "values": ["/wp-admin"]}], "actions": [{"type": "pass"}]}),
+ ),
+ rule(
+ serde_json::json!({"id": "utm", "actions": [{"type": "strip_query", "params": ["utm_*", "fbclid"]}]}),
+ ),
+ rule(
+ serde_json::json!({"id": "cookies", "conditions": [{"field": "extension", "operator": "equals", "values": ["css", "js"]}], "actions": [{"type": "strip_cookies", "keep": ["lang"]}, {"type": "hash_cookie", "name": "lang"}]}),
+ ),
+ ];
+ validate_rules(&global, true).unwrap();
+ let rules = CompiledRules::compile("shop", &[], &global, false).unwrap();
+ let admin = rules.evaluate_request(&request("/wp-admin/index.php", None, &[]), false);
+ assert_eq!(admin.pass.as_deref(), Some("admin"));
+ let asset = request(
+ "/app.CSS",
+ Some("v=1&utm_source=x&fbclid=y"),
+ &[("cookie", "sid=1; lang=pl")],
+ );
+ let outcome = rules.evaluate_request(&asset, false);
+ assert!(outcome.pass.is_none());
+ assert_eq!(
+ outcome.rewrite_query(asset.query.as_deref()),
+ Some(Some("v=1".into()))
+ );
+ let mut headers = asset.headers.clone();
+ outcome.rewrite_cookies(&mut headers);
+ assert_eq!(headers.get("cookie").unwrap(), "lang=pl");
+ assert_eq!(outcome.hash, vec!["c:lang=pl".to_owned()]);
+ let only_utm = request("/page", Some("utm_medium=a"), &[]);
+ assert_eq!(
+ rules
+ .evaluate_request(&only_utm, false)
+ .rewrite_query(only_utm.query.as_deref()),
+ Some(None)
+ );
+ }
+
+ #[test]
+ fn vhost_rules_win_over_global_and_report_the_override() {
+ let global = vec![rule(
+ serde_json::json!({"id": "ttl", "stage": "response", "actions": [{"type": "ttl", "seconds": 60}]}),
+ )];
+ let vhost = vec![rule(
+ serde_json::json!({"id": "ttl", "stage": "response", "conditions": [{"field": "status", "operator": "equals", "values": ["2xx"]}], "actions": [{"type": "ttl", "seconds": 3600}, {"type": "grace", "seconds": 30}]}),
+ )];
+ let rules = CompiledRules::compile("shop", &vhost, &global, false).unwrap();
+ let outcome = rules.evaluate_response(
+ &request("/", None, &[]),
+ StatusCode::OK,
+ &HeaderMap::new(),
+ false,
+ );
+ assert_eq!(outcome.overrides.ttl, Some(3600));
+ assert_eq!(outcome.overrides.grace, Some(30));
+ assert_eq!(outcome.overridden.len(), 1);
+ assert_eq!(outcome.overridden[0].winner, "vhost:ttl");
+ assert_eq!(outcome.overridden[0].ignored, "global:ttl");
+ let ignored = CompiledRules::compile("shop", &[], &global, true).unwrap();
+ assert!(ignored.is_empty());
+ let scoped = vec![rule(
+ serde_json::json!({"id": "other", "vhosts": ["blog"], "actions": [{"type": "pass"}]}),
+ )];
+ assert!(CompiledRules::compile("shop", &[], &scoped, false)
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn invalid_rules_are_rejected() {
+ for json in [
+ serde_json::json!({"id": "x", "actions": [{"type": "ttl", "seconds": 5}]}),
+ serde_json::json!({"id": "x", "conditions": [{"field": "status", "operator": "equals", "values": ["200"]}], "actions": [{"type": "pass"}]}),
+ serde_json::json!({"id": "x", "stage": "deliver", "actions": [{"type": "set_header", "name": "set-cookie", "value": "a"}]}),
+ serde_json::json!({"id": "x", "conditions": [{"field": "path", "operator": "regex", "values": ["("]}], "actions": [{"type": "pass"}]}),
+ serde_json::json!({"id": "x", "conditions": [{"field": "header", "operator": "exists"}], "actions": [{"type": "pass"}]}),
+ serde_json::json!({"id": "bad id", "actions": [{"type": "pass"}]}),
+ serde_json::json!({"id": "x", "actions": []}),
+ ] {
+ assert!(
+ validate_rules(&[rule(json.clone())], true).is_err(),
+ "{json}"
+ );
+ }
+ let duplicate = vec![
+ rule(serde_json::json!({"id": "a", "actions": [{"type": "pass"}]})),
+ rule(serde_json::json!({"id": "a", "actions": [{"type": "pass"}]})),
+ ];
+ assert!(validate_rules(&duplicate, true).is_err());
+ }
+
+ #[test]
+ fn response_overrides_force_ttl_and_ignore_cache_control() {
+ let settings = Settings::default();
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ http::header::CACHE_CONTROL,
+ HeaderValue::from_static("private, no-cache"),
+ );
+ assert!(plan(StatusCode::OK, &headers, &settings, Duration::ZERO).is_none());
+ let forced = ResponseOverrides {
+ ttl: Some(120),
+ grace: Some(10),
+ ignore_cache_control: true,
+ ..ResponseOverrides::NONE
+ };
+ let planned =
+ plan_with(StatusCode::OK, &headers, &settings, Duration::ZERO, &forced).unwrap();
+ assert_eq!(planned.ttl(), 120);
+ assert_eq!(planned.grace(), 10);
+ let no_store = ResponseOverrides {
+ no_store: true,
+ ..ResponseOverrides::NONE
+ };
+ let mut public = HeaderMap::new();
+ public.insert(
+ http::header::CACHE_CONTROL,
+ HeaderValue::from_static("public, max-age=60"),
+ );
+ assert!(plan_with(
+ StatusCode::OK,
+ &public,
+ &settings,
+ Duration::ZERO,
+ &no_store
+ )
+ .is_none());
+ let ttl_only = ResponseOverrides {
+ ttl: Some(600),
+ ..ResponseOverrides::NONE
+ };
+ assert_eq!(
+ plan_with(
+ StatusCode::OK,
+ &public,
+ &settings,
+ Duration::ZERO,
+ &ttl_only
+ )
+ .unwrap()
+ .ttl(),
+ 600
+ );
+ assert!(plan_with(
+ StatusCode::OK,
+ &headers,
+ &settings,
+ Duration::ZERO,
+ &ttl_only
+ )
+ .is_none());
+ }
+
+ #[test]
+ fn deliver_rules_set_and_remove_headers() {
+ let rules = vec![rule(
+ serde_json::json!({"id": "debug", "stage": "deliver", "conditions": [{"field": "response_header", "name": "x-cache", "operator": "equals", "values": ["HIT"]}], "actions": [{"type": "set_header", "name": "X-Served", "value": "cache"}, {"type": "remove_header", "name": "server"}]}),
+ )];
+ let compiled = CompiledRules::compile("", &[], &rules, false).unwrap();
+ let mut headers = HeaderMap::new();
+ headers.insert("x-cache", HeaderValue::from_static("HIT"));
+ headers.insert("server", HeaderValue::from_static("origin"));
+ let outcome =
+ compiled.evaluate_deliver(&request("/", None, &[]), StatusCode::OK, &headers, false);
+ outcome.apply(&mut headers);
+ assert_eq!(headers.get("x-served").unwrap(), "cache");
+ assert!(headers.get("server").is_none());
+ }
+
+ #[test]
+ fn rule_variant_changes_the_cache_key_only_when_present() {
+ let cache = Cache::new(1);
+ let headers = HeaderMap::new();
+ let plain = cache
+ .ticket_scoped_for_config_variant(
+ cache_control_revision(&cache),
+ 1,
+ "",
+ "https",
+ "a.test",
+ "r",
+ "/x",
+ &headers,
+ "",
+ )
+ .unwrap();
+ let again = cache
+ .ticket_scoped_for_config(
+ cache_control_revision(&cache),
+ 1,
+ "",
+ "https",
+ "a.test",
+ "r",
+ "/x",
+ &headers,
+ )
+ .unwrap();
+ let variant = cache
+ .ticket_scoped_for_config_variant(
+ cache_control_revision(&cache),
+ 1,
+ "",
+ "https",
+ "a.test",
+ "r",
+ "/x",
+ &headers,
+ "c:lang=pl",
+ )
+ .unwrap();
+ assert_eq!(plain.key, again.key);
+ assert_ne!(plain.key, variant.key);
+ }
+
+ fn cache_control_revision(cache: &Cache) -> u64 {
+ cache.store.lock().unwrap().control_revision
+ }
+
+ #[test]
+ fn vcl_subset_is_imported_with_warnings() {
+ let source = r#"
+vcl 4.1;
+backend default { .host = "127.0.0.1"; }
+sub vcl_recv {
+ if (req.url ~ "^/wp-(admin|login)" || req.http.Cookie ~ "wordpress_logged_in") {
+ return (pass);
+ }
+ if (req.method != "GET" && req.method != "HEAD") { return (pass); }
+ set req.url = regsuball(req.url, "(\?|&)(utm_[a-z]+|gclid|fbclid)=[^&]+", "\1");
+ if (req.url ~ "\.(css|js|png)$") {
+ unset req.http.Cookie;
+ }
+ if (client.ip ~ purgers) { return (purge); }
+}
+sub vcl_hash { hash_data(req.http.X-Lang); }
+sub vcl_backend_response {
+ if (beresp.status >= 500) {
+ set beresp.ttl = 0s;
+ set beresp.uncacheable = true;
+ } else {
+ set beresp.ttl = 1h;
+ set beresp.grace = 6h;
+ }
+ unset beresp.http.Set-Cookie;
+}
+sub vcl_deliver {
+ set resp.http.X-Cache-Engine = "RustProxy";
+ unset resp.http.X-Powered-By;
+}
+"#;
+ let imported = import_vcl(source).unwrap();
+ validate_rules(&imported.rules, true).unwrap();
+ let actions: Vec<_> = imported
+ .rules
+ .iter()
+ .flat_map(|rule| rule.actions.clone())
+ .collect();
+ assert!(actions.contains(&RuleAction::Pass));
+ assert!(actions.contains(&RuleAction::StripQuery {
+ params: vec!["utm_*".into(), "gclid".into(), "fbclid".into()],
+ keep_only: false
+ }));
+ assert!(actions.contains(&RuleAction::StripCookies { keep: vec![] }));
+ assert!(actions.contains(&RuleAction::HashHeader {
+ name: "X-Lang".into()
+ }));
+ assert!(actions.contains(&RuleAction::Ttl { seconds: 3600 }));
+ assert!(actions.contains(&RuleAction::Grace { seconds: 21600 }));
+ assert!(actions.contains(&RuleAction::NoStore));
+ assert!(actions.contains(&RuleAction::StripSetCookie));
+ assert!(actions.contains(&RuleAction::SetHeader {
+ name: "X-Cache-Engine".into(),
+ value: "RustProxy".into()
+ }));
+ assert!(actions.contains(&RuleAction::RemoveHeader {
+ name: "X-Powered-By".into()
+ }));
+ let else_rule = imported
+ .rules
+ .iter()
+ .find(|rule| rule.actions.contains(&RuleAction::Ttl { seconds: 3600 }))
+ .unwrap();
+ assert!(else_rule.conditions[0].negate);
+ assert!(imported
+ .warnings
+ .iter()
+ .any(|warning| warning.contains("client.ip")));
+ assert!(imported
+ .warnings
+ .iter()
+ .any(|warning| warning.contains("backend")));
+ assert!(import_vcl("sub vcl_recv { if (").is_err());
+ assert!(import_vcl("vcl 4.1;").is_err());
+ }
+}
diff --git a/src/cache/tests.rs b/src/cache/tests.rs
index 8fa3a58..570dbbd 100644
--- a/src/cache/tests.rs
+++ b/src/cache/tests.rs
@@ -21,3 +21,6 @@ include!("lookup/hot_hit_034_tests.rs");
#[cfg(test)]
include!("varnish_compatible_tests.rs");
+
+#[cfg(test)]
+include!("rules_tests.rs");
diff --git a/src/cache/tickets.rs b/src/cache/tickets.rs
index 3d5a3fc..4ca0aa4 100644
--- a/src/cache/tickets.rs
+++ b/src/cache/tickets.rs
@@ -49,8 +49,51 @@ impl Cache {
)
}
+ #[allow(clippy::too_many_arguments)]
+ pub fn ticket_scoped_for_config_variant(
+ &self,
+ control_revision: u64,
+ revision: u64,
+ scope: &str,
+ scheme: &str,
+ authority: &str,
+ route: &str,
+ target: &str,
+ headers: &HeaderMap,
+ variant: &str,
+ ) -> Option {
+ self.ticket_variant_impl(
+ Some(control_revision),
+ revision,
+ scope,
+ scheme,
+ authority,
+ route,
+ target,
+ headers,
+ variant,
+ )
+ }
+
#[allow(clippy::too_many_arguments)]
fn ticket_scoped_impl(
+ &self,
+ expected_control_revision: Option,
+ revision: u64,
+ scope: &str,
+ scheme: &str,
+ authority: &str,
+ route: &str,
+ target: &str,
+ headers: &HeaderMap,
+ ) -> Option {
+ self.ticket_variant_impl(
+ expected_control_revision, revision, scope, scheme, authority, route, target, headers, "",
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn ticket_variant_impl(
&self,
expected_control_revision: Option,
revision: u64,
@@ -60,8 +103,9 @@ impl Cache {
_route: &str,
target: &str,
headers: &HeaderMap,
+ variant: &str,
) -> Option {
- if target.len() > 8192 || scope.len() > 64 {
+ if target.len() > 8192 || scope.len() > 64 || variant.len() > 8192 {
return None;
}
let domain = crate::config::request_host(authority)
@@ -83,6 +127,10 @@ impl Cache {
] {
field(value);
}
+ if !variant.is_empty() {
+ field(b"rule-variant");
+ field(variant.as_bytes());
+ }
let key: Key = digest.finalize().into();
let store = self.store.lock().unwrap_or_else(|e| e.into_inner());
(store.revision == revision
diff --git a/src/cache/vcl.rs b/src/cache/vcl.rs
new file mode 100644
index 0000000..de4259c
--- /dev/null
+++ b/src/cache/vcl.rs
@@ -0,0 +1,825 @@
+const MAX_VCL_BYTES: usize = 256 * 1024;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum VclToken {
+ Ident(String),
+ Str(String),
+ Num(String),
+ Sym(&'static str),
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct VclImport {
+ pub rules: Vec,
+ pub warnings: Vec,
+}
+
+fn vcl_tokens(source: &str) -> Result> {
+ let bytes = source.as_bytes();
+ let mut tokens = Vec::new();
+ let mut index = 0;
+ let mut line = 1;
+ while index < bytes.len() {
+ let byte = bytes[index];
+ if byte == b'\n' {
+ line += 1;
+ index += 1;
+ continue;
+ }
+ if byte.is_ascii_whitespace() {
+ index += 1;
+ continue;
+ }
+ if byte == b'#' || (byte == b'/' && bytes.get(index + 1) == Some(&b'/')) {
+ while index < bytes.len() && bytes[index] != b'\n' {
+ index += 1;
+ }
+ continue;
+ }
+ if byte == b'/' && bytes.get(index + 1) == Some(&b'*') {
+ index += 2;
+ while index + 1 < bytes.len() && !(bytes[index] == b'*' && bytes[index + 1] == b'/') {
+ if bytes[index] == b'\n' {
+ line += 1;
+ }
+ index += 1;
+ }
+ index += 2;
+ continue;
+ }
+ if byte == b'{' && bytes.get(index + 1) == Some(&b'"') {
+ let start = index + 2;
+ let end = source[start..]
+ .find("\"}")
+ .map(|offset| start + offset)
+ .ok_or_else(|| anyhow::anyhow!("line {line}: unterminated long string"))?;
+ line += source[start..end].matches('\n').count();
+ tokens.push((VclToken::Str(source[start..end].to_owned()), line));
+ index = end + 2;
+ continue;
+ }
+ if byte == b'"' {
+ let start = index + 1;
+ let end = source[start..]
+ .find('"')
+ .map(|offset| start + offset)
+ .ok_or_else(|| anyhow::anyhow!("line {line}: unterminated string"))?;
+ tokens.push((VclToken::Str(source[start..end].to_owned()), line));
+ index = end + 1;
+ continue;
+ }
+ if byte.is_ascii_alphabetic() || byte == b'_' {
+ let start = index;
+ while index < bytes.len()
+ && (bytes[index].is_ascii_alphanumeric()
+ || matches!(bytes[index], b'_' | b'.' | b'-' | b':'))
+ {
+ index += 1;
+ }
+ tokens.push((VclToken::Ident(source[start..index].to_owned()), line));
+ continue;
+ }
+ if byte.is_ascii_digit() {
+ let start = index;
+ while index < bytes.len()
+ && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'.')
+ {
+ index += 1;
+ }
+ tokens.push((VclToken::Num(source[start..index].to_owned()), line));
+ continue;
+ }
+ let two = source.get(index..index + 2).unwrap_or("");
+ let symbol = match two {
+ "==" => Some("=="),
+ "!=" => Some("!="),
+ "!~" => Some("!~"),
+ "&&" => Some("&&"),
+ "||" => Some("||"),
+ ">=" => Some(">="),
+ "<=" => Some("<="),
+ _ => None,
+ };
+ if let Some(symbol) = symbol {
+ tokens.push((VclToken::Sym(symbol), line));
+ index += 2;
+ continue;
+ }
+ let symbol = match byte {
+ b'{' => "{",
+ b'}' => "}",
+ b'(' => "(",
+ b')' => ")",
+ b';' => ";",
+ b'=' => "=",
+ b'~' => "~",
+ b'!' => "!",
+ b',' => ",",
+ b'>' => ">",
+ b'<' => "<",
+ b'+' => "+",
+ b'.' => ".",
+ b'-' => "-",
+ b'*' => "*",
+ b'/' => "/",
+ b'%' => "%",
+ _ => anyhow::bail!("line {line}: unexpected character {:?}", byte as char),
+ };
+ tokens.push((VclToken::Sym(symbol), line));
+ index += 1;
+ }
+ Ok(tokens)
+}
+
+#[derive(Debug, Clone)]
+enum VclStatement {
+ If(Vec<(Option, Vec)>, usize),
+ Simple(Vec, usize),
+}
+
+#[derive(Debug, Clone)]
+enum VclExpr {
+ And(Vec),
+ Or(Vec),
+ Not(Box),
+ Atom(Vec),
+}
+
+struct VclParser {
+ tokens: Vec<(VclToken, usize)>,
+ position: usize,
+}
+
+impl VclParser {
+ fn peek(&self) -> Option<&VclToken> {
+ self.tokens.get(self.position).map(|(token, _)| token)
+ }
+ fn line(&self) -> usize {
+ self.tokens
+ .get(self.position)
+ .or(self.tokens.last())
+ .map(|(_, line)| *line)
+ .unwrap_or(0)
+ }
+ fn next(&mut self) -> Option {
+ let token = self
+ .tokens
+ .get(self.position)
+ .map(|(token, _)| token.clone());
+ self.position += 1;
+ token
+ }
+ fn is_sym(&self, symbol: &str) -> bool {
+ matches!(self.peek(), Some(VclToken::Sym(value)) if *value == symbol)
+ }
+ fn is_ident(&self, name: &str) -> bool {
+ matches!(self.peek(), Some(VclToken::Ident(value)) if value == name)
+ }
+ fn expect(&mut self, symbol: &str) -> Result<()> {
+ let line = self.line();
+ match self.next() {
+ Some(VclToken::Sym(value)) if value == symbol => Ok(()),
+ other => anyhow::bail!("line {line}: expected {symbol:?}, found {other:?}"),
+ }
+ }
+ fn block(&mut self) -> Result> {
+ self.expect("{")?;
+ let mut statements = Vec::new();
+ while !self.is_sym("}") {
+ ensure!(
+ self.peek().is_some(),
+ "unexpected end of VCL inside a block"
+ );
+ statements.push(self.statement()?);
+ }
+ self.expect("}")?;
+ Ok(statements)
+ }
+ fn statement(&mut self) -> Result {
+ let line = self.line();
+ if self.is_ident("if") {
+ self.next();
+ let mut branches = vec![(Some(self.condition()?), self.block()?)];
+ loop {
+ if self.is_ident("elsif") || self.is_ident("elseif") {
+ self.next();
+ branches.push((Some(self.condition()?), self.block()?));
+ } else if self.is_ident("else") {
+ self.next();
+ if self.is_ident("if") {
+ self.next();
+ branches.push((Some(self.condition()?), self.block()?));
+ } else {
+ branches.push((None, self.block()?));
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ return Ok(VclStatement::If(branches, line));
+ }
+ let mut tokens = Vec::new();
+ let mut depth = 0usize;
+ loop {
+ match self.next() {
+ None => anyhow::bail!("line {line}: missing ';'"),
+ Some(VclToken::Sym(";")) if depth == 0 => break,
+ Some(token) => {
+ if token == VclToken::Sym("(") {
+ depth += 1;
+ } else if token == VclToken::Sym(")") {
+ depth = depth.saturating_sub(1);
+ }
+ tokens.push(token);
+ }
+ }
+ }
+ Ok(VclStatement::Simple(tokens, line))
+ }
+ fn condition(&mut self) -> Result {
+ self.expect("(")?;
+ let expr = self.or_expr()?;
+ self.expect(")")?;
+ Ok(expr)
+ }
+ fn or_expr(&mut self) -> Result {
+ let mut items = vec![self.and_expr()?];
+ while self.is_sym("||") {
+ self.next();
+ items.push(self.and_expr()?);
+ }
+ Ok(if items.len() == 1 {
+ items.remove(0)
+ } else {
+ VclExpr::Or(items)
+ })
+ }
+ fn and_expr(&mut self) -> Result {
+ let mut items = vec![self.unary()?];
+ while self.is_sym("&&") {
+ self.next();
+ items.push(self.unary()?);
+ }
+ Ok(if items.len() == 1 {
+ items.remove(0)
+ } else {
+ VclExpr::And(items)
+ })
+ }
+ fn unary(&mut self) -> Result {
+ if self.is_sym("!") {
+ self.next();
+ return Ok(VclExpr::Not(Box::new(self.unary()?)));
+ }
+ if self.is_sym("(") {
+ self.next();
+ let expr = self.or_expr()?;
+ self.expect(")")?;
+ return Ok(expr);
+ }
+ let mut atom = Vec::new();
+ while let Some(token) = self.peek() {
+ if matches!(
+ token,
+ VclToken::Sym("&&") | VclToken::Sym("||") | VclToken::Sym(")")
+ ) {
+ break;
+ }
+ atom.push(self.next().unwrap_or(VclToken::Sym(";")));
+ }
+ ensure!(!atom.is_empty(), "line {}: empty condition", self.line());
+ Ok(VclExpr::Atom(atom))
+ }
+}
+
+fn vcl_duration(value: &str) -> Option {
+ let split = value
+ .find(|c: char| c.is_ascii_alphabetic())
+ .unwrap_or(value.len());
+ let (number, unit) = value.split_at(split);
+ let number = number
+ .parse::()
+ .ok()
+ .filter(|n| n.is_finite() && *n >= 0.0)?;
+ let factor = match unit {
+ "ms" => 0.001,
+ "s" | "" => 1.0,
+ "m" => 60.0,
+ "h" => 3600.0,
+ "d" => 86_400.0,
+ "w" => 604_800.0,
+ "y" => 31_536_000.0,
+ _ => return None,
+ };
+ Some((number * factor).round() as u64)
+}
+
+fn header_of<'a>(ident: &'a str, prefixes: &[&str]) -> Option<&'a str> {
+ prefixes
+ .iter()
+ .find_map(|prefix| ident.strip_prefix(prefix))
+}
+
+struct VclAtomResult {
+ condition: RuleCondition,
+}
+
+fn vcl_atom(
+ tokens: &[VclToken],
+ stage: RuleStage,
+ negate: bool,
+) -> std::result::Result {
+ let ident = match tokens.first() {
+ Some(VclToken::Ident(value)) => value.as_str(),
+ other => return Err(format!("unsupported condition {other:?}")),
+ };
+ let lower = ident.to_ascii_lowercase();
+ let request_prefixes: &[&str] = &["req.http.", "bereq.http."];
+ let response_prefixes: &[&str] = &["beresp.http.", "resp.http.", "obj.http."];
+ let (field, name) = if matches!(lower.as_str(), "req.url" | "bereq.url") {
+ (ConditionField::Url, None)
+ } else if matches!(
+ lower.as_str(),
+ "req.method" | "req.request" | "bereq.method"
+ ) {
+ (ConditionField::Method, None)
+ } else if matches!(
+ lower.as_str(),
+ "beresp.status" | "resp.status" | "obj.status"
+ ) {
+ (ConditionField::Status, None)
+ } else if matches!(lower.as_str(), "client.ip") {
+ return Err(
+ "client.ip with an ACL is not imported; add a client IP condition with the CIDR list"
+ .into(),
+ );
+ } else if let Some(header) = header_of(ident, request_prefixes) {
+ if header.eq_ignore_ascii_case("host") {
+ (ConditionField::Host, None)
+ } else {
+ (ConditionField::Header, Some(header.to_owned()))
+ }
+ } else if let Some(header) = header_of(ident, response_prefixes) {
+ if stage == RuleStage::Request {
+ return Err(format!("{ident} is not available in vcl_recv"));
+ }
+ if header.eq_ignore_ascii_case("content-type") {
+ (ConditionField::ContentType, None)
+ } else {
+ (ConditionField::ResponseHeader, Some(header.to_owned()))
+ }
+ } else {
+ return Err(format!("unsupported variable {ident}"));
+ };
+ let make = |operator, values: Vec, negated: bool| VclAtomResult {
+ condition: RuleCondition {
+ field,
+ name: name.clone(),
+ operator,
+ values,
+ negate: negated,
+ },
+ };
+ if tokens.len() == 1 {
+ return if name.is_some() {
+ Ok(make(ConditionOperator::Exists, Vec::new(), negate))
+ } else {
+ Err(format!("bare {ident} test is not supported"))
+ };
+ }
+ let value = match tokens.get(2) {
+ Some(VclToken::Str(value)) | Some(VclToken::Num(value)) | Some(VclToken::Ident(value)) => {
+ value.clone()
+ }
+ _ => return Err(format!("unsupported comparison on {ident}")),
+ };
+ if tokens.len() > 3 {
+ return Err(format!("expression on {ident} is too complex"));
+ }
+ let operator = match tokens.get(1) {
+ Some(VclToken::Sym(symbol)) => *symbol,
+ _ => return Err(format!("unsupported comparison on {ident}")),
+ };
+ if field == ConditionField::Status {
+ let code = value
+ .parse::()
+ .map_err(|_| format!("invalid status {value}"))?;
+ let range = match operator {
+ "==" => format!("{code}"),
+ "!=" => {
+ return Ok(make(
+ ConditionOperator::Equals,
+ vec![format!("{code}")],
+ !negate,
+ ))
+ }
+ ">=" => format!("{code}-599"),
+ ">" => format!("{}-599", code + 1),
+ "<=" => format!("100-{code}"),
+ "<" => format!("100-{}", code.saturating_sub(1)),
+ _ => return Err(format!("unsupported status comparison {operator}")),
+ };
+ return Ok(make(ConditionOperator::Equals, vec![range], negate));
+ }
+ match operator {
+ "~" => Ok(make(ConditionOperator::Regex, vec![value], negate)),
+ "!~" => Ok(make(ConditionOperator::Regex, vec![value], !negate)),
+ "==" => Ok(make(ConditionOperator::Equals, vec![value], negate)),
+ "!=" => Ok(make(ConditionOperator::Equals, vec![value], !negate)),
+ _ => Err(format!("unsupported operator {operator} on {ident}")),
+ }
+}
+
+fn vcl_conditions(
+ expr: &VclExpr,
+ stage: RuleStage,
+) -> std::result::Result<(RuleMatch, Vec), String> {
+ let single = |expr: &VclExpr| -> std::result::Result {
+ match expr {
+ VclExpr::Atom(tokens) => vcl_atom(tokens, stage, false).map(|atom| atom.condition),
+ VclExpr::Not(inner) => match inner.as_ref() {
+ VclExpr::Atom(tokens) => vcl_atom(tokens, stage, true).map(|atom| atom.condition),
+ _ => Err("negated groups are not supported".into()),
+ },
+ _ => Err("nested && / || groups are not supported".into()),
+ }
+ };
+ match expr {
+ VclExpr::And(items) => Ok((
+ RuleMatch::All,
+ items
+ .iter()
+ .map(single)
+ .collect::>()?,
+ )),
+ VclExpr::Or(items) => Ok((
+ RuleMatch::Any,
+ items
+ .iter()
+ .map(single)
+ .collect::>()?,
+ )),
+ other => Ok((RuleMatch::All, vec![single(other)?])),
+ }
+}
+
+fn query_params_from_regex(pattern: &str) -> Vec {
+ static CLASS: std::sync::LazyLock = std::sync::LazyLock::new(|| {
+ regex::Regex::new(r"\[[^\]]*\][+*]?|\.\*|\.\+").expect("static regex")
+ });
+ let simplified = CLASS.replace_all(pattern, "*");
+ let mut params = Vec::new();
+ for token in
+ simplified.split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '*')))
+ {
+ if token.len() > 64
+ || !token
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_ascii_alphabetic())
+ {
+ continue;
+ }
+ let token = token.to_owned();
+ if !params.contains(&token) {
+ params.push(token);
+ }
+ }
+ params
+}
+
+fn vcl_actions(
+ tokens: &[VclToken],
+ stage: RuleStage,
+) -> std::result::Result, String> {
+ let words: Vec = tokens
+ .iter()
+ .map(|token| match token {
+ VclToken::Ident(value) | VclToken::Str(value) | VclToken::Num(value) => value.clone(),
+ VclToken::Sym(symbol) => (*symbol).to_owned(),
+ })
+ .collect();
+ let first = words
+ .first()
+ .map(|word| word.to_ascii_lowercase())
+ .unwrap_or_default();
+ let joined = words.join(" ").to_ascii_lowercase();
+ match (stage, first.as_str()) {
+ (_, "return") => {
+ let target = words
+ .get(2)
+ .map(|word| word.to_ascii_lowercase())
+ .unwrap_or_default();
+ match (stage, target.as_str()) {
+ (RuleStage::Request, "pass" | "pipe") => Ok(vec![RuleAction::Pass]),
+ (RuleStage::Request, "hash" | "lookup") => Ok(Vec::new()),
+ (RuleStage::Response, "pass" | "hit_for_pass" | "uncacheable") => {
+ Ok(vec![RuleAction::NoStore])
+ }
+ (RuleStage::Response, "deliver") | (RuleStage::Deliver, "deliver") => {
+ Ok(Vec::new())
+ }
+ _ => Err(format!("return ({target}) is not supported here")),
+ }
+ }
+ (RuleStage::Request, "unset")
+ if words
+ .get(1)
+ .is_some_and(|word| word.eq_ignore_ascii_case("req.http.cookie")) =>
+ {
+ Ok(vec![RuleAction::StripCookies { keep: Vec::new() }])
+ }
+ (RuleStage::Request, "set")
+ if words
+ .get(1)
+ .is_some_and(|word| word.eq_ignore_ascii_case("req.url"))
+ && joined.contains("regsub") =>
+ {
+ let pattern = words
+ .iter()
+ .find(|word| word.contains('?') || word.contains('&') || word.contains("utm"))
+ .cloned()
+ .unwrap_or_default();
+ let params = query_params_from_regex(&pattern);
+ if params.is_empty() {
+ Err("req.url rewrite not recognised as query parameter removal".into())
+ } else {
+ Ok(vec![RuleAction::StripQuery {
+ params,
+ keep_only: false,
+ }])
+ }
+ }
+ (RuleStage::Request, "hash_data") => match words.get(2) {
+ Some(word)
+ if word.to_ascii_lowercase().starts_with("req.http.")
+ && !word.eq_ignore_ascii_case("req.http.cookie") =>
+ {
+ Ok(vec![RuleAction::HashHeader {
+ name: word[9..].to_owned(),
+ }])
+ }
+ _ => Err("hash_data is only imported for a single request header".into()),
+ },
+ (RuleStage::Response, "set") => {
+ let target = words
+ .get(1)
+ .map(|word| word.to_ascii_lowercase())
+ .unwrap_or_default();
+ let value = words.get(3).cloned().unwrap_or_default();
+ match target.as_str() {
+ "beresp.ttl" => vcl_duration(&value)
+ .map(|seconds| vec![RuleAction::Ttl { seconds }])
+ .ok_or_else(|| format!("invalid duration {value}")),
+ "beresp.grace" => vcl_duration(&value)
+ .map(|seconds| vec![RuleAction::Grace { seconds }])
+ .ok_or_else(|| format!("invalid duration {value}")),
+ "beresp.uncacheable" if value.eq_ignore_ascii_case("true") => {
+ Ok(vec![RuleAction::NoStore])
+ }
+ _ => Err(format!("set {target} is not supported")),
+ }
+ }
+ (RuleStage::Response, "unset") => {
+ match words.get(1).map(|word| word.to_ascii_lowercase()) {
+ Some(word) if word == "beresp.http.set-cookie" => {
+ Ok(vec![RuleAction::StripSetCookie])
+ }
+ Some(word)
+ if word == "beresp.http.cache-control"
+ || word == "beresp.http.expires"
+ || word == "beresp.http.pragma" =>
+ {
+ Ok(vec![RuleAction::IgnoreCacheControl])
+ }
+ Some(word) => Err(format!("unset {word} is not supported")),
+ None => Err("unset without a target".into()),
+ }
+ }
+ (RuleStage::Deliver, "set") => {
+ let target = words.get(1).cloned().unwrap_or_default();
+ let name = target
+ .strip_prefix("resp.http.")
+ .or_else(|| target.strip_prefix("RESP.HTTP."))
+ .ok_or_else(|| format!("set {target} is not supported"))?;
+ match (tokens.get(3), tokens.len()) {
+ (Some(VclToken::Str(value)), 4) => Ok(vec![RuleAction::SetHeader {
+ name: name.to_owned(),
+ value: value.clone(),
+ }]),
+ _ => Err(format!(
+ "set resp.http.{name} only supports a constant string"
+ )),
+ }
+ }
+ (RuleStage::Deliver, "unset") => {
+ let target = words.get(1).cloned().unwrap_or_default();
+ target
+ .strip_prefix("resp.http.")
+ .map(|name| {
+ vec![RuleAction::RemoveHeader {
+ name: name.to_owned(),
+ }]
+ })
+ .ok_or_else(|| format!("unset {target} is not supported"))
+ }
+ _ => Err(format!("statement '{}' is not supported", words.join(" "))),
+ }
+}
+
+fn vcl_stage(name: &str) -> Option {
+ match name {
+ "vcl_recv" | "vcl_hash" => Some(RuleStage::Request),
+ "vcl_backend_response" | "vcl_fetch" => Some(RuleStage::Response),
+ "vcl_deliver" => Some(RuleStage::Deliver),
+ _ => None,
+ }
+}
+
+struct VclBuilder {
+ rules: Vec,
+ warnings: Vec,
+ ids: HashSet,
+}
+
+impl VclBuilder {
+ fn push(
+ &mut self,
+ stage: RuleStage,
+ match_mode: RuleMatch,
+ conditions: Vec,
+ actions: Vec,
+ line: usize,
+ ) {
+ if actions.is_empty() {
+ return;
+ }
+ if self.rules.len() >= MAX_CACHE_RULES {
+ self.warnings.push(format!(
+ "line {line}: rule limit reached, the rest of the VCL was skipped"
+ ));
+ return;
+ }
+ let base = format!("vcl-{}-{line}", stage.label());
+ let mut id = base.clone();
+ let mut index = 2;
+ while !self.ids.insert(id.clone()) {
+ id = format!("{base}-{index}");
+ index += 1;
+ }
+ let rule = Rule {
+ id: id.clone(),
+ name: format!(
+ "VCL {} line {line}",
+ match stage {
+ RuleStage::Request => "vcl_recv",
+ RuleStage::Response => "vcl_backend_response",
+ RuleStage::Deliver => "vcl_deliver",
+ }
+ ),
+ enabled: true,
+ stage,
+ match_mode,
+ conditions,
+ actions,
+ stop: false,
+ vhosts: Vec::new(),
+ };
+ match compile_rule(&rule, RuleOrigin::Global, "") {
+ Ok(_) => self.rules.push(rule),
+ Err(error) => self.warnings.push(format!("line {line}: {error}")),
+ }
+ }
+
+ fn statements(
+ &mut self,
+ stage: RuleStage,
+ statements: &[VclStatement],
+ inherited: Option<(RuleMatch, Vec)>,
+ ) {
+ let mut pending: Vec = Vec::new();
+ let mut pending_line = 0;
+ let flush = |builder: &mut Self,
+ pending: &mut Vec,
+ line: usize,
+ inherited: &Option<(RuleMatch, Vec)>| {
+ let (mode, conditions) = inherited.clone().unwrap_or((RuleMatch::All, Vec::new()));
+ builder.push(stage, mode, conditions, std::mem::take(pending), line);
+ };
+ for statement in statements {
+ match statement {
+ VclStatement::Simple(tokens, line) => match vcl_actions(tokens, stage) {
+ Ok(actions) => {
+ if pending.is_empty() {
+ pending_line = *line;
+ }
+ pending.extend(actions);
+ }
+ Err(error) => self.warnings.push(format!("line {line}: {error}")),
+ },
+ VclStatement::If(branches, line) => {
+ flush(self, &mut pending, pending_line, &inherited);
+ if inherited.is_some() {
+ self.warnings.push(format!(
+ "line {line}: nested if is not imported; flatten it into one condition"
+ ));
+ continue;
+ }
+ let mut previous: Vec = Vec::new();
+ let mut previous_ok = true;
+ for (index, (condition, body)) in branches.iter().enumerate() {
+ let parsed = match condition {
+ Some(expr) => vcl_conditions(expr, stage),
+ None => {
+ if previous.len() == 1 && previous_ok {
+ let mut negated = previous[0].clone();
+ negated.negate = !negated.negate;
+ Ok((RuleMatch::All, vec![negated]))
+ } else {
+ Err("else branch after a complex condition is not imported"
+ .into())
+ }
+ }
+ };
+ match parsed {
+ Ok((mode, conditions)) => {
+ if index == 0 || condition.is_none() {
+ previous = conditions.clone();
+ } else {
+ previous_ok = false;
+ }
+ self.statements(stage, body, Some((mode, conditions)));
+ }
+ Err(error) => {
+ previous_ok = false;
+ self.warnings.push(format!("line {line}: {error}"));
+ }
+ }
+ }
+ }
+ }
+ }
+ flush(self, &mut pending, pending_line, &inherited);
+ }
+}
+
+pub fn import_vcl(source: &str) -> Result {
+ ensure!(
+ source.len() <= MAX_VCL_BYTES,
+ "VCL is limited to {} KiB",
+ MAX_VCL_BYTES / 1024
+ );
+ let tokens = vcl_tokens(source)?;
+ let mut parser = VclParser {
+ tokens,
+ position: 0,
+ };
+ let mut builder = VclBuilder {
+ rules: Vec::new(),
+ warnings: Vec::new(),
+ ids: HashSet::new(),
+ };
+ let mut found = false;
+ while let Some(token) = parser.next() {
+ match token {
+ VclToken::Ident(word) if word == "sub" => {
+ let line = parser.line();
+ let name = match parser.next() {
+ Some(VclToken::Ident(name)) => name,
+ other => {
+ anyhow::bail!("line {line}: expected subroutine name, found {other:?}")
+ }
+ };
+ let body = parser.block()?;
+ match vcl_stage(&name) {
+ Some(stage) => {
+ found = true;
+ builder.statements(stage, &body, None);
+ }
+ None => builder
+ .warnings
+ .push(format!("line {line}: sub {name} is not imported")),
+ }
+ }
+ VclToken::Ident(word) if matches!(word.as_str(), "vcl" | "import" | "include") => {
+ while !matches!(parser.next(), Some(VclToken::Sym(";")) | None) {}
+ }
+ VclToken::Ident(word) if matches!(word.as_str(), "backend" | "acl" | "probe") => {
+ let line = parser.line();
+ parser.next();
+ parser.block()?;
+ builder.warnings.push(format!("line {line}: {word} definitions are not imported; configure backends and ACLs in RustProxy"));
+ }
+ other => anyhow::bail!("line {}: unexpected {other:?} at top level", parser.line()),
+ }
+ }
+ ensure!(
+ found,
+ "no vcl_recv, vcl_backend_response or vcl_deliver subroutine found"
+ );
+ Ok(VclImport {
+ rules: builder.rules,
+ warnings: builder.warnings,
+ })
+}
diff --git a/src/config/routing.rs b/src/config/routing.rs
index 78e9573..78725dd 100644
--- a/src/config/routing.rs
+++ b/src/config/routing.rs
@@ -262,7 +262,7 @@ fn compile_routing(
headers: host.headers.compile()?,
security: host.security_headers.compile()?,
compression: host.compression.clone(),
- cache: host.cache.resolve(&config.cache)?,
+ cache: host.cache.resolve_for(&config.cache, &host.id)?,
force_cache: host.cache.unsafe_force.clone(),
transform: host.transform.resolve(&config.transform)?,
pages: host.pages.clone(),
diff --git a/src/prometheus/docker_misc.rs b/src/prometheus/docker_misc.rs
index b3fdaf5..4ed4142 100644
--- a/src/prometheus/docker_misc.rs
+++ b/src/prometheus/docker_misc.rs
@@ -159,6 +159,21 @@ fn render_misc(app: &App, snapshot: &crate::config::Snapshot, f: &mut Families)
);
}
if settings.include_cache_domains {
+ for (key, count) in crate::cache::rule_hit_counts() {
+ let (origin, rest) = key.split_once(':').unwrap_or(("global", key.as_str()));
+ let (vhost, rule) = if origin == "vhost" {
+ rest.split_once(':').unwrap_or(("", rest))
+ } else {
+ ("", rest)
+ };
+ f.add(
+ "rust_proxy_cache_rule_matches_total",
+ "counter",
+ "Cache rule matches since process start.",
+ &labels(&[("origin", origin), ("vhost", vhost), ("rule", rule)]),
+ count,
+ );
+ }
let dashboard = app.cache.dashboard(None, 0, 1);
f.add(
"rust_proxy_cache_statistics_revision",
diff --git a/src/proxy/forward/cache_lookup.rs b/src/proxy/forward/cache_lookup.rs
index 64143c0..26ed413 100644
--- a/src/proxy/forward/cache_lookup.rs
+++ b/src/proxy/forward/cache_lookup.rs
@@ -51,6 +51,7 @@ if let Some(ticket) = &cache_ticket {
local: local.0,
tls,
base_headers: request.headers().clone(),
+ rule_context: cache_rule_context.clone(),
};
let refresh_ticket = ticket.clone();
tokio::spawn(async move {
@@ -89,6 +90,7 @@ if let Some(ticket) = &cache_ticket {
local: local.0,
tls,
base_headers: request.headers().clone(),
+ rule_context: cache_rule_context.clone(),
},
ticket.clone(),
hit.remaining_ttl,
@@ -256,6 +258,7 @@ if handshake.is_none()
local: local.0,
tls,
base_headers: request.headers().clone(),
+ rule_context: cache_rule_context.clone(),
},
ticket.clone(),
hit.remaining_ttl,
diff --git a/src/proxy/forward/response.rs b/src/proxy/forward/response.rs
index 78ee38d..e85fc89 100644
--- a/src/proxy/forward/response.rs
+++ b/src/proxy/forward/response.rs
@@ -7,7 +7,7 @@
).await {
return fallback;
}
- let (origin_validation_headers, origin_plan, origin_reason, mut response) =
+ let (origin_validation_headers, origin_plan, origin_reason, mut response, cache_rule_overrides) =
include!("success_prepare.rs");
include!("success_finish.rs")
}
diff --git a/src/proxy/forward/route_cache.rs b/src/proxy/forward/route_cache.rs
index f1efec2..ad8abac 100644
--- a/src/proxy/forward/route_cache.rs
+++ b/src/proxy/forward/route_cache.rs
@@ -123,6 +123,51 @@ if let Some(exchange) = request.extensions().get::>() {
exchange.set_cache_enabled(cache_settings.active_for(route.cache));
exchange.set_transform_enabled(transform_settings.is_some_and(|settings| settings.enabled));
}
+let mut cache_rule_context: Option> = None;
+let mut cache_rule_query: Option> = None;
+let mut cache_rule_variant = String::new();
+let mut cache_rule_pass = false;
+if !admin_control_plane && cache_settings.active_for(route.cache) {
+ if let Some(rules) = cache_settings.compiled_rules.clone() {
+ let mut rule_request = crate::cache::RuleRequest {
+ host: host.clone(),
+ path: path.to_string(),
+ query: request.uri().query().map(str::to_owned),
+ method: request.method().clone(),
+ headers: request.headers().clone(),
+ client_ip: Some(context.client_ip),
+ };
+ let outcome = rules.evaluate_request(&rule_request, true);
+ if !outcome.matched.is_empty() {
+ outcome.rewrite_cookies(request.headers_mut());
+ cache_rule_query = outcome.rewrite_query(request.uri().query());
+ if let Some(query) = &cache_rule_query {
+ let target = match query {
+ Some(query) => format!("{}?{}", request.uri().path(), query),
+ None => request.uri().path().to_owned(),
+ };
+ let mut parts = request.uri().clone().into_parts();
+ if let Ok(value) = http::uri::PathAndQuery::try_from(target) {
+ parts.path_and_query = Some(value);
+ if let Ok(uri) = Uri::from_parts(parts) {
+ *request.uri_mut() = uri;
+ }
+ }
+ }
+ cache_rule_variant = outcome.hash_variant();
+ cache_rule_pass = outcome.pass.is_some();
+ rule_request.headers = request.headers().clone();
+ rule_request.query = request.uri().query().map(str::to_owned);
+ }
+ if rules.has_late_rules() {
+ let rule_context = Arc::new(crate::cache::RuleContext { rules, request: rule_request });
+ if let Some(sink) = request.extensions().get::() {
+ sink.set(rule_context.clone());
+ }
+ cache_rule_context = Some(rule_context);
+ }
+ }
+}
let policy_reason = if admin_control_plane {
Some("admin_control_plane")
} else if frontend.is_some_and(|f| f.basic_auth.is_some()) {
@@ -141,6 +186,8 @@ let policy_reason = if admin_control_plane {
Some("route_disabled")
} else if handshake.is_some() {
Some("request_upgrade")
+} else if cache_rule_pass {
+ Some("cache_rule")
} else {
None
};
@@ -161,9 +208,13 @@ let body_empty = if cache_enabled
} else {
cache_enabled && request.body().is_end_stream()
};
-let public_suffix: std::borrow::Cow<'_, str> = std::borrow::Cow::Borrowed(
- routing_uri.path_and_query().map(|v| v.as_str()).unwrap_or("/")
-);
+let public_suffix: std::borrow::Cow<'_, str> = match &cache_rule_query {
+ Some(query) => std::borrow::Cow::Owned(match query {
+ Some(query) => format!("{}?{}", routing_uri.path(), query),
+ None => routing_uri.path().to_owned(),
+ }),
+ None => std::borrow::Cow::Borrowed(routing_uri.path_and_query().map(|v| v.as_str()).unwrap_or("/")),
+};
let cache_plan = cache_plan::CachePlan::new(policy_reason, cache_settings, &path, || {
cache_settings.active_for(route.cache) && route
.frontend
@@ -287,7 +338,7 @@ let key_headers = cache_key_headers
.as_ref()
.unwrap_or_else(|| request.headers());
let cache_ticket = if effective_cacheable {
- state.cache.ticket_scoped_for_config(
+ state.cache.ticket_scoped_for_config_variant(
snapshot.envelope.revision,
state.cache.revision(),
route.frontend.as_ref().map(|f| f.id.as_str()).unwrap_or(""),
@@ -296,6 +347,7 @@ let cache_ticket = if effective_cacheable {
cache_route,
&public_suffix,
key_headers,
+ &cache_rule_variant,
).map(|ticket| ticket.with_varnish_compatible(cache_settings.varnish_compatible))
} else {
None
@@ -327,6 +379,6 @@ let miss_recorded = false;
origin_suffix, uri, exchange, lease, stop, downstream, h2_downstream,
range_selection, if_range, range_requested, effective_reason, revalidation_reason,
cache_ticket, client_conditionals, cached_revalidation, freshness_revalidation_reason,
- pending_revalidation, miss_recorded,
+ pending_revalidation, miss_recorded, cache_rule_context,
)
}
diff --git a/src/proxy/forward/success_finish.rs b/src/proxy/forward/success_finish.rs
index 37105f0..df1f3f2 100644
--- a/src/proxy/forward/success_finish.rs
+++ b/src/proxy/forward/success_finish.rs
@@ -96,11 +96,12 @@ let transformed_plan =
|| (ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie")) {
None
} else {
- crate::cache::plan(
+ crate::cache::plan_with(
response.status(),
response.headers(),
cache_settings,
upstream_started.elapsed(),
+ &cache_rule_overrides,
)
};
let outcome = if cache_ticket.is_some() {
@@ -181,6 +182,7 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
local: local.0,
tls,
base_headers: proactive_base_headers.clone(),
+ rule_context: cache_rule_context.clone(),
},
proactive_ticket,
proactive_remaining_ttl,
diff --git a/src/proxy/forward/success_prepare.rs b/src/proxy/forward/success_prepare.rs
index 4b40ac1..83a6bbc 100644
--- a/src/proxy/forward/success_prepare.rs
+++ b/src/proxy/forward/success_prepare.rs
@@ -112,14 +112,22 @@ if handshake.as_ref().is_some_and(|handshake| {
"RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n",
);
}
+let cache_rule_overrides = match (&cache_rule_context, cache_ticket.is_some()) {
+ (Some(rule_context), true) => rule_context.response_overrides(response.status(), response.headers()),
+ _ => crate::cache::ResponseOverrides::NONE,
+};
+if cache_rule_overrides.strip_set_cookie {
+ response.headers_mut().remove(::http::header::SET_COOKIE);
+}
let origin_plan = if cache_ticket.is_some()
&& !(ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie"))
{
- crate::cache::plan(
+ crate::cache::plan_with(
response.status(),
response.headers(),
cache_settings,
upstream_started.elapsed(),
+ &cache_rule_overrides,
).map(|plan| {
let plan = if force_vary_cookie { plan.with_vary("cookie") } else { plan };
if force_vary_authorization { plan.with_vary("authorization") } else { plan }
@@ -392,5 +400,5 @@ if !range_requested && handshake.is_none() {
};
}
}
- (origin_validation_headers, origin_plan, origin_reason, response)
+ (origin_validation_headers, origin_plan, origin_reason, response, cache_rule_overrides)
}
diff --git a/src/proxy/forward_entry.rs b/src/proxy/forward_entry.rs
index c1c0f45..a325d84 100644
--- a/src/proxy/forward_entry.rs
+++ b/src/proxy/forward_entry.rs
@@ -6,8 +6,11 @@ async fn forward(
) -> Response {
let cookies = crate::auth_provider::CookieSink::default();
request.extensions_mut().insert(cookies.clone());
+ let cache_rules = crate::cache::RuleSink::default();
+ request.extensions_mut().insert(cache_rules.clone());
let mut response = forward_request(state, peer, local, request).await;
cookies.apply(&mut response);
+ cache_rules.apply(&mut response);
response
}
@@ -593,6 +596,7 @@ async fn forward_request(
freshness_revalidation_reason,
pending_revalidation,
mut miss_recorded,
+ cache_rule_context,
) = include!("forward/route_cache.rs");
let (serve_stale, mut fill_leader) = include!("forward/cache_lookup.rs");
diff --git a/src/proxy/types.rs b/src/proxy/types.rs
index df0a374..06ff133 100644
--- a/src/proxy/types.rs
+++ b/src/proxy/types.rs
@@ -299,6 +299,7 @@ struct CacheRefreshContext {
local: std::net::SocketAddr,
tls: bool,
base_headers: http::HeaderMap,
+ rule_context: Option>,
}
async fn refresh_cache_once(
@@ -379,11 +380,21 @@ async fn refresh_cache_once(
if origin.status() != StatusCode::OK {
return false;
}
- let Some(origin_plan) = crate::cache::plan(
+ let rule_overrides = context
+ .rule_context
+ .as_ref()
+ .map(|rules| rules.response_overrides(origin.status(), origin.headers()))
+ .unwrap_or(crate::cache::ResponseOverrides::NONE);
+ let mut origin = origin;
+ if rule_overrides.strip_set_cookie {
+ origin.headers_mut().remove(::http::header::SET_COOKIE);
+ }
+ let Some(origin_plan) = crate::cache::plan_with(
origin.status(),
origin.headers(),
&context.cache_settings,
started.elapsed(),
+ &rule_overrides,
) else {
return false;
};
@@ -446,11 +457,12 @@ async fn refresh_cache_once(
.extensions()
.get::()
.is_some();
- let Some(transformed_plan) = crate::cache::plan(
+ let Some(transformed_plan) = crate::cache::plan_with(
refreshed.status(),
refreshed.headers(),
&context.cache_settings,
started.elapsed(),
+ &rule_overrides,
) else {
return false;
};
diff --git a/src/tls/server_config.rs b/src/tls/server_config.rs
index cf645cb..271cd51 100644
--- a/src/tls/server_config.rs
+++ b/src/tls/server_config.rs
@@ -2,8 +2,10 @@ fn certificate_dns_names(certificate: &[u8]) -> Result> {
let mut reader = certificate;
let certs = rustls_pemfile::certs(&mut reader).collect::>>()?;
let leaf = certs.first().context("certificate chain is empty")?;
- let der = leaf.as_ref();
+ certificate_der_dns_names(leaf.as_ref())
+}
+fn certificate_der_dns_names(der: &[u8]) -> Result> {
let mut root_offset = 0;
let (tag, certificate_sequence) = der_tlv(der, &mut root_offset)?;
ensure!(
@@ -346,6 +348,7 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result>::new();
+ let mut covered = HashMap::)>::new();
let mut ids = HashSet::new();
let mut hosts = HashSet::new();
let mut default = None;
@@ -353,6 +356,27 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result) -> Result Arc::new(load_pair(directory, "default.pem", "default.key")?),
};
Ok(Some(server_config(
- Arc::new(Resolver { names, fallback }),
+ Arc::new(Resolver {
+ names,
+ covered: covered
+ .into_iter()
+ .map(|(name, (_, key))| (name, key))
+ .collect(),
+ fallback,
+ }),
&settings.policy,
true,
)?))
diff --git a/src/tls/tests.rs b/src/tls/tests.rs
index ea35730..e95dc76 100644
--- a/src/tls/tests.rs
+++ b/src/tls/tests.rs
@@ -384,6 +384,29 @@ mod tests {
assert!(compile(&settings, Some(dir.path())).is_err());
}
#[test]
+ fn sni_wildcards_cover_one_label_and_san_names_are_used_before_the_default() {
+ let dir = private_tempdir();
+ generate(dir.path(), "parent", vec!["*.h.example.test".into()]).unwrap();
+ generate(dir.path(), "apps", vec!["*.apps.h.example.test".into()]).unwrap();
+ let parent = Arc::new(load_pair(dir.path(), "parent.pem", "parent.key").unwrap());
+ let apps = Arc::new(load_pair(dir.path(), "apps.pem", "apps.key").unwrap());
+ let resolver = Resolver {
+ names: HashMap::from([("*.h.example.test".to_string(), parent.clone())]),
+ covered: HashMap::from([("*.apps.h.example.test".to_string(), apps.clone())]),
+ fallback: parent.clone(),
+ };
+ assert!(Arc::ptr_eq(&resolver.named("x.h.example.test").unwrap(), &parent));
+ assert!(Arc::ptr_eq(&resolver.named("x.apps.h.example.test").unwrap(), &apps));
+ assert!(resolver.named("deep.x.h.example.test").is_none());
+ assert_eq!(single_label_wildcard("a.b.c").as_deref(), Some("*.b.c"));
+ assert_eq!(single_label_wildcard("a.b"), None);
+ let leaf = apps.cert.first().unwrap();
+ assert_eq!(
+ certificate_der_dns_names(leaf.as_ref()).unwrap(),
+ ["*.apps.h.example.test"]
+ );
+ }
+ #[test]
fn named_generation_never_overwrites_keys() {
let dir = private_tempdir();
generate(dir.path(), "app", vec!["app.localhost".into()]).unwrap();
diff --git a/src/tls/types.rs b/src/tls/types.rs
index b12d790..a4a1eea 100644
--- a/src/tls/types.rs
+++ b/src/tls/types.rs
@@ -266,22 +266,22 @@ pub struct Certificate {
#[derive(Debug)]
struct Resolver {
names: HashMap>,
+ covered: HashMap>,
fallback: Arc,
}
+fn single_label_wildcard(host: &str) -> Option {
+ let (first, rest) = host.split_once('.')?;
+ (!first.is_empty() && rest.contains('.')).then(|| format!("*.{rest}"))
+}
+fn lookup(map: &HashMap>, host: &str) -> Option> {
+ map.get(host)
+ .or_else(|| single_label_wildcard(host).and_then(|wildcard| map.get(&wildcard)))
+ .cloned()
+}
impl Resolver {
fn named(&self, server_name: &str) -> Option> {
let host = normalize_host(server_name).ok()?;
- if let Some(key) = self.names.get(&host) {
- return Some(key.clone());
- }
- let labels: Vec<&str> = host.split('.').collect();
- for index in 1..labels.len().saturating_sub(1) {
- let wildcard = format!("*.{}", labels[index..].join("."));
- if let Some(key) = self.names.get(&wildcard) {
- return Some(key.clone());
- }
- }
- None
+ lookup(&self.names, &host).or_else(|| lookup(&self.covered, &host))
}
}
impl ResolvesServerCert for Resolver {
diff --git a/tests/panel_refresh_contract.js b/tests/panel_refresh_contract.js
index 0b149b2..16aa6b9 100644
--- a/tests/panel_refresh_contract.js
+++ b/tests/panel_refresh_contract.js
@@ -51,5 +51,5 @@ const events = openapi.paths["/api/events"].get;
const logsFlag = (events.parameters || []).find(parameter => parameter.name === "logs");
assert.equal(logsFlag?.schema?.type, "boolean");
assert.equal(logsFlag?.schema?.default, true);
-assert.equal(openapi.info.version, "0.37.0");
+assert.equal(openapi.info.version, "0.37.1");
console.log("Panel refresh/API contract checks: OK");