v0.43.1
This commit is contained in:
1 parent
5b6d4a7903
commit
4d1087e357
160 files changed
+2407
-1933
No files matched your search
@@ -37,7 +37,6 @@ struct DnsDiagnostic {
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// A read-only view of the live resolver, not a second source of ACL permissions.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct DnsAclStatus {
|
||||
pub hostname: String,
|
||||
|
||||
@@ -1,24 +1,14 @@
|
||||
// Headless ACME: issues and renews the certificates requested with
|
||||
// `--acme-domains` through the same Certbot worker as the panel. Results are
|
||||
// kept in `<data-dir>/certs/headless-acme.json` and merged into the
|
||||
// configuration on reload, so the configuration file stays read-only.
|
||||
|
||||
const HEADLESS_ACME_ACTOR: &str = "system:headless-acme";
|
||||
const HEADLESS_ACME_CHECK_SECONDS: i64 = 12 * 3600;
|
||||
const HEADLESS_ACME_RETRY_SECONDS: [i64; 6] = [600, 1800, 3600, 3 * 3600, 6 * 3600, 12 * 3600];
|
||||
/// Renewal request left in the data directory by `rust-proxy --headless tls renew`.
|
||||
pub const HEADLESS_ACME_RENEW_FILE: &str = "headless-acme-renew.json";
|
||||
/// Requests older than this (for example written while the service was down)
|
||||
/// are discarded instead of forcing a renewal after a later restart.
|
||||
const HEADLESS_ACME_RENEW_MAX_AGE: i64 = 600;
|
||||
const HEADLESS_ACME_RENEW_MAX_TARGETS: usize = 64;
|
||||
|
||||
static HEADLESS_ACME_RENEW: std::sync::LazyLock<tokio::sync::Notify> =
|
||||
std::sync::LazyLock::new(tokio::sync::Notify::new);
|
||||
|
||||
/// Operator request to check (or, with `force`, re-issue) headless ACME
|
||||
/// certificates now. An empty target list means every headless ACME certificate;
|
||||
/// a target is a certificate id (`hl-acme-…`) or one of its domain names.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HeadlessRenewRequest {
|
||||
@@ -47,7 +37,6 @@ impl HeadlessRenewRequest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether this request selects the certificate `id` covering `names`.
|
||||
pub fn selects(&self, id: &str, names: &[String]) -> bool {
|
||||
self.targets.is_empty()
|
||||
|| self.targets.iter().any(|target| {
|
||||
@@ -56,8 +45,6 @@ impl HeadlessRenewRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a renewal request for the running headless service (atomically,
|
||||
/// mode 0600, owned by the owner of the data directory).
|
||||
pub fn write_headless_renew_request(
|
||||
data_dir: &std::path::Path,
|
||||
request: &HeadlessRenewRequest,
|
||||
@@ -79,7 +66,6 @@ pub fn write_headless_renew_request(
|
||||
file.sync_all()?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// The CLI usually runs as root while the service runs as its own user.
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let owner = std::fs::metadata(data_dir)?;
|
||||
if owner.uid() != unsafe { libc::geteuid() } {
|
||||
@@ -95,8 +81,6 @@ pub fn write_headless_renew_request(
|
||||
result.map(|()| path)
|
||||
}
|
||||
|
||||
/// Reads and removes a pending renewal request. Invalid or stale requests are
|
||||
/// removed and reported as errors.
|
||||
pub fn take_headless_renew_request(
|
||||
data_dir: &std::path::Path,
|
||||
now: i64,
|
||||
@@ -133,7 +117,6 @@ pub fn take_headless_renew_request(
|
||||
Ok(Some(request))
|
||||
}
|
||||
|
||||
/// Wakes the headless ACME task to process a renewal request (SIGUSR1).
|
||||
pub fn request_headless_acme_renewal() {
|
||||
HEADLESS_ACME_RENEW.notify_one();
|
||||
}
|
||||
@@ -325,7 +308,6 @@ pub struct HeadlessAcmeStatus {
|
||||
static HEADLESS_ACME_STATUS: std::sync::Mutex<std::collections::BTreeMap<String, HeadlessAcmeStatus>> =
|
||||
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// Status of the headless ACME certificates for the health listener.
|
||||
pub fn headless_acme_status() -> std::collections::BTreeMap<String, HeadlessAcmeStatus> {
|
||||
HEADLESS_ACME_STATUS
|
||||
.lock()
|
||||
@@ -339,8 +321,6 @@ fn set_headless_status(id: &str, update: impl FnOnce(&mut HeadlessAcmeStatus)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes automatic certificates that are no longer wanted: their served
|
||||
/// names are gone, or every served name already has an issued replacement.
|
||||
async fn headless_acme_prune(
|
||||
state: &Arc<App>,
|
||||
directory: &std::path::Path,
|
||||
@@ -408,14 +388,10 @@ async fn headless_acme_prune(
|
||||
tracing::info!(certificates = ?stale, "automatic ACME certificates no longer needed (hosts removed or replaced) were deleted");
|
||||
}
|
||||
|
||||
/// Background task of headless mode: issues and renews the certificates of
|
||||
/// `--acme-domains` / `headless.acme.domains` and, with `auto`, of every
|
||||
/// vhost host without a certificate. Settings are re-read after each reload.
|
||||
pub async fn headless_loop(
|
||||
weak: std::sync::Weak<App>,
|
||||
shutdown: tokio_util::sync::CancellationToken,
|
||||
) {
|
||||
// Give the listeners a moment so the HTTP-01 challenge can be answered.
|
||||
tokio::select! { _ = shutdown.cancelled() => return, _ = tokio::time::sleep(Duration::from_secs(3)) => {} }
|
||||
let mut next: std::collections::HashMap<String, i64> = Default::default();
|
||||
let mut failures: std::collections::HashMap<String, usize> = Default::default();
|
||||
@@ -450,7 +426,6 @@ pub async fn headless_loop(
|
||||
tracing::warn!("headless ACME renewal requested, but no ACME certificates are configured");
|
||||
}
|
||||
if let Some(acme) = acme.clone() {
|
||||
// A changed provider/environment makes every certificate due again.
|
||||
let current = (acme.provider.clone(), acme.environment.clone());
|
||||
if fingerprint.as_ref() != Some(¤t) {
|
||||
next.clear();
|
||||
|
||||
@@ -147,9 +147,12 @@ async fn cache_rules_test(
|
||||
let mut request_outcome = rules.evaluate_request(&request, false);
|
||||
let mut rule_gate = crate::cache::RuleGate::from_outcome(&request_outcome);
|
||||
if rule_gate == crate::cache::RuleGate::CookieGuard && settings.enabled {
|
||||
if let Some(relaxed) =
|
||||
crate::cache::static_cookie_guard_relaxation(&rules, &request, &request_outcome, &settings)
|
||||
{
|
||||
if let Some(relaxed) = crate::cache::static_cookie_guard_relaxation(
|
||||
&rules,
|
||||
&request,
|
||||
&request_outcome,
|
||||
&settings,
|
||||
) {
|
||||
request_outcome = relaxed.outcome;
|
||||
rule_gate = crate::cache::RuleGate::CookieGuardRelaxed;
|
||||
}
|
||||
@@ -166,15 +169,21 @@ async fn cache_rules_test(
|
||||
Some(query) => format!("{path}?{query}"),
|
||||
None => path.clone(),
|
||||
};
|
||||
// Same precedence as live traffic (cache::request_gate). Vhost security
|
||||
// gates (Basic auth, providers, sticky pools) are not simulated here.
|
||||
let request_policy = crate::cache::request_gate(
|
||||
crate::cache::GateInput { cache_enabled: settings.enabled, ..Default::default() },
|
||||
crate::cache::GateInput {
|
||||
cache_enabled: settings.enabled,
|
||||
..Default::default()
|
||||
},
|
||||
rule_gate,
|
||||
)
|
||||
.or_else(|| {
|
||||
crate::cache::request_policy_with_vcl_cookie(
|
||||
&method, &headers, true, &path, query.is_some(), &settings,
|
||||
&method,
|
||||
&headers,
|
||||
true,
|
||||
&path,
|
||||
query.is_some(),
|
||||
&settings,
|
||||
request_outcome.lookup.is_some(),
|
||||
)
|
||||
.bypass_reason()
|
||||
|
||||
@@ -498,7 +498,6 @@ struct RenewRequest {
|
||||
certificate_id: String,
|
||||
#[serde(default)]
|
||||
dry_run: bool,
|
||||
/// Renew even when Certbot does not consider the certificate due.
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
}
|
||||
@@ -21,17 +21,11 @@ struct FileLogSource {
|
||||
size: u64,
|
||||
modified_ms: u64,
|
||||
compressed: bool,
|
||||
/// 0 = file being written; N = rotation `.N` / `.N.gz` (higher is older).
|
||||
rotation: u32,
|
||||
/// vhost, redirect, host404, unmatched, access or error.
|
||||
scope: &'static str,
|
||||
/// Site id for per-site logs (vhost, redirect or 404 host id).
|
||||
site: String,
|
||||
/// Current configured hostnames, not inferred from historical log records.
|
||||
domains: Vec<String>,
|
||||
}
|
||||
/// Splits `<base>.jsonl[.<N>][.gz]` (or `<file>[.<N>][.gz]` for the global logs)
|
||||
/// into the rotation index; `None` for files that are not part of the set.
|
||||
fn rotation_suffix(rest: &str) -> Option<(u32, bool)> {
|
||||
if rest.is_empty() {
|
||||
return Some((0, false));
|
||||
@@ -44,10 +38,8 @@ fn rotation_suffix(rest: &str) -> Option<(u32, bool)> {
|
||||
if !number.is_empty() && number.len() <= 6 && number.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return number.parse().ok().map(|n: u32| (n.max(1), compressed));
|
||||
}
|
||||
// Other compressed rotations (e.g. `.old.gz`) sort after numbered ones.
|
||||
compressed.then_some((u32::MAX, true))
|
||||
}
|
||||
/// Scope and site of a per-site log base name (`app`, `old.redirect`, `park.host404`).
|
||||
fn site_scope(base: &str) -> (&'static str, String) {
|
||||
if base == "_unmatched" {
|
||||
return ("unmatched", String::new());
|
||||
@@ -70,7 +62,6 @@ struct FileLogQuery {
|
||||
client_ip: Option<String>,
|
||||
vhost: Option<String>,
|
||||
consolidate_vhosts: Option<bool>,
|
||||
/// Only records at or after this time (ms since the epoch).
|
||||
since_ms: Option<u64>,
|
||||
aggregate_field: Option<String>,
|
||||
aggregate_limit: Option<usize>,
|
||||
@@ -131,8 +122,6 @@ fn source_from_path(
|
||||
}
|
||||
include!("file_logs_io.rs");
|
||||
|
||||
/// Build a scope-aware hostname catalog, including Docker assignments even when
|
||||
/// their writer is disabled/offline and currently discovered label publications.
|
||||
fn file_log_vhost_domains(
|
||||
config: &crate::config::Config,
|
||||
observed: &std::collections::BTreeMap<String, crate::docker::Observation>,
|
||||
|
||||
@@ -24,8 +24,6 @@ fn newest_log_files(
|
||||
result
|
||||
}
|
||||
|
||||
/// Rotated copies of a global log: `<file>.N`, `<file>.N.gz` (logrotate with or
|
||||
/// without `delaycompress`) and other `<file>.*.gz`, newest rotation first.
|
||||
fn rotated_gzip_sources(
|
||||
active: &std::path::Path,
|
||||
id_prefix: &str,
|
||||
@@ -90,7 +88,6 @@ fn rotated_gzip_sources(
|
||||
sort_by_rotation(&mut sources);
|
||||
sources
|
||||
}
|
||||
/// Newest data first: the file being written, then `.1`, `.2`, … (ties by mtime).
|
||||
fn sort_by_rotation(sources: &mut [FileLogSource]) {
|
||||
sources.sort_by(|a, b| {
|
||||
a.rotation
|
||||
|
||||
@@ -208,7 +208,6 @@ fn validate_file_log_query(query: &FileLogQuery) -> Result<(), ApiError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs a stored-log query (blocking file I/O).
|
||||
fn file_log_query_blocking(
|
||||
config: &crate::config::Config,
|
||||
observed: &std::collections::BTreeMap<String, crate::docker::Observation>,
|
||||
@@ -220,10 +219,6 @@ fn file_log_query_blocking(
|
||||
let requested = query.source.as_deref().unwrap_or("all");
|
||||
let mut truncated = false;
|
||||
let mut files_skipped = 0usize;
|
||||
// One site/log (all its rotations) or one file is read newest-first: each file
|
||||
// may use the whole remaining budget, so the newest records are always
|
||||
// complete and older rotations are read only while budget remains. "All"
|
||||
// spreads the budget over the newest file of every log first.
|
||||
let sequential = requested != "all";
|
||||
if requested != "all" {
|
||||
let consolidate = query.consolidate_vhosts.unwrap_or(false);
|
||||
@@ -334,8 +329,6 @@ fn file_log_query_blocking(
|
||||
records.push(value);
|
||||
}
|
||||
}
|
||||
// Older rotations only hold older records: stop once a whole file
|
||||
// is before the requested period.
|
||||
if sequential
|
||||
&& since_ms.is_some_and(|since| file_newest.is_some_and(|n| n < since))
|
||||
{
|
||||
|
||||
@@ -240,10 +240,6 @@ async fn events(
|
||||
.into_response())
|
||||
}
|
||||
|
||||
/// List the effective (compiled) reverse-proxy vhosts, including Docker
|
||||
/// assignments. The persisted config deliberately excludes generated routes.
|
||||
/// Catalog fingerprints also change when Docker inventory changes without
|
||||
/// increasing the persisted configuration revision.
|
||||
fn monitored_vhost_catalog(state: &Arc<App>) -> (Vec<crate::vhost::Vhost>, Vec<Value>, String) {
|
||||
let snapshot = state.config.load_full();
|
||||
let desired = &snapshot.envelope.config;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "RustProxy Administration API",
|
||||
"version": "0.43.0",
|
||||
"version": "0.43.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": [
|
||||
|
||||
@@ -338,24 +338,16 @@ struct CertificateDeploy {
|
||||
key_pem: String,
|
||||
}
|
||||
|
||||
/// Query for the local page preview used by the 404 host editor.
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
struct PagePreviewQuery {
|
||||
kind: String,
|
||||
status: Option<u16>,
|
||||
/// 404 host ID whose saved custom HTML is previewed.
|
||||
host: Option<String>,
|
||||
/// Saved custom HTML of a default response: `direct_ip`, `unknown_host`,
|
||||
/// `response`, `fallback` or `error-<code>`; with `vhost` for per-vhost pages.
|
||||
slot: Option<String>,
|
||||
vhost: Option<String>,
|
||||
}
|
||||
|
||||
/// Renders a built-in local page (or the saved custom HTML of a 404 host)
|
||||
/// exactly as `Page::render` serves it. The session guard sends this response
|
||||
/// with a sandbox CSP, so the document runs in an opaque origin without
|
||||
/// scripts and may only be framed by the panel itself.
|
||||
async fn page_preview(
|
||||
State(state): State<Arc<App>>,
|
||||
Query(query): Query<PagePreviewQuery>,
|
||||
@@ -413,6 +405,5 @@ async fn page_preview(
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Marks a sandboxed page preview for the session guard.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PagePreview;
|
||||
@@ -407,8 +407,6 @@ async fn guard(State(state): State<Arc<App>>, mut request: Request, next: Next)
|
||||
}
|
||||
}
|
||||
if response.extensions().get::<PagePreview>().is_some() && response.status().is_success() {
|
||||
// Rendered page previews may contain operator HTML: no scripts, an
|
||||
// opaque origin, and framing only by the panel itself.
|
||||
response.headers_mut().insert("content-security-policy", HeaderValue::from_static(
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"));
|
||||
response
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
include!("status_system.rs");
|
||||
|
||||
/// Live, read-only diagnostics for every configured DNS/DDNS ACL hostname.
|
||||
/// In particular, a successful lookup need not match the address of a caller.
|
||||
async fn dns_acl_status(State(state): State<Arc<App>>) -> Result<Json<Value>, ApiError> {
|
||||
let snapshot = state.config.load();
|
||||
let hostnames = crate::acl::dynamic::statuses(&snapshot.envelope.config).map_err(|error| {
|
||||
|
||||
@@ -3411,7 +3411,6 @@ mod tests {
|
||||
.unwrap();
|
||||
write_gz(&dir.path().join("mail.jsonl.2.gz"), &records(200, 210));
|
||||
write_gz(&dir.path().join("mail.jsonl.10.gz"), &records(100, 110));
|
||||
// The oldest rotation has the newest mtime (copied or touched files).
|
||||
std::fs::File::options()
|
||||
.append(true)
|
||||
.open(dir.path().join("mail.jsonl.10.gz"))
|
||||
|
||||
@@ -99,9 +99,6 @@ window.rustProxyChoicePicker = (() => {
|
||||
const maxHint = el("small", t("aclPickerLimit"), "fine acl-picker-limit");
|
||||
dropdown.append(search, optionsBox, empty, maxHint); details.append(dropdown);
|
||||
const selectedTags = el("div", undefined, "acl-picker-selected"); root.append(details, selectedTags);
|
||||
// Option rows are built on the first open: long lists (countries) would
|
||||
// otherwise add thousands of DOM nodes per picker. `state` is the source of
|
||||
// truth for every option; `checks` holds only rendered checkboxes.
|
||||
const items = [...(options.items || [])], state = new Map(), checks = new Map(), order = [];
|
||||
let rendered = false;
|
||||
const isChosen = id => state.get(id) === true;
|
||||
@@ -223,14 +220,12 @@ window.rustProxyChipInput = (() => {
|
||||
|
||||
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(" ");
|
||||
// Country names are resolved once per language: constructing Intl.DisplayNames
|
||||
// for every lookup was a large part of rendering many country pickers.
|
||||
const countryNames = new Map();
|
||||
const nameOf = code => {
|
||||
const lang = document.documentElement.lang || "en";
|
||||
let names = countryNames.get(lang);
|
||||
if (!names) { let display = null; try { display = new Intl.DisplayNames([lang], { type: "region" }); } catch { /* unsupported locale */ } names = { display, cache: new Map() }; countryNames.set(lang, names); }
|
||||
if (!names.cache.has(code)) { let name = code; try { name = names.display?.of(code) || code; } catch { /* unknown region */ } names.cache.set(code, name); }
|
||||
if (!names) { let display = null; try { display = new Intl.DisplayNames([lang], { type: "region" }); } catch { } names = { display, cache: new Map() }; countryNames.set(lang, names); }
|
||||
if (!names.cache.has(code)) { let name = code; try { name = names.display?.of(code) || code; } catch { } names.cache.set(code, name); }
|
||||
return names.cache.get(code);
|
||||
};
|
||||
const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
|
||||
|
||||
+78
-5
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
(() => {
|
||||
let job = null, pending = false, loading = false, renewalLogs = {}, resetIssueFormJob = null, runtimeAvailable = true;
|
||||
let sourceUiRef = null, job = null, pending = false, loading = false, renewalLogs = {}, resetIssueFormJob = null, runtimeAvailable = true;
|
||||
const picker = $("certificate-provider");
|
||||
const secrets = ["acme-secret", "acme-cf-token", "acme-ovh-application-key", "acme-ovh-application-secret", "acme-ovh-consumer-key"];
|
||||
const tabs = [...document.querySelectorAll("[data-certificate-tab]")];
|
||||
@@ -21,6 +21,7 @@
|
||||
if (selected && focus) button.focus();
|
||||
}
|
||||
document.querySelectorAll("[data-certificate-page]").forEach(page => { page.hidden = page.dataset.certificatePage !== name; });
|
||||
syncRuntimeVisibility();
|
||||
if (persist) syncLocation();
|
||||
}
|
||||
for (const button of tabs) {
|
||||
@@ -36,6 +37,7 @@
|
||||
});
|
||||
}
|
||||
|
||||
function syncRuntimeVisibility() { const card = $("acme-runtime-card"); if (card) card.hidden = activeTab !== "generate" && card.dataset.state !== "unavailable"; }
|
||||
const clearSecrets = () => { for (const id of secrets) $(id).value = ""; };
|
||||
function resetIssueForm() {
|
||||
$("acme-form").reset();
|
||||
@@ -60,6 +62,7 @@
|
||||
}
|
||||
$("acme-domains").placeholder = provider === "http01" ? "example.org, www.example.org" : "example.org, *.example.org";
|
||||
syncSubmitState();
|
||||
sourceUiRef?.sync();
|
||||
}
|
||||
function open(provider = "http01") {
|
||||
selectTab("generate"); picker.value = provider;
|
||||
@@ -68,13 +71,79 @@
|
||||
}
|
||||
function close() { clearSecrets(); selectTab("installed"); }
|
||||
picker.addEventListener("change", () => { clearSecrets(); syncProvider(); });
|
||||
sourceUiRef = (() => {
|
||||
const label = picker.closest("label"); if (!label) return { sync() { } };
|
||||
label.classList.add("provider-picker-legacy"); label.hidden = true;
|
||||
const box = el("div", undefined, "certificate-source");
|
||||
const modes = el("div", undefined, "certificate-source-modes"); modes.setAttribute("role", "radiogroup");
|
||||
const modeDefs = [["acme", "certificateSourceAcme"], ["import", "certificateSourceImport"], ["existing", "certificateSourceExisting"]];
|
||||
const modeButtons = modeDefs.map(([mode, key]) => {
|
||||
const button = el("button", t(key)); button.type = "button"; button.dataset.i18n = key; button.dataset.sourceMode = mode; button.dataset.uiIconName = "none"; button.setAttribute("role", "radio");
|
||||
button.addEventListener("click", () => {
|
||||
if (mode === "acme") setProvider(["import", "existing"].includes(picker.value) ? (lastAcme || "http01") : picker.value);
|
||||
else setProvider(mode);
|
||||
});
|
||||
modes.append(button); return button;
|
||||
});
|
||||
const acmeRow = el("div", undefined, "certificate-source-acme");
|
||||
const validationField = el("label"), validationLabel = el("span", t("certificateSourceValidation")); validationLabel.dataset.i18n = "certificateSourceValidation";
|
||||
const validation = el("select"); validation.id = "certificate-validation";
|
||||
for (const [value, key] of [["dns01", "certificateValidationDns"], ["http01", "certificateValidationHttp"]]) { const option = el("option", t(key)); option.value = value; option.dataset.i18n = key; validation.append(option); }
|
||||
validationField.append(validationLabel, validation);
|
||||
const providerField = el("div", undefined, "certificate-dns-provider"), providerLabel = el("span", t("certificateDnsProvider")); providerLabel.dataset.i18n = "certificateDnsProvider";
|
||||
const combo = el("div", undefined, "provider-combo");
|
||||
const input = el("input"); input.id = "certificate-dns-provider"; input.type = "text"; input.autocomplete = "off"; input.setAttribute("role", "combobox"); input.setAttribute("aria-expanded", "false"); input.setAttribute("aria-controls", "certificate-dns-provider-list");
|
||||
const list = el("ul", undefined, "provider-combo-list"); list.id = "certificate-dns-provider-list"; list.setAttribute("role", "listbox"); list.hidden = true;
|
||||
combo.append(input, list); providerField.append(providerLabel, combo);
|
||||
acmeRow.append(validationField, providerField);
|
||||
box.append(modes, acmeRow); label.after(box);
|
||||
const dnsProviders = () => [...picker.options].map(option => option.value).filter(value => !["http01", "import", "existing"].includes(value));
|
||||
const providerName = value => { const option = [...picker.options].find(item => item.value === value); return String(option?.textContent || value).replace(/^Let's Encrypt\s*[-–]\s*/i, "").replace(/\s*\(DNS-01\)\s*$/i, ""); };
|
||||
let lastAcme = "http01", lastDns = dnsProviders()[0] || "cloudflare", active = -1;
|
||||
function setProvider(value) { if (picker.value === value) { sync(); return; } picker.value = value; picker.dispatchEvent(new Event("change", { bubbles: true })); }
|
||||
function renderList(filter = "") {
|
||||
const query = filter.trim().toLowerCase();
|
||||
const items = dnsProviders().filter(value => !query || `${value} ${providerName(value)}`.toLowerCase().includes(query));
|
||||
list.replaceChildren(...items.map((value, index) => {
|
||||
const item = el("li", providerName(value)); item.setAttribute("role", "option"); item.dataset.value = value; item.id = `certificate-dns-provider-${value}`;
|
||||
item.setAttribute("aria-selected", String(value === picker.value)); item.classList.toggle("is-active", index === active);
|
||||
item.addEventListener("mousedown", event => { event.preventDefault(); choose(value); });
|
||||
return item;
|
||||
}));
|
||||
if (!items.length) list.append(el("li", t("certificateDnsProviderNone"), "provider-combo-empty"));
|
||||
}
|
||||
function openList() { active = -1; renderList(""); list.hidden = false; input.setAttribute("aria-expanded", "true"); input.select?.(); }
|
||||
function closeList() { list.hidden = true; input.setAttribute("aria-expanded", "false"); input.value = providerName(lastDns); }
|
||||
function choose(value) { lastDns = value; closeList(); setProvider(value); }
|
||||
input.addEventListener("focus", openList); input.addEventListener("click", () => { if (list.hidden) openList(); });
|
||||
input.addEventListener("input", () => { active = -1; renderList(input.value); list.hidden = false; input.setAttribute("aria-expanded", "true"); });
|
||||
input.addEventListener("blur", () => setTimeout(closeList, 0));
|
||||
input.addEventListener("keydown", event => {
|
||||
const options = [...list.querySelectorAll("[data-value]")];
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); if (list.hidden) openList(); active = options.length ? (active + (event.key === "ArrowDown" ? 1 : options.length - 1) + (active < 0 && event.key === "ArrowUp" ? 1 : 0)) % options.length : -1; options.forEach((node, index) => node.classList.toggle("is-active", index === active)); if (options[active]) input.setAttribute("aria-activedescendant", options[active].id); }
|
||||
else if (event.key === "Enter") { event.preventDefault(); const pick = options[active >= 0 ? active : 0]; if (pick) choose(pick.dataset.value); }
|
||||
else if (event.key === "Escape") { event.preventDefault(); closeList(); }
|
||||
});
|
||||
validation.addEventListener("change", () => setProvider(validation.value === "http01" ? "http01" : lastDns));
|
||||
function sync() {
|
||||
const value = picker.value, mode = value === "import" || value === "existing" ? value : "acme";
|
||||
if (mode === "acme") lastAcme = value;
|
||||
if (dnsProviders().includes(value)) lastDns = value;
|
||||
for (const button of modeButtons) { const on = button.dataset.sourceMode === mode; button.setAttribute("aria-checked", String(on)); button.classList.toggle("is-selected", on); }
|
||||
acmeRow.hidden = mode !== "acme";
|
||||
validation.value = value === "http01" ? "http01" : "dns01";
|
||||
providerField.hidden = mode !== "acme" || value === "http01";
|
||||
if (list.hidden) input.value = providerName(lastDns);
|
||||
}
|
||||
return { sync, translate() { for (const node of box.querySelectorAll("[data-i18n]")) node.textContent = t(node.dataset.i18n); sync(); } };
|
||||
})();
|
||||
$("certificate-new").addEventListener("click", () => open());
|
||||
|
||||
const stateKey = value => ({ running: "certificateStateRunning", ready: "certificateStateReady", complete: "certificateStateComplete", failed: "certificateStateFailed" }[value?.status] || "certificateStateIdle");
|
||||
function renderRuntime(value) {
|
||||
const status = value?.status || "checking", mode = value?.mode || "none";
|
||||
runtimeAvailable = status !== "unavailable";
|
||||
$("acme-runtime-card").dataset.state = status;
|
||||
$("acme-runtime-card").dataset.state = status; syncRuntimeVisibility();
|
||||
$("acme-runtime-message").textContent = t(value?.message || "acme.runtime_checking");
|
||||
$("acme-runtime-state").textContent = t(status === "unavailable" ? "certificateRuntimeUnavailable" : status === "ready" && mode === "managed" ? "certificateRuntimeManaged" : status === "ready" && mode === "system" ? "certificateRuntimeSystem" : "certificateRuntimePreparing");
|
||||
const path = value?.managed_directory;
|
||||
@@ -83,6 +152,7 @@
|
||||
const availability = flag => t(flag === true ? "runtimeAvailable" : flag === false ? "runtimeUnavailable" : "certificateRuntimePreparing");
|
||||
$("acme-runtime-components").textContent = `${t("runtimePython")}: ${availability(value?.python)} · ${t("runtimePip")}: ${availability(value?.pip)} · ${t("runtimeCertbot")}: ${availability(value?.certbot)}`;
|
||||
syncSubmitState();
|
||||
if (typeof renderCertificateSummary === "function" && envelope) renderCertificateSummary(envelope.config.tls?.certificates || []);
|
||||
}
|
||||
function renderOperation(cardId, messageId, stateId, logId, value, idleKey) {
|
||||
const card = $(cardId), message = $(messageId), state = $(stateId), log = $(logId);
|
||||
@@ -121,11 +191,14 @@
|
||||
const state = values[cert.id], enabled = cert.issuer.auto_renew !== false;
|
||||
const entry = el("div", undefined, "renewal-entry"); entry.dataset.state = state?.status || "idle";
|
||||
const head = el("div", undefined, "renewal-entry-head"), identity = el("div", undefined, "renewal-entry-identity");
|
||||
identity.append(el("strong", cert.id), el("span", `${cert.issuer.provider} / ${cert.issuer.environment}`, "fine"));
|
||||
const mode = el("span", t(enabled ? "renewalEnabled" : "renewalDisabled"), "pill"); head.append(identity, mode); entry.append(head);
|
||||
const dot = el("span", undefined, "certificate-state-dot"); dot.dataset.tone = state?.status === "failed" ? "bad" : enabled ? "ok" : "unknown";
|
||||
identity.append(dot, el("strong", cert.id), el("span", `${cert.issuer.provider} / ${cert.issuer.environment}`, "pill"));
|
||||
const mode = el("span", t(enabled ? "renewalEnabled" : "renewalDisabled"), `pill${enabled ? " live" : ""}`); head.append(identity, mode); entry.append(head);
|
||||
const meta = el("div", undefined, "renewal-meta");
|
||||
renewalMeta(meta, "renewalLast", stamp(state?.last_checked));
|
||||
meta.append(el("span", "→", "renewal-meta-arrow"));
|
||||
renewalMeta(meta, "renewalNext", enabled ? stamp(state?.next_check) : "-");
|
||||
meta.append(el("span", "→", "renewal-meta-arrow"));
|
||||
renewalMeta(meta, "renewalExpires", stamp(state?.not_after));
|
||||
entry.append(meta);
|
||||
if (state?.message) {
|
||||
@@ -217,6 +290,6 @@
|
||||
renderRuntime(null); render(null); selectTab("installed", false, false);
|
||||
}
|
||||
};
|
||||
window.rustProxyCertificates = { open, close, select: selectTab, reset() { clearSecrets(); picker.value = "http01"; syncProvider(); selectTab("installed", false, false); } };
|
||||
window.rustProxyCertificates = { open, close, select: selectTab, syncSource: () => sourceUiRef?.sync(), reset() { clearSecrets(); picker.value = "http01"; syncProvider(); selectTab("installed", false, false); } };
|
||||
syncProvider(); selectTab(activeTab, false, false);
|
||||
})();
|
||||
@@ -50,11 +50,6 @@ window.rustProxyChartScale = (() => {
|
||||
}
|
||||
return `${format(n)}${unit === "percent" ? "%" : unit === "ms" ? " ms" : unit === "rate" ? "/s" : ""}`;
|
||||
}
|
||||
// Crosshair (Grafana-style): with value tooltips enabled, a dashed vertical line
|
||||
// snaps to the nearest sample, each series gets a dot, and a tooltip lists
|
||||
// every series' value at that sample; a dashed horizontal line marks the
|
||||
// Y value under the pointer. Values are read back from the drawn lines
|
||||
// with the chart's own axis scale, so they match what is plotted.
|
||||
function lineSeries(svg) {
|
||||
const box = svg.viewBox?.baseVal, height = box?.height || svg.clientHeight || 1;
|
||||
return [...svg.querySelectorAll("polyline, path")].filter(node => !node.classList.contains("chart-grid") && !node.closest(".rp-chart-crosshair")).map(node => {
|
||||
@@ -127,8 +122,6 @@ window.rustProxyChartScale = (() => {
|
||||
const draw = () => {
|
||||
frame = 0; if (!last || !host.isConnected) return;
|
||||
const values = crosshairValues(svg, last); if (!values) { cross.hidden = true; return; }
|
||||
// Client rectangles include the interface-scale transform; the
|
||||
// overlay is positioned in the host's own (unscaled) pixels.
|
||||
const hostBox = host.getBoundingClientRect(), scale = host.offsetWidth ? hostBox.width / host.offsetWidth : 1;
|
||||
const left = (values.box.left - hostBox.left) / scale, top = (values.box.top - hostBox.top) / scale, width = values.box.width / scale, height = values.box.height / scale;
|
||||
const x = left + values.snap * width, y = top + values.fy * height, pointerX = left + values.fx * width;
|
||||
@@ -156,8 +149,6 @@ window.rustProxyChartScale = (() => {
|
||||
function setAxisText(node, value) {
|
||||
if (node.textContent !== value) node.textContent = value;
|
||||
}
|
||||
// The overlay host is needed for X/Y scales and for value tooltips; each
|
||||
// is a separate appearance preference, both off by default.
|
||||
const axesOn = () => document.documentElement.dataset.chartAxes === "true";
|
||||
const tooltipsOn = () => document.documentElement.dataset.chartTooltips === "true";
|
||||
const axesWanted = () => axesOn() || tooltipsOn();
|
||||
|
||||
@@ -32,12 +32,9 @@ function activePack() { return languagePacks.get(language) || languagePacks.get(
|
||||
let canonicalLocale = { source: null, value: "und" };
|
||||
function locale() {
|
||||
const source = activePack()?.meta.locale || "und";
|
||||
if (canonicalLocale.source !== source) { let value = "und"; try { value = Intl.getCanonicalLocales(source)[0]; } catch { /* invalid tag */ } canonicalLocale = { source, value }; }
|
||||
if (canonicalLocale.source !== source) { let value = "und"; try { value = Intl.getCanonicalLocales(source)[0]; } catch { } canonicalLocale = { source, value }; }
|
||||
return canonicalLocale.value;
|
||||
}
|
||||
// Live views format hundreds of numbers and times per update; constructing a
|
||||
// new Intl formatter for each value (toLocaleString with options) dominated
|
||||
// that work. Formatters are cached per language and options.
|
||||
const intlFormatters = new Map();
|
||||
function intlFormatter(kind, key, create) {
|
||||
const cacheKey = `${locale()}|${kind}|${key}`;
|
||||
@@ -49,9 +46,6 @@ function formatNumber(value, maximumFractionDigits = 0) { return intlFormatter("
|
||||
function formatDateParts(date, withDate, hour12) {
|
||||
return intlFormatter(withDate ? "datetime" : "time", hour12, lang => new Intl.DateTimeFormat(lang, withDate ? { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12 } : { hour: "numeric", minute: "numeric", second: "numeric", hour12 })).format(date);
|
||||
}
|
||||
// Sorting calls a comparator O(n log n) times; String#localeCompare with a
|
||||
// locale/options argument builds a new collator on every call, which made
|
||||
// periodic table re-renders slow. Collators are cached per language.
|
||||
const textCollators = new Map();
|
||||
function textCollator(numeric = true) {
|
||||
const key = `${activePack()?.meta.locale || "und"}|${numeric}`;
|
||||
|
||||
@@ -164,6 +164,7 @@ function uiIconForTarget(target) {
|
||||
if (target.matches(".chart-style-choice")) return null;
|
||||
if (target.matches(".overview-inline-grip, .overview-inline-narrow, .overview-inline-widen, .overview-inline-up, .overview-inline-down, .overview-inline-hide, .overview-layout-narrow, .overview-layout-widen, .overview-layout-up, .overview-layout-down, .overview-layout-hide")) return null;
|
||||
if (target.matches("#tunnels-open, .vhost-backend-protocol-badge, .config-history-day, .draft-dock-toggle, .mobile-menu-toggle, .sidebar-collapse")) return null;
|
||||
if (target.matches(".page-editor-summary, .settings-flow-step, .security-summary-tile, .settings-flow-example-tabs button")) return null;
|
||||
if (UI_GLYPH_LABEL.test(String(target.textContent || "").trim())) return null;
|
||||
if (UI_ID_ICONS[target.id]) return UI_ID_ICONS[target.id];
|
||||
if (target.matches("#web-service-preset-apply, [data-cache-memory-preset], [data-cache-cold-preset], [data-transform-preset]")) return "wand";
|
||||
@@ -303,8 +304,6 @@ const uiIconObserver = new MutationObserver(records => {
|
||||
});
|
||||
window.rustProxyIcons = { refresh: refreshUiIcons, setEnabled: setUiIconsEnabled, iconFor: uiIconForTarget };
|
||||
|
||||
// Shared information popovers (<details class="metric-info">): one is open at a time, Escape or
|
||||
// a click elsewhere closes it, and its bubble is kept inside the visible (clipping) area.
|
||||
(() => {
|
||||
const MARGIN = 8;
|
||||
const visibleArea = node => {
|
||||
|
||||
@@ -158,8 +158,6 @@ window.rustProxyExtraOverview = (() => {
|
||||
value: (deltas[0] + deltas[1]) / seconds, unit, detail: `${t("overviewExtraRejectedDetail")}: ${fmt(fields[0])} / ${fmt(fields[1])}`
|
||||
};
|
||||
if (unit === "rate") return { value: deltas[0] / seconds, unit, detail: "" };
|
||||
// Percentages use the sum of mutually exclusive categories, sampled
|
||||
// at the same lifecycle stage. No false 0% or clamped 100% on skew.
|
||||
const sum = deltas.reduce((total, value) => total + value, 0);
|
||||
return {
|
||||
value: sum > 0 ? deltas[0] / sum * 100 : null, unit,
|
||||
|
||||
@@ -51,9 +51,6 @@ window.rustProxyOverviewRows = (() => {
|
||||
if (needed > spanOf(card)) setSpan(node, needed, columns);
|
||||
}
|
||||
}
|
||||
// Measuring forces a layout of the whole document. While Overview is
|
||||
// hidden there is nothing to measure; remember it and re-run once the
|
||||
// grid is shown again (the ResizeObserver below fires on that change).
|
||||
let hiddenPending = false;
|
||||
function apply() {
|
||||
frame = 0;
|
||||
|
||||
@@ -316,7 +316,6 @@ for (const [id, direction] of [["dashboard-widget-scroll-prev", -1], ["dashboard
|
||||
}
|
||||
function refreshChartStylePalette(active = adminPreferences?.chart_style || "default") {
|
||||
const target = $("chart-style-palette"); if (!target || !languagePacks.size) return;
|
||||
// Keep the selected swatch button mounted; replacing it on click loses focus.
|
||||
for (const style of ADMIN_CHART_STYLES) {
|
||||
let button = [...target.children].find(node => node.dataset.chartPreset === style);
|
||||
if (!button) {
|
||||
@@ -351,9 +350,6 @@ function applyAdminPreferences(value, cache = true) {
|
||||
const savedHeights = normalizeDashboardWidgetHeights(value.dashboard_widget_heights);
|
||||
const savedAutoFit = value.dashboard_auto_fit !== false;
|
||||
const savedPositions = normalizeDashboardWidgetPositions(value.dashboard_widget_positions);
|
||||
// A saved table column (or any unrelated preference) must not re-apply the
|
||||
// dashboard layout. Moving its cards detaches focused controls and shifts
|
||||
// the page, even if the selected dashboard layout has not changed.
|
||||
const layoutChanged = !adminPreferences || JSON.stringify([
|
||||
adminPreferences.dashboard_widgets, adminPreferences.dashboard_hidden_widgets,
|
||||
adminPreferences.dashboard_widget_sizes, adminPreferences.dashboard_widget_heights,
|
||||
@@ -393,7 +389,6 @@ function applyAdminPreferences(value, cache = true) {
|
||||
if (redirectChanged) window.rustProxyRedirects?.applyPreferences(normalized);
|
||||
if (notfoundChanged) window.rustProxyNotFound?.applyPreferences(normalized);
|
||||
if (streamChanged) window.rustProxyStreams?.applyPreferences(normalized);
|
||||
// Only a real language change requires translating/re-rendering the whole panel.
|
||||
if (languagePacks.size && languageChanged) translate();
|
||||
else refreshAppearanceUi({ palette: paletteChanged, widgets: widgetSettingsChanged,
|
||||
refresh: refreshChanged, presets: layoutChanged, search: false });
|
||||
|
||||
+244
-69
@@ -63,90 +63,187 @@ for (const id of ["certificate-file", "certificate-key"]) {
|
||||
$(id).addEventListener("input", syncCertificatePermissions);
|
||||
$(id).addEventListener("change", syncCertificatePermissions);
|
||||
}
|
||||
function certificateUsage(cert) {
|
||||
const config = envelope?.config || {}, settings = config.tls || {};
|
||||
const hostsOf = item => item?.frontend?.hosts || [];
|
||||
const groups = {
|
||||
vhosts: (config.vhosts || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), mismatch: item.allow_certificate_mismatch === true, open: () => { setPanel("vhosts"); window.rustProxyVhosts?.edit(item.id); } })),
|
||||
redirects: (config.redirects || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), open: () => { setPanel("redirects"); window.rustProxyRedirects?.edit(item.id); } })),
|
||||
notfound: (config.not_found_hosts || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), open: () => { setPanel("notfound"); window.rustProxyNotFound?.edit(item.id); } })),
|
||||
docker: (config.docker_agents?.agents || []).filter(agent => [agent.certificate_id, ...(agent.certificate_ids || [])].includes(cert.id)).map(agent => ({ id: agent.id, hosts: agent.domains || [], open: () => setPanel("settings") }))
|
||||
};
|
||||
const legacy = [];
|
||||
for (const item of config.vhosts || []) if (item.certificate_id === cert.id) legacy.push(`vhost:${item.id}`);
|
||||
for (const item of config.redirects || []) if (item.certificate_id === cert.id) legacy.push(`redirect:${item.id}`);
|
||||
for (const item of config.not_found_hosts || []) if (item.certificate_id === cert.id) legacy.push(`404:${item.id}`);
|
||||
const admin = config.administration?.certificate_id === cert.id, isDefault = settings.default_certificate === cert.id;
|
||||
if (admin) legacy.push(t("administration"));
|
||||
if (isDefault) legacy.push(t("defaultLabel"));
|
||||
const count = groups.vhosts.length + groups.redirects.length + groups.notfound.length + (admin ? 1 : 0) + (isDefault ? 1 : 0);
|
||||
return { groups, admin, isDefault, legacy, count, inUse: legacy.length > 0 };
|
||||
}
|
||||
function certificateCoverage(cert) {
|
||||
const inventory = certificateInventory.get(cert.id);
|
||||
return inventory?.covered_hosts?.length ? inventory.covered_hosts : (cert.covered_hosts || []);
|
||||
}
|
||||
function certificateCovers(coverage, host) { return coverage.some(pattern => window.rustProxyAutoCertificate.covers(pattern, host)); }
|
||||
function certificateCoverageState(coverage, hosts) {
|
||||
if (!hosts.length || !coverage.length) return { state: "unknown", missing: [] };
|
||||
const missing = hosts.filter(host => !certificateCovers(coverage, host));
|
||||
return { state: missing.length === 0 ? "full" : missing.length === hosts.length ? "none" : "partial", missing };
|
||||
}
|
||||
let certificateFilter = "all";
|
||||
const certificateOpenRows = new Set();
|
||||
function certificateTimeline(inventory) {
|
||||
const days = inventory?.days_remaining, to = Number(inventory?.not_after_unix);
|
||||
const box = el("div", undefined, "certificate-validity");
|
||||
const tone = inventory?.expiry_status === "expired" ? "bad" : inventory?.expiry_status === "warning" ? "warn" : "ok";
|
||||
box.dataset.tone = days == null ? "unknown" : tone;
|
||||
const text = days == null ? t("certificateValidityUnknown") : `${t("certificateDaysLeft").replace("{days}", days)} · ${t("certificateUntil")} ${formatDate(to * 1000)}`;
|
||||
const bar = el("span", undefined, "certificate-validity-bar"), fill = el("i");
|
||||
const ratio = days == null ? 0 : Math.max(0, Math.min(1, Number(days) / 90));
|
||||
fill.style.width = `${Math.round(ratio * 100)}%`; bar.append(fill);
|
||||
box.append(el("span", text, "certificate-validity-text"), bar);
|
||||
return box;
|
||||
}
|
||||
function formatDate(ms) { try { return new Date(ms).toLocaleDateString(typeof language !== "undefined" ? language.replace("_", "-") : undefined); } catch { return new Date(ms).toISOString().slice(0, 10); } }
|
||||
function renderCertificateSummary(certificates) {
|
||||
const box = $("certificate-summary"); if (!box) return;
|
||||
const settings = envelope?.config.tls || {};
|
||||
let acme = 0, external = 0, managedFiles = 0, expiring = [], assignments = 0, vhostCount = 0, redirectCount = 0, notfoundCount = 0;
|
||||
for (const cert of certificates) {
|
||||
if (cert.issuer) acme++; else if (certificateUsesExternalFiles(cert)) external++; else managedFiles++;
|
||||
const inventory = certificateInventory.get(cert.id);
|
||||
if (["warning", "expired"].includes(inventory?.expiry_status)) expiring.push(`${cert.id} · ${inventory?.days_remaining ?? "-"} ${t("certificateDaysShort")}`);
|
||||
const usage = certificateUsage(cert); assignments += usage.count; vhostCount += usage.groups.vhosts.length; redirectCount += usage.groups.redirects.length; notfoundCount += usage.groups.notfound.length;
|
||||
}
|
||||
const tile = (value, titleKey, line, tone, filter) => {
|
||||
const node = el(filter ? "button" : "div", undefined, `cert-summary-tile${tone ? ` is-${tone}` : ""}`);
|
||||
if (filter) { node.type = "button"; node.dataset.uiIconName = "none"; node.addEventListener("click", () => { window.rustProxyAcme?.select("installed"); setCertificateFilter(filter); }); }
|
||||
const title = el("span", t(titleKey)); title.dataset.i18n = titleKey;
|
||||
node.append(el("b", value), title, el("small", line)); return node;
|
||||
};
|
||||
const runtime = $("acme-runtime-state")?.textContent || "";
|
||||
box.replaceChildren(
|
||||
tile(String(certificates.length), "certificateSummaryCount", `${acme} ACME · ${external} ${t("certificateSummaryExternal")} · ${managedFiles} ${t("certificateSummaryManaged")}`, certificates.length ? "ok" : "", "all"),
|
||||
tile(String(expiring.length), "certificateSummaryExpiring", expiring.length ? expiring.slice(0, 2).join(", ") : t("certificateSummaryNothingExpiring"), expiring.length ? "warn" : "ok", "expiring"),
|
||||
tile(String(assignments), "certificateSummaryAssignments", `${vhostCount} vhost · ${redirectCount} ${t("certificateSummaryRedirects")} · ${notfoundCount} 404${settings.default_certificate ? ` · ${t("defaultLabel")}: ${settings.default_certificate}` : ""}`, "", "unassigned"),
|
||||
tile(runtime || "-", "certificateSummaryRuntime", $("acme-runtime-components")?.textContent || "", $("acme-runtime-card")?.dataset.state === "ready" ? "ok" : $("acme-runtime-card")?.dataset.state === "unavailable" ? "bad" : "")
|
||||
);
|
||||
}
|
||||
function setCertificateFilter(value) {
|
||||
certificateFilter = value;
|
||||
for (const button of document.querySelectorAll("[data-certificate-filter]")) button.setAttribute("aria-pressed", String(button.dataset.certificateFilter === value));
|
||||
applyCertificateFilter();
|
||||
}
|
||||
function applyCertificateFilter() {
|
||||
const query = ($("certificate-search")?.value || "").trim().toLowerCase();
|
||||
let shown = 0;
|
||||
for (const row of document.querySelectorAll("#certificate-list > .certificate-row")) {
|
||||
const matchesQuery = !query || row.dataset.search.includes(query);
|
||||
const matchesFilter = certificateFilter === "all" || (certificateFilter === "expiring" && row.dataset.expiring === "true") || (certificateFilter === "unassigned" && row.dataset.assigned === "false");
|
||||
row.hidden = !(matchesQuery && matchesFilter); if (!row.hidden) shown++;
|
||||
}
|
||||
const empty = $("certificate-list-filtered-empty");
|
||||
if (empty) empty.hidden = shown > 0 || !document.querySelector("#certificate-list > .certificate-row");
|
||||
}
|
||||
function renderCertificates() {
|
||||
if (!envelope) return;
|
||||
const settings = envelope.config.tls || {};
|
||||
const entries = (settings.certificates || []).map(cert => {
|
||||
const certificates = settings.certificates || [];
|
||||
const entries = certificates.map(cert => {
|
||||
const inventory = certificateInventory.get(cert.id);
|
||||
const coverage = (inventory?.covered_hosts?.length ? inventory.covered_hosts : (cert.covered_hosts || []));
|
||||
const coverage = certificateCoverage(cert);
|
||||
const bindings = cert.hosts || [];
|
||||
const used = [];
|
||||
for (const vhost of envelope.config.vhosts || []) if (vhost.certificate_id === cert.id) used.push(`vhost:${vhost.id}`);
|
||||
for (const redirect of envelope.config.redirects || []) if (redirect.certificate_id === cert.id) used.push(`redirect:${redirect.id}`);
|
||||
for (const host of envelope.config.not_found_hosts || []) if (host.certificate_id === cert.id) used.push(`404:${host.id}`);
|
||||
if (envelope.config.administration?.certificate_id === cert.id) used.push(t("administration"));
|
||||
if (settings.default_certificate === cert.id) used.push(t("defaultLabel"));
|
||||
const managed = !!cert.issuer, inUse = used.length > 0;
|
||||
const box = el("div", undefined, "entity certificate-card");
|
||||
const head = el("div", undefined, "certificate-card-head");
|
||||
const usage = certificateUsage(cert), used = usage.legacy;
|
||||
const managed = !!cert.issuer, inUse = usage.inUse;
|
||||
const box = el("details", undefined, "entity certificate-card certificate-row");
|
||||
box.dataset.certificateId = cert.id;
|
||||
box.dataset.expiring = String(["warning", "expired"].includes(inventory?.expiry_status));
|
||||
box.dataset.assigned = String(usage.count > 0);
|
||||
box.dataset.search = [cert.id, ...coverage, ...bindings, ...usage.groups.vhosts.map(item => item.id), ...usage.groups.redirects.map(item => item.id), ...usage.groups.notfound.map(item => item.id)].join(" ").toLowerCase();
|
||||
box.open = certificateOpenRows.has(cert.id);
|
||||
box.addEventListener("toggle", () => { if (box.open) certificateOpenRows.add(cert.id); else certificateOpenRows.delete(cert.id); });
|
||||
const summary = el("summary", undefined, "certificate-row-summary");
|
||||
const dot = el("span", undefined, "certificate-state-dot"); dot.dataset.tone = inventory?.expiry_status === "expired" ? "bad" : inventory?.expiry_status === "warning" ? "warn" : inventory ? "ok" : "unknown";
|
||||
const identity = el("div", undefined, "certificate-card-identity");
|
||||
identity.append(el("span", cert.id, "entity-title"));
|
||||
const statePills = el("div", undefined, "vhost-policy-pills certificate-state-pills");
|
||||
if (managed) statePills.append(el("small", `${t("certificateManaged")} · ${cert.issuer.provider} / ${cert.issuer.environment}`, "pill"));
|
||||
if (managed) statePills.append(el("small", `${t("certificateManaged")} · ${cert.issuer.provider} / ${cert.issuer.environment}`, "pill live"));
|
||||
else if (certificateUsesExternalFiles(cert)) statePills.append(el("small", t("certificateExternalFiles"), "pill"));
|
||||
if (settings.default_certificate === cert.id) statePills.append(el("small", t("defaultLabel"), "pill"));
|
||||
else statePills.append(el("small", t("certificateManagedFiles"), "pill"));
|
||||
if (settings.default_certificate === cert.id) statePills.append(el("small", t("defaultLabel"), "pill live"));
|
||||
if (inventory?.expiry_status === "expired") statePills.append(el("small", t("certificateExpired"), "pill status-error"));
|
||||
else if (inventory?.expiry_status === "warning") statePills.append(el("small", t("certificateExpiresSoon"), "pill status-error"));
|
||||
if (statePills.children.length) identity.append(statePills);
|
||||
head.append(identity);
|
||||
box.append(head);
|
||||
|
||||
identity.append(statePills);
|
||||
const coverageBlock = el("div", undefined, "certificate-coverage");
|
||||
coverageBlock.append(el("span", t("certificateCovers"), "small-label"));
|
||||
const domainPills = el("div", undefined, "vhost-policy-pills certificate-domain-pills");
|
||||
if (coverage.length) {
|
||||
for (const host of coverage) domainPills.append(el("small", host, "pill"));
|
||||
} else {
|
||||
domainPills.append(el("small", t("certificateCoverageUnknown"), "certificate-coverage-unknown"));
|
||||
}
|
||||
for (const host of coverage.slice(0, 3)) domainPills.append(el("small", host, "pill"));
|
||||
if (coverage.length > 3) domainPills.append(el("small", `+${coverage.length - 3}`, "pill"));
|
||||
} else domainPills.append(el("small", t("certificateCoverageUnknown"), "certificate-coverage-unknown"));
|
||||
coverageBlock.append(domainPills);
|
||||
box.append(coverageBlock);
|
||||
const usageCell = el("div", undefined, "certificate-usage-cell");
|
||||
const usageParts = [];
|
||||
if (usage.groups.vhosts.length) usageParts.push(`${usage.groups.vhosts.length} vhost`);
|
||||
if (usage.groups.redirects.length) usageParts.push(`${usage.groups.redirects.length} ${t("certificateSummaryRedirects")}`);
|
||||
if (usage.groups.notfound.length) usageParts.push(`${usage.groups.notfound.length} 404`);
|
||||
if (usage.admin) usageParts.push(t("administration"));
|
||||
if (usage.isDefault) usageParts.push(t("defaultLabel"));
|
||||
usageCell.append(el("b", String(usage.count)), el("span", usageParts.join(" · ") || t("certUnassigned"), "fine"));
|
||||
summary.append(dot, identity, coverageBlock, certificateTimeline(inventory), usageCell, el("span", "", "certificate-row-chevron"));
|
||||
box.append(summary);
|
||||
|
||||
const details = el("details", undefined, "certificate-details");
|
||||
details.append(el("summary", t("certificateDetails")));
|
||||
const detailBody = el("div", undefined, "certificate-details-body");
|
||||
const stamp = value => Number(value) ? formatDateTime(Number(value) * 1000) : "-";
|
||||
detailBody.append(
|
||||
el("p", `${t("certificateBindings")}: ${bindings.join(", ") || "-"}`, "entity-details"),
|
||||
el("p", `${t("certificateFiles")}: ${cert.cert_file} / ${cert.key_file}`, "entity-details"),
|
||||
el("p", `${t("certAssigned")}: ${used.join(", ") || t("certUnassigned")}`, "entity-details"),
|
||||
el("p", `${t("certificateIssuerName")}: ${inventory?.certificate_issuer || "-"}`, "entity-details"),
|
||||
el("p", `${t("certificateValidFrom")}: ${stamp(inventory?.not_before_unix)}`, "entity-details"),
|
||||
el("p", `${t("renewalExpires")}: ${stamp(inventory?.not_after_unix)}`, "entity-details"),
|
||||
el("p", `${t("certificateDaysRemaining")}: ${inventory?.days_remaining ?? "-"}`, "entity-details"),
|
||||
el("p", `${t("certificateRenewalStatus")}: ${inventory?.renewal_status || "-"}`, "entity-details"),
|
||||
el("p", `${t("renewalLast")}: ${stamp(inventory?.last_renewal_attempt)}`, "entity-details"),
|
||||
el("p", `${t("certificateRenewalError")}: ${inventory?.last_renewal_error ? t(inventory.last_renewal_error) : "-"}`, "entity-details"),
|
||||
);
|
||||
details.append(detailBody);
|
||||
box.append(details);
|
||||
|
||||
const buttons = el("div", undefined, "entity-actions");
|
||||
const assignPane = el("div", undefined, "certificate-bulk-assign");
|
||||
assignPane.hidden = true;
|
||||
const assignmentList = el("div", undefined, "certificate-bulk-list");
|
||||
for (const host of envelope.config.vhosts || []) {
|
||||
const label = el("label", undefined, "check");
|
||||
const check = document.createElement("input");
|
||||
check.type = "checkbox"; check.value = host.id;
|
||||
check.checked = host.certificate_id === cert.id;
|
||||
label.append(check, el("span", `${host.id} · ${(host.frontend?.hosts || []).join(", ")}`));
|
||||
assignmentList.append(label);
|
||||
}
|
||||
const applyBindings = action(t("certAssignApply"), async () => {
|
||||
if (busy) return;
|
||||
const selected = new Set([...assignmentList.querySelectorAll('input:checked')].map(input => input.value));
|
||||
const next = structuredClone(envelope.config);
|
||||
for (const host of next.vhosts) {
|
||||
if (selected.has(host.id)) host.certificate_id = cert.id;
|
||||
else if (host.certificate_id === cert.id) host.certificate_id = null;
|
||||
const body = el("div", undefined, "certificate-row-body");
|
||||
const usageSection = el("section", undefined, "certificate-section certificate-usage");
|
||||
const usageHead = el("h4"); usageHead.append(el("span", t("certificateWhereUsed")), el("span", String(usage.count), "pill"));
|
||||
usageSection.append(usageHead);
|
||||
const groupDefs = [["vhosts", "certificateGroupVhosts"], ["redirects", "certificateGroupRedirects"], ["notfound", "certificateGroupNotFound"], ["docker", "certificateGroupDocker"]];
|
||||
let anyUsage = false;
|
||||
for (const [key, labelKey] of groupDefs) {
|
||||
const items = usage.groups[key]; if (!items.length) continue; anyUsage = true;
|
||||
const group = el("div", undefined, "certificate-usage-group");
|
||||
group.append(el("span", `${t(labelKey)} · ${items.length}`, "small-label"));
|
||||
for (const item of items) {
|
||||
const row = el("div", undefined, "certificate-usage-row");
|
||||
const cover = certificateCoverageState(coverage, item.hosts);
|
||||
const pillText = cover.state === "full" ? t("certificateCovered") : cover.state === "unknown" ? t("certificateCoverageUnknownShort") : `${t("certificateNotCovered")}: ${cover.missing.join(", ")}${item.mismatch ? ` · ${t("certificateMismatchAccepted")}` : ""}`;
|
||||
const open = el("button", t("certificateOpen"), "quiet certificate-usage-open"); open.type = "button"; open.dataset.uiIconName = "none"; open.addEventListener("click", item.open);
|
||||
row.append(el("span", item.id, "mono"), el("span", item.hosts.join(", ") || "-", "fine"), el("span", pillText, `pill${cover.state === "full" ? " live" : cover.state === "unknown" ? "" : " warn"}`), open);
|
||||
group.append(row);
|
||||
}
|
||||
await saveSection("vhosts", next.vhosts);
|
||||
});
|
||||
assignPane.append(el("p", t("certAssignHelp"), "fine"), assignmentList, applyBindings);
|
||||
const assignButton = action(t("certAssignVhosts"), () => {
|
||||
assignPane.hidden = !assignPane.hidden;
|
||||
});
|
||||
usageSection.append(group);
|
||||
}
|
||||
const extra = [];
|
||||
if (usage.admin) extra.push(t("administration"));
|
||||
if (usage.isDefault) extra.push(t("certificateDefaultSni"));
|
||||
if (extra.length) { anyUsage = true; usageSection.append(el("p", `${t("certificateAlsoUsedBy")}: ${extra.join(", ")}`, "fine")); }
|
||||
if (!anyUsage) usageSection.append(el("p", t("certUnassigned"), "fine"));
|
||||
usageSection.append(el("p", t("certificateUsageHelp"), "fine certificate-usage-help"));
|
||||
|
||||
const side = el("div", undefined, "certificate-row-side");
|
||||
const stamp = value => Number(value) ? formatDateTime(Number(value) * 1000) : "-";
|
||||
const kv = (rows) => { const list = el("dl", undefined, "certificate-kv"); for (const [key, value] of rows) list.append(el("dt", t(key)), el("dd", value)); return list; };
|
||||
const details = el("section", undefined, "certificate-section certificate-details");
|
||||
details.append(el("h4", t("certificateDetails")), kv([
|
||||
["certificateIssuerName", inventory?.certificate_issuer || "-"],
|
||||
["certificateValidFrom", stamp(inventory?.not_before_unix)],
|
||||
["renewalExpires", stamp(inventory?.not_after_unix)],
|
||||
["certificateDaysRemaining", String(inventory?.days_remaining ?? "-")],
|
||||
["certificateBindings", bindings.join(", ") || "-"],
|
||||
["certAssigned", used.join(", ") || t("certUnassigned")]
|
||||
]));
|
||||
const renewal = el("section", undefined, "certificate-section certificate-renewal-summary");
|
||||
renewal.append(el("h4", t("certificateRenewalStatus")), kv([
|
||||
["certificateRenewalStatus", inventory?.renewal_status || "-"],
|
||||
["renewalLast", stamp(inventory?.last_renewal_attempt)],
|
||||
["certificateRenewalError", inventory?.last_renewal_error ? t(inventory.last_renewal_error) : "-"]
|
||||
]));
|
||||
if (managed) { const link = el("button", t("certificateRenewalActionsLink"), "quiet"); link.type = "button"; link.dataset.uiIconName = "none"; link.addEventListener("click", () => window.rustProxyAcme?.select("renewal")); renewal.append(link); }
|
||||
const files = el("section", undefined, "certificate-section certificate-files");
|
||||
files.append(el("h4", t("certificateFiles")), el("p", `${cert.cert_file}\n${cert.key_file}`, "mono certificate-file-paths"));
|
||||
const buttons = el("div", undefined, "entity-actions");
|
||||
const assignButton = action(t("certAssignVhosts"), () => openCertificateAssign(cert));
|
||||
assignButton.disabled = !(envelope.config.vhosts || []).length;
|
||||
buttons.append(assignButton);
|
||||
if (!managed) {
|
||||
@@ -173,13 +270,91 @@ function renderCertificates() {
|
||||
}
|
||||
const remove = action(t("remove"), async () => { if (inUse) { toast(t("certInUse"), true); return; } if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return; const next = structuredClone(envelope.config); next.tls.certificates = next.tls.certificates.filter(v => v.id !== cert.id); await saveSection("tls", next.tls); });
|
||||
remove.disabled = inUse; remove.title = inUse ? t("certInUse") : ""; buttons.append(remove);
|
||||
box.append(buttons, assignPane);
|
||||
side.append(details, renewal, files, buttons);
|
||||
body.append(usageSection, side);
|
||||
box.append(body);
|
||||
return box;
|
||||
});
|
||||
$("certificate-list").replaceChildren(...entries);
|
||||
const filteredEmpty = el("p", t("certificateFilterEmpty"), "empty"); filteredEmpty.id = "certificate-list-filtered-empty"; filteredEmpty.hidden = true;
|
||||
$("certificate-list").replaceChildren(...entries, filteredEmpty);
|
||||
if (!entries.length) $("certificate-list").append(el("p", t("emptyCertificates"), "empty"));
|
||||
renderCertificateSummary(certificates);
|
||||
applyCertificateFilter();
|
||||
window.rustProxyCertificates?.syncSource?.();
|
||||
syncCertificatePermissions();
|
||||
}
|
||||
let certificateAssignState = null;
|
||||
function openCertificateAssign(cert) {
|
||||
const dialog = $("certificate-assign-dialog"); if (!dialog || !envelope) return;
|
||||
const coverage = certificateCoverage(cert);
|
||||
const rows = (envelope.config.vhosts || []).map(host => {
|
||||
const hosts = host.frontend?.hosts || [], cover = certificateCoverageState(coverage, hosts);
|
||||
const selectable = cover.state === "full" || cover.state === "unknown" || host.allow_certificate_mismatch === true || host.certificate_id === cert.id;
|
||||
return { host, hosts, cover, selectable, initial: host.certificate_id === cert.id, checked: host.certificate_id === cert.id };
|
||||
});
|
||||
certificateAssignState = { cert, rows, filter: "matching", query: "" };
|
||||
$("certificate-assign-title").textContent = `${t("certAssignVhosts")} · ${cert.id}`;
|
||||
$("certificate-assign-domains").replaceChildren(...coverage.slice(0, 4).map(host => el("span", host, "pill")), ...(coverage.length > 4 ? [el("span", `+${coverage.length - 4}`, "pill")] : []));
|
||||
$("certificate-assign-search").value = "";
|
||||
renderCertificateAssign();
|
||||
if (!dialog.open) dialog.showModal();
|
||||
}
|
||||
function renderCertificateAssign() {
|
||||
const state = certificateAssignState; if (!state) return;
|
||||
const counts = { matching: state.rows.filter(row => row.cover.state === "full").length, assigned: state.rows.filter(row => row.checked).length, all: state.rows.length };
|
||||
const filters = $("certificate-assign-filters");
|
||||
filters.replaceChildren(...[["matching", "certificateAssignMatching"], ["assigned", "certificateAssignAssigned"], ["all", "certificateFilterAll"]].map(([key, labelKey]) => {
|
||||
const button = el("button", `${t(labelKey)} · ${counts[key]}`); button.type = "button"; button.dataset.uiIconName = "none";
|
||||
button.setAttribute("aria-pressed", String(state.filter === key));
|
||||
button.addEventListener("click", () => { state.filter = key; renderCertificateAssign(); });
|
||||
return button;
|
||||
}));
|
||||
const query = state.query.toLowerCase(), list = $("certificate-assign-list");
|
||||
const head = el("div", undefined, "certificate-assign-row certificate-assign-head");
|
||||
for (const key of ["", "certificateAssignColVhost", "certificateAssignColHosts", "certificateAssignColCoverage", "certificateAssignColNow"]) head.append(el("span", key ? t(key) : ""));
|
||||
const visible = state.rows.filter(row => (state.filter === "all" || (state.filter === "matching" && row.cover.state === "full") || (state.filter === "assigned" && row.checked))
|
||||
&& (!query || `${row.host.id} ${row.hosts.join(" ")}`.toLowerCase().includes(query)));
|
||||
const items = visible.map(row => {
|
||||
const line = el("label", undefined, "certificate-assign-row");
|
||||
const check = document.createElement("input"); check.type = "checkbox"; check.checked = row.checked; check.disabled = !row.selectable && !row.checked;
|
||||
check.addEventListener("change", () => { row.checked = check.checked; renderCertificateAssign(); });
|
||||
const coverText = row.cover.state === "full" ? t("certificateCoveredAll") : row.cover.state === "unknown" ? t("certificateCoverageUnknownShort") : row.cover.state === "none" ? t("certificateCoverageNone") : `${t("certificateCoveragePartial").replace("{covered}", row.hosts.length - row.cover.missing.length).replace("{total}", row.hosts.length)}`;
|
||||
const coverExtra = row.cover.state !== "full" && row.cover.state !== "unknown" ? (row.host.allow_certificate_mismatch ? ` · ${t("certificateMismatchAccepted")}` : ` · ${t("certificateMismatchRequired")}`) : "";
|
||||
const now = el("span", undefined, "certificate-assign-now");
|
||||
if (row.checked !== row.initial) now.append(el("span", t(row.checked ? "certificateAssignAdd" : "certificateAssignRemove"), `pill ${row.checked ? "warn" : "status-error"}`), " ");
|
||||
now.append(el("span", row.host.certificate_id ? (row.host.certificate_id === state.cert.id ? t("certificateAssignThis") : row.host.certificate_id) : t("certificateAssignDefault"), "fine"));
|
||||
line.classList.toggle("is-changed", row.checked !== row.initial);
|
||||
line.classList.toggle("is-disabled", check.disabled);
|
||||
line.append(check, el("b", row.host.id, "mono"), el("span", row.hosts.join(", ") || "-", "fine"), el("span", coverText + coverExtra, `pill${row.cover.state === "full" ? " live" : row.cover.state === "unknown" ? "" : " warn"}`), now);
|
||||
return line;
|
||||
});
|
||||
list.replaceChildren(head, ...(items.length ? items : [el("p", t("certificateFilterEmpty"), "empty")]));
|
||||
const added = state.rows.filter(row => row.checked && !row.initial).length, removed = state.rows.filter(row => !row.checked && row.initial).length;
|
||||
const changes = $("certificate-assign-changes"); changes.replaceChildren();
|
||||
if (added || removed) {
|
||||
changes.append(el("b", `${t("certificateAssignChanges")}: `));
|
||||
if (added) changes.append(el("span", `+${added} ${t("certificateAssignAdded")}`, "pill live"), " ");
|
||||
if (removed) changes.append(el("span", `−${removed} ${t("certificateAssignRemoved")}`, "pill status-error"));
|
||||
} else changes.append(el("span", t("certificateAssignNoChanges"), "fine"));
|
||||
$("certificate-assign-apply").disabled = !(added || removed);
|
||||
}
|
||||
$("certificate-assign-search")?.addEventListener("input", event => { if (certificateAssignState) { certificateAssignState.query = event.target.value; renderCertificateAssign(); } });
|
||||
$("certificate-assign-all")?.addEventListener("click", () => { if (!certificateAssignState) return; for (const row of certificateAssignState.rows) if (row.cover.state === "full") row.checked = true; renderCertificateAssign(); });
|
||||
$("certificate-assign-none")?.addEventListener("click", () => { if (!certificateAssignState) return; for (const row of certificateAssignState.rows) row.checked = false; renderCertificateAssign(); });
|
||||
for (const id of ["certificate-assign-close", "certificate-assign-cancel"]) $(id)?.addEventListener("click", () => { $("certificate-assign-dialog").close(); });
|
||||
$("certificate-assign-dialog")?.addEventListener("close", () => { certificateAssignState = null; });
|
||||
$("certificate-assign-apply")?.addEventListener("click", async () => {
|
||||
const state = certificateAssignState; if (!state || busy || !envelope) return;
|
||||
const selected = new Set(state.rows.filter(row => row.checked).map(row => row.host.id));
|
||||
const next = structuredClone(envelope.config);
|
||||
for (const host of next.vhosts) {
|
||||
if (selected.has(host.id)) host.certificate_id = state.cert.id;
|
||||
else if (host.certificate_id === state.cert.id) host.certificate_id = null;
|
||||
}
|
||||
if (await saveSection("vhosts", next.vhosts)) $("certificate-assign-dialog").close();
|
||||
});
|
||||
$("certificate-search")?.addEventListener("input", applyCertificateFilter);
|
||||
for (const button of document.querySelectorAll("[data-certificate-filter]")) button.addEventListener("click", () => setCertificateFilter(button.dataset.certificateFilter));
|
||||
$("certificate-form").addEventListener("submit", async event => {
|
||||
event.preventDefault(); const form = event.currentTarget;
|
||||
if (!envelope || busy) return;
|
||||
|
||||
@@ -263,8 +263,6 @@
|
||||
try {
|
||||
data = await api(`/api/cache?${query}`, { signal });
|
||||
} catch (error) {
|
||||
// A label-only Docker publication can disappear from the
|
||||
// effective catalog. Recover from its now-invalid scope.
|
||||
if (error?.status !== 404 || scope() === "*") throw error;
|
||||
$("cache-scope").value = "*";
|
||||
offset = 0; resetLiveChart("*");
|
||||
@@ -276,7 +274,7 @@
|
||||
if (data.settings && Array.isArray(data.vhosts)) {
|
||||
staticData = { settings: data.settings, vhosts: data.vhosts, catalog_version: data.catalog_version };
|
||||
staticRevision = data.revision;
|
||||
configure(); // Effective Docker vhosts can change without a saved config revision.
|
||||
configure();
|
||||
} else if (staticData) {
|
||||
data = { ...staticData, ...data };
|
||||
}
|
||||
|
||||
@@ -52,9 +52,6 @@ window.rustProxyCacheRules = (() => {
|
||||
}
|
||||
const flowMarker = rule => Array.isArray(rule.vcl_flow?.branches) && rule.vcl_flow.branches.length > 0;
|
||||
function flowFailure(rule) { return new Error(t("cacheRulesFlowInvalid").replace("{rule}", rule?.name || rule?.id || "VCL")); }
|
||||
// Structural checks only. Conditions/actions are evaluated and validated by
|
||||
// Rust; this prevents UI operations from splitting or silently flattening a
|
||||
// saved imported program before it reaches that compiler.
|
||||
function validateFlow(rules) {
|
||||
const groups = new Map();
|
||||
rules.forEach((rule, position) => {
|
||||
@@ -165,8 +162,6 @@ window.rustProxyCacheRules = (() => {
|
||||
}
|
||||
function ruleVcl(rule) {
|
||||
const lines = vclActions(rule).flatMap(line => line.split("\n"));
|
||||
// An imported return(deliver) may be represented by stop=true and no actions.
|
||||
// Preserve terminal control flow even when preceded by header/TTL actions.
|
||||
if (rule.stop && !lines.some(line => /^return\s*\(/.test(line)))
|
||||
lines.push(`return (${rule.stage === "request" ? (rule.hash_stage ? "lookup" : "hash") : "deliver"});`);
|
||||
const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
|
||||
@@ -224,16 +219,10 @@ window.rustProxyCacheRules = (() => {
|
||||
for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
// These are ordinary graphical rules, not a separate VCL engine. Keep
|
||||
// privacy boundaries fail-closed: rules which can increase cache reuse or
|
||||
// alter downstream caching start disabled until the operator reviews them.
|
||||
const templatePass = (label, conditions, match = "all") => ({
|
||||
name: t(label), stage: "request", match, conditions,
|
||||
actions: [{ type: "pass" }], stop: true,
|
||||
});
|
||||
// Cookie/session guards use cookie_pass: the same BYPASS for pages, but
|
||||
// RustProxy may still cache a *public static asset* when the global static
|
||||
// cookie policy is on and no explicit pass rule matches the request.
|
||||
const templateCookieGuard = (label, conditions, match = "all") => ({
|
||||
...templatePass(label, conditions, match), actions: [{ type: "cookie_pass" }],
|
||||
});
|
||||
@@ -246,8 +235,6 @@ window.rustProxyCacheRules = (() => {
|
||||
});
|
||||
const protectedPaths = "^/(?:admin|auth|login|logout|user|users|account|profile|settings|dashboard|cart|checkout|orders|billing|payment)(?:/|[?]|$)";
|
||||
const TEMPLATES = {
|
||||
// Path guard and Cookie guard are separate rules: the explicit path pass
|
||||
// is never relaxed, the Cookie guard may yield to the static policy.
|
||||
wordpress: () => [
|
||||
{ name: t("cacheRuleTplWordpress"), stage: "request", match: "all", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }], actions: [{ type: "pass" }] },
|
||||
{ name: t("cacheRuleTplWordpressCookies"), stage: "request", match: "all", conditions: [{ field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "cookie_pass" }] },
|
||||
@@ -256,8 +243,6 @@ window.rustProxyCacheRules = (() => {
|
||||
{ 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" }] },
|
||||
],
|
||||
// Opt-in CDN cookie policy. Never strip a mixed Cookie header: it may
|
||||
// contain session/authentication state required by the origin.
|
||||
cdn: () => {
|
||||
const technical = "(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)";
|
||||
return [
|
||||
@@ -268,9 +253,6 @@ window.rustProxyCacheRules = (() => {
|
||||
{ name: t("cacheRuleTplCdnRemaining"), stage: "request", match: "all", conditions: [{ field: "header", name: "Cookie", operator: "exists" }], actions: [{ type: "cookie_pass" }], stop: true },
|
||||
];
|
||||
},
|
||||
// Separate from the CDN template: remove only explicitly named cookies
|
||||
// confirmed to be irrelevant to this Vhost. HTTP Cookie has no Domain
|
||||
// attribute, so no origin inference or wildcard session-cookie removal.
|
||||
publiccookies: () => [{
|
||||
name: t("cacheRuleTplPubliccookies"), enabled: false, stage: "request", match: "all",
|
||||
conditions: [
|
||||
@@ -284,13 +266,10 @@ window.rustProxyCacheRules = (() => {
|
||||
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" }] }],
|
||||
// No negative-cache template: the storage layer currently stores 200 only.
|
||||
// A TTL rule matching 404 would appear enabled but could never yield HIT.
|
||||
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
|
||||
browser: () => [{ name: t("cacheRuleTplBrowser"), stage: "deliver", 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: "set_header", name: "Cache-Control", value: "public, max-age=2592000" }] }],
|
||||
nobrowser: () => [{ name: t("cacheRuleTplNoBrowser"), stage: "deliver", match: "any", conditions: [{ field: "content_type", operator: "prefix", values: ["text/html"] }, { field: "path", operator: "prefix", values: ["/admin", "/account"] }], actions: [{ type: "set_header", name: "Cache-Control", value: "no-store" }] }],
|
||||
security: () => [{ name: t("cacheRuleTplSecurity"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "default_header", name: "X-Content-Type-Options", value: "nosniff" }, { type: "default_header", name: "Referrer-Policy", value: "strict-origin-when-cross-origin" }] }],
|
||||
// Safety and authenticated traffic. No rule below removes unknown cookies.
|
||||
safemethods: () => [templatePass("cacheRuleTplSafemethods", [{ field: "method", operator: "equals", values: ["GET", "HEAD"], negate: true }])],
|
||||
authbypass: () => [templatePass("cacheRuleTplAuthbypass", [{ field: "header", name: "Authorization", operator: "exists" }])],
|
||||
cookiepass: () => [templateCookieGuard("cacheRuleTplCookiepass", [{ field: "header", name: "Cookie", operator: "exists" }])],
|
||||
@@ -316,7 +295,6 @@ window.rustProxyCacheRules = (() => {
|
||||
signedurls: () => [templatePass("cacheRuleTplSignedurls", [
|
||||
...["token", "access_token", "signature", "sig", "auth_token"].map(name => ({ field: "query", name, operator: "exists" })),
|
||||
], "any")],
|
||||
// Framework-specific guards are independent from the CDN allowlist.
|
||||
woocommerce: () => [
|
||||
templatePass("cacheRuleTplWoocommerce", [templatePath("^/(?:cart|checkout|my-account)(?:/|[?]|$)")]),
|
||||
templateCookieGuard("cacheRuleTplWoocommerceCookies", [
|
||||
@@ -328,8 +306,6 @@ window.rustProxyCacheRules = (() => {
|
||||
authjs: () => [templateCookieGuard("cacheRuleTplAuthjs", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:__Secure-)?(?:next-auth[.]session-token|authjs[.]session-token)="] }])],
|
||||
aspnet: () => [templateCookieGuard("cacheRuleTplAspnet", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:[.]AspNetCore[.]Cookies|ASP[.]NET_SessionId)="] }])],
|
||||
drupal: () => [templateCookieGuard("cacheRuleTplDrupal", [{ field: "header", name: "Cookie", operator: "regex", values: ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="] }])],
|
||||
// Cache acceleration must be opt-in: names, routes, representation privacy,
|
||||
// Vary, and origin Cache-Control must be checked before activation.
|
||||
publicjson: () => [templateResponse("cacheRuleTplPublicjson", [
|
||||
{ field: "path", operator: "prefix", values: ["/api/public/"] },
|
||||
{ field: "status", operator: "equals", values: ["200"] },
|
||||
@@ -364,8 +340,6 @@ window.rustProxyCacheRules = (() => {
|
||||
{ field: "path", operator: "prefix", values: ["/search"] },
|
||||
{ field: "status", operator: "equals", values: ["200"] },
|
||||
], [{ type: "ttl", seconds: 15 }])],
|
||||
// Cache blocking AND browser no-store are separate stages: a deliver rule
|
||||
// alone cannot prevent a shared-cache HIT. Purge old objects on activation.
|
||||
nocachehtml: () => [
|
||||
templateResponse("cacheRuleTplNocachehtmlResponse", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "no_store" }], true),
|
||||
templateDeliver("cacheRuleTplNocachehtmlDeliver", [{ field: "content_type", operator: "prefix", values: ["text/html"] }], [{ type: "set_header", name: "Cache-Control", value: "no-store" }]),
|
||||
@@ -382,8 +356,6 @@ window.rustProxyCacheRules = (() => {
|
||||
stagingnoindex: () => [templateDeliver("cacheRuleTplStagingnoindex", [], [{ type: "default_header", name: "X-Robots-Tag", value: "noindex, nofollow" }], false)],
|
||||
frameguard: () => [templateDeliver("cacheRuleTplFrameguard", [], [{ type: "default_header", name: "X-Frame-Options", value: "SAMEORIGIN" }], false)],
|
||||
};
|
||||
// Display order is deliberate. Parent-domain cookie cleanup stays a
|
||||
// distinct template and can be inserted before CDN strip/pass guards.
|
||||
const TEMPLATE_GROUPS = [
|
||||
{ id: "privacy", keys: ["safemethods", "authbypass", "cookiepass", "sessioncookies", "privateroutes", "preview", "checkout", "webhooks", "healthchecks", "graphql", "streaming", "signedurls", "nocachehtml", "privateapi", "privatedownloads"] },
|
||||
{ id: "frameworks", keys: ["wordpress", "woocommerce", "django", "laravel", "authjs", "aspnet", "drupal"] },
|
||||
@@ -399,9 +371,6 @@ window.rustProxyCacheRules = (() => {
|
||||
function applicableGlobals(vhostId) {
|
||||
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
|
||||
}
|
||||
// A request `pass` rule whose only conditions describe cookies (all match)
|
||||
// or that has a Cookie condition alongside others (any match) is a likely
|
||||
// Cookie/session guard created before cookie_pass existed.
|
||||
function cookieOnlyPass(rule) {
|
||||
if (rule.stage !== "request" || !rule.actions.some(a => a.type === "pass")) return false;
|
||||
const isCookie = c => !c.negate && (c.field === "cookie" || (c.field === "header" && String(c.name || "").trim().toLowerCase() === "cookie"));
|
||||
@@ -481,9 +450,6 @@ window.rustProxyCacheRules = (() => {
|
||||
const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
|
||||
const toolbar = el("div", undefined, "cache-rules-toolbar");
|
||||
if (scope === "vhost") {
|
||||
// Both ordinary vhost and Docker assignment editors use this component.
|
||||
// The shared guide opener is delegated in settings.js, so dynamic editors
|
||||
// receive the same modal without binding additional event handlers.
|
||||
const helpLinks = el("div", undefined, "cache-rules-vhost-links");
|
||||
const docs = el("a", t("cacheRulesDocs"), "docs-link");
|
||||
docs.href = "/docs#doc=docs%2FCACHE.md§ion=cache-rules-vcl-style";
|
||||
@@ -540,8 +506,6 @@ window.rustProxyCacheRules = (() => {
|
||||
const importResult = el("div", undefined, "cache-rules-import-result");
|
||||
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importApply, importCancel);
|
||||
let pendingImport = null, importGeneration = 0;
|
||||
// Any edit/close/submit supersedes older in-flight API responses. An old
|
||||
// parse result must never mutate the editor after the user cancelled it.
|
||||
const resetImportPreview = () => {
|
||||
importGeneration++;
|
||||
pendingImport = null;
|
||||
@@ -653,8 +617,6 @@ window.rustProxyCacheRules = (() => {
|
||||
if (grouped) card.append(el("p", t("cacheRuleFlowPart").replace("{index}", rule.vcl_flow.index + 1).replace("{count}", rule.vcl_flow.count), "fine cache-rules-notice cache-rule-note"));
|
||||
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
|
||||
if (cookieOnlyPass(rule)) {
|
||||
// Controlled migration: an explicit pass is never relaxed automatically.
|
||||
// The operator may convert a Cookie-session guard after review.
|
||||
const note = el("p", t("cacheRuleCookieGuardHint"), "fine cache-rules-notice cache-rule-note");
|
||||
const convert = el("button", t("cacheRuleCookieGuardConvert"), "outline"); convert.type = "button";
|
||||
convert.addEventListener("click", () => { rule.actions = rule.actions.map(a => a.type === "pass" ? { type: "cookie_pass" } : a); render(); changed(); toast(t("cacheRuleCookieGuardConverted")); });
|
||||
@@ -814,9 +776,6 @@ window.rustProxyCacheRules = (() => {
|
||||
run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
|
||||
try {
|
||||
const requestHeaders = pairs(headers.value);
|
||||
// A draft/new vhost has no stored frontend.hosts entry yet. With a
|
||||
// path-only test use its current editor hostname, not an empty Host,
|
||||
// so global host conditions are evaluated consistently.
|
||||
if (scope === "vhost" && url.value.trim().startsWith("/") && !requestHeaders.some(([name]) => name.toLowerCase() === "host")) {
|
||||
const host = String(typeof options.testHost === "function" ? options.testHost() || "" : "").trim();
|
||||
if (host && !host.startsWith("*.")) requestHeaders.push(["Host", host]);
|
||||
@@ -868,8 +827,6 @@ window.rustProxyCacheRules = (() => {
|
||||
}
|
||||
return rule;
|
||||
});
|
||||
// The parent-name rule must execute before the independent CDN cookie
|
||||
// strip / remaining-cookie pass checks; never move or merge CDN rules.
|
||||
const cdnIndex = templateKey === "publiccookies" ? rules.findIndex(rule =>
|
||||
/^CDN:/.test(rule.name || "") && rule.conditions.some(c => c.field === "header" && String(c.name || "").toLowerCase() === "cookie") &&
|
||||
rule.actions.some(a => a.type === "strip_cookies" || a.type === "pass" || a.type === "cookie_pass")) : -1;
|
||||
@@ -937,8 +894,6 @@ window.rustProxyCacheRules = (() => {
|
||||
const source = importText.value;
|
||||
try {
|
||||
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: source }) });
|
||||
// The user must opt into a partial/approximated import after seeing
|
||||
// warnings. Previously incomplete VCL was added before any warning was shown.
|
||||
if (generation !== importGeneration || importText.value !== source || importBox.hidden) return;
|
||||
if (data.warnings?.length) {
|
||||
const list = el("ul", undefined, "cache-rules-warnings");
|
||||
|
||||
@@ -1139,7 +1139,6 @@ progress::-moz-progress-bar {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
|
||||
.pages-errors {
|
||||
margin: 14px 0 6px;
|
||||
}
|
||||
@@ -1635,9 +1634,6 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* One information affordance for the whole panel: <details class="metric-info">
|
||||
with a summary popover, or a .rp-info-icon button that opens a help dialog.
|
||||
Shape follows the Appearance corner style; colors follow the theme. */
|
||||
.metric-info>summary,
|
||||
.rp-info-icon {
|
||||
box-sizing: border-box;
|
||||
@@ -2090,7 +2086,6 @@ html[data-interface-icons="true"] :is(button, a, summary)>svg.ui-icon {
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
|
||||
.fastcgi-php-only-local[hidden],
|
||||
#php-fpm-profiles-list .fastcgi-php-only[hidden],
|
||||
#php-fpm-profiles-list .fastcgi-profile-section[hidden] {
|
||||
|
||||
@@ -169,7 +169,6 @@ html[data-theme=cream] :is(.card, .stat, dialog) {
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
/* Value tooltips without X/Y scales: keep the host for the crosshair only. */
|
||||
.rp-chart-axis-off :is(.rp-chart-axis-y, .rp-chart-axis-x, .rp-chart-axis-series, .rp-chart-crosshair-h, .rp-chart-crosshair-y) {
|
||||
display: none;
|
||||
}
|
||||
@@ -1221,7 +1220,7 @@ html[data-dashboard-density=ultra] #panel-overview .stat-cache-outcomes .cache-m
|
||||
}
|
||||
|
||||
:is(.stat-chart, .activity-card, .system-card, .function-live-chart) svg:not(.ui-icon),
|
||||
:is(.traffic-donut, .traffic-bar-chart span) {
|
||||
.traffic-bar-chart span {
|
||||
filter: var(--chart-svg-filter);
|
||||
}
|
||||
|
||||
@@ -2051,8 +2050,7 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
border-radius: var(--rp-radius-control) !important;
|
||||
}
|
||||
|
||||
/* Corner style coverage for editor/settings surfaces that have no radius of their own. */
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(.acl-policy-mode-card, .acl-policy-builder, .acl-policy-preview, .settings-shortcuts, .top-log-menu-items, .listener-active-summary, .listener-active-item, .listener-card, .named-listener-row, .host-chip-editor, .vhost-chart, .vhost-detail-strip, .vhost-live-metric, .vh-www-panel, .vh-enable-control, .lb-simulator, .rt-tester, .hdr-card, .hdr-preview, .hdr-preview-col, .location-header-direction, .vh-header-empty, .docker-service-row, .docker-agent-summary, .lb-equivalent pre, .policy-visual>p.fine, .location-doc-intro, .docker-agent-security, .policy-action, .policy-condition-builder, .hdr-row, .vh-www-domain-pair, .vh-location, .location-conditions, .location-group, .location-preview, .redirect-tester, .redirect-rule-table, .notfound-preview, .notfound-preview iframe, .page-preview-pane, .page-preview-pane iframe, .page-editor, .settings-flow-step, .settings-flow-example pre, .settings-timeline-step, .security-summary-tile, .acl-simulator, .page-kind-chip) {
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(.acl-policy-mode-card, .acl-policy-builder, .acl-policy-preview, .settings-shortcuts, .top-log-menu-items, .listener-active-summary, .listener-active-item, .listener-card, .named-listener-row, .host-chip-editor, .vhost-chart, .vhost-detail-strip, .vhost-live-metric, .vh-www-panel, .vh-enable-control, .lb-simulator, .rt-tester, .hdr-card, .hdr-preview, .hdr-preview-col, .location-header-direction, .vh-header-empty, .docker-service-row, .docker-agent-summary, .lb-equivalent pre, .policy-visual>p.fine, .location-doc-intro, .docker-agent-security, .policy-action, .policy-condition-builder, .hdr-row, .vh-www-domain-pair, .vh-location, .location-conditions, .location-group, .location-preview, .redirect-tester, .redirect-rule-table, .notfound-preview, .notfound-preview iframe, .page-preview-pane, .page-preview-pane iframe, .page-editor, .cert-summary-tile, .certificate-section, .certificate-assign-table, .traffic-capture, .settings-flow-step, .settings-flow-example pre, .settings-timeline-step, .security-summary-tile, .acl-simulator, .page-kind-chip) {
|
||||
border-radius: var(--rp-radius-surface) !important;
|
||||
}
|
||||
|
||||
@@ -2069,13 +2067,11 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
border-bottom-left-radius: 0;
|
||||
}
|
||||
|
||||
/* The sparkline runs edge to edge at the bottom of the chart box. */
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) .vhost-chart svg {
|
||||
border-bottom-right-radius: max(0px, calc(var(--rp-radius-surface) - 1px));
|
||||
border-bottom-left-radius: max(0px, calc(var(--rp-radius-surface) - 1px));
|
||||
}
|
||||
|
||||
/* Filled cells meet the strip corners; clip them to the strip shape. */
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) .vhost-detail-strip {
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -4104,9 +4100,6 @@ html[data-dashboard-density=ultra] #panel-overview .docker-load-list {
|
||||
background: color-mix(in srgb, var(--accent) 8%, transparent);
|
||||
pointer-events: none;
|
||||
}
|
||||
/* Nested surfaces: a block inside a dialog, card or floating panel uses a
|
||||
smaller radius than its container, and the dialog body itself is not a
|
||||
second framed block inside the dialog. */
|
||||
html[data-corner-style] :is(dialog, .card, .stat, .settings-page, .settings-tabs, .draft-dock, .top-log-menu-items, .metric-info-popover, .backend-column-options) * {
|
||||
--rp-radius-surface: var(--rp-radius-nested, 0px);
|
||||
}
|
||||
|
||||
@@ -94,7 +94,6 @@
|
||||
margin-top: 6px !important;
|
||||
}
|
||||
|
||||
|
||||
:is(.vh-grid, .field-grid)>:is(.vh-field, label:not([class]), .auto-id-field) {
|
||||
grid-row: span 2;
|
||||
}
|
||||
@@ -368,7 +367,6 @@
|
||||
border-bottom: 1px solid var(--row-line);
|
||||
}
|
||||
|
||||
/* Collapsed Custom Location = one routing-table row. */
|
||||
.location-summary {
|
||||
display: grid;
|
||||
grid-template-columns: 26px 12px minmax(0, 120px) 120px minmax(0, 1fr) minmax(0, 1.3fr) minmax(0, 1.3fr);
|
||||
@@ -620,8 +618,7 @@
|
||||
#panel-tls .certificate-operation-heading strong,
|
||||
#panel-tls .renewal-entry-identity strong,
|
||||
.certificate-api-credential-info code,
|
||||
.certificate-api-credential-info small,
|
||||
.certificate-bulk-list .check {
|
||||
.certificate-api-credential-info small {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@@ -696,11 +693,6 @@
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* Vhost editor: heading and tabs stay on top, only the fields scroll and the
|
||||
save bar is a plain footer. No sticky positioning inside the scrolled area,
|
||||
so long Custom Location editors cannot push the bar into the content. */
|
||||
/* Tabbed editors: heading, summary and tabs stay on top, only the fields
|
||||
scroll, and the save bar is the dialog footer. */
|
||||
:is(#vhost-dialog, #redirect-dialog, #notfound-dialog, #stream-dialog)[open] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1239,8 +1231,7 @@ p,
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.vh-www-details,
|
||||
.certificate-bulk-assign {
|
||||
.vh-www-details {
|
||||
margin-top: 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 12px;
|
||||
@@ -1408,7 +1399,6 @@ p,
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
/* Redirect rule rows reuse the Custom location routing table. */
|
||||
.redirect-rule-cards {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr);
|
||||
}
|
||||
@@ -1704,8 +1694,7 @@ html[data-dashboard-density=ultra] #panel-overview .dashboard-overview-grid>.car
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.acl-policy-step-head,
|
||||
.certificate-card-head {
|
||||
.acl-policy-step-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
@@ -2478,7 +2467,6 @@ h2+.fine {
|
||||
}
|
||||
}
|
||||
|
||||
/* Stream backends: routing-table rows in the editor and the card. */
|
||||
.stream-backend-toolbar {
|
||||
align-items: end;
|
||||
justify-content: flex-start;
|
||||
@@ -2521,7 +2509,6 @@ h2+.fine {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 404 host response choice cards and sandboxed preview. */
|
||||
.notfound-kinds {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
margin-bottom: 10px;
|
||||
@@ -3018,7 +3005,6 @@ h2+.fine {
|
||||
.hdr-row.is-invalid .hdr-row-hint {
|
||||
color: var(--red);
|
||||
}
|
||||
/* Error fallback status picker (vhost and Custom Location). */
|
||||
.vh-error-fallback-statuses {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
@@ -3070,7 +3056,6 @@ h2+.fine {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* Web Service type and FastCGI source choices reuse the Vhost www cards. */
|
||||
.web-service-kinds {
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
}
|
||||
@@ -3098,9 +3083,6 @@ h2+.fine {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* Editor dialogs: the title row is followed directly by the tabs. Live
|
||||
summaries are shown inside the relevant tab (Backend health, Backends);
|
||||
the identifier is in the title pill and hostnames in the Frontend tab. */
|
||||
:is(#vhost-form, #redirect-form, #notfound-form, #stream-form)>.vh-live-summary {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -169,10 +169,6 @@
|
||||
letter-spacing: .7px;
|
||||
}
|
||||
|
||||
.certificate-details-body {
|
||||
padding: 0 0 8px;
|
||||
}
|
||||
|
||||
.certificate-details .entity-details {
|
||||
margin: 4px 0;
|
||||
}
|
||||
@@ -952,7 +948,6 @@ html:not([data-switch-controls="false"]) .docker-publish-field input.docker-publ
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
|
||||
.certificate-api-credential-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1021,14 +1016,6 @@ html:not([data-switch-controls="false"]) .docker-publish-field input.docker-publ
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.certificate-bulk-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
max-height: 250px;
|
||||
overflow-y: auto;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.docker-agent-security-hint,
|
||||
.docker-agent-summary>span,
|
||||
.docker-fingerprint {
|
||||
@@ -3844,7 +3831,6 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
padding: 11px;
|
||||
}
|
||||
}
|
||||
/* Settings navigation: grouped list, active item marked like other editors. */
|
||||
.settings-nav-group {
|
||||
padding: 10px 10px 4px;
|
||||
color: var(--muted);
|
||||
@@ -3869,10 +3855,9 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
/* Sub-tabs inside a settings page and the certificate views use the same
|
||||
underlined tabs as the Vhost editor. */
|
||||
#panel-settings .settings-tabs.sub-tabs,
|
||||
#panel-tls .settings-tabs.certificate-tabs {
|
||||
#panel-tls .settings-tabs.certificate-tabs,
|
||||
#panel-traffic .settings-tabs.traffic-tabs {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
@@ -3886,7 +3871,8 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
}
|
||||
|
||||
#panel-settings .settings-tabs.sub-tabs button,
|
||||
#panel-tls .settings-tabs.certificate-tabs button {
|
||||
#panel-tls .settings-tabs.certificate-tabs button,
|
||||
#panel-traffic .settings-tabs.traffic-tabs button {
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
margin-bottom: -1px;
|
||||
@@ -3901,13 +3887,15 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
}
|
||||
|
||||
#panel-settings .settings-tabs.sub-tabs button:hover,
|
||||
#panel-tls .settings-tabs.certificate-tabs button:hover {
|
||||
#panel-tls .settings-tabs.certificate-tabs button:hover,
|
||||
#panel-traffic .settings-tabs.traffic-tabs button:hover {
|
||||
background: var(--panel2);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
#panel-settings .settings-tabs.sub-tabs button[aria-selected=true],
|
||||
#panel-tls .settings-tabs.certificate-tabs button[aria-selected=true] {
|
||||
#panel-tls .settings-tabs.certificate-tabs button[aria-selected=true],
|
||||
#panel-traffic .settings-tabs.traffic-tabs button[aria-selected=true] {
|
||||
border-bottom-color: var(--green);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
@@ -3915,7 +3903,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(#panel-settings .settings-tabs.sub-tabs, #panel-tls .settings-tabs.certificate-tabs) {
|
||||
html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-style=rounded], [data-corner-style=extra]) :is(#panel-settings .settings-tabs.sub-tabs, #panel-tls .settings-tabs.certificate-tabs, #panel-traffic .settings-tabs.traffic-tabs) {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
@@ -3929,7 +3917,6 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
}
|
||||
}
|
||||
|
||||
/* Docker agents in Settings: routing-table rows with sections. */
|
||||
#docker-agent-settings-list {
|
||||
gap: 9px;
|
||||
}
|
||||
@@ -4055,8 +4042,6 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
}
|
||||
}
|
||||
|
||||
/* Help text in agent rows uses the regular help style, not the compact
|
||||
monospace .entity caption. */
|
||||
.docker-agent-row small {
|
||||
font: 11px/1.45 inherit;
|
||||
font-family: inherit;
|
||||
@@ -4080,7 +4065,6 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
align-self: start;
|
||||
}
|
||||
|
||||
/* Visual request flows (cache, transformation) and the cache freshness timeline. */
|
||||
.settings-page-intro {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
@@ -4318,7 +4302,6 @@ button.settings-flow-step:focus-visible {
|
||||
}
|
||||
}
|
||||
|
||||
/* Security page: summary tiles, default-decision cards, policy simulator. */
|
||||
.security-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
||||
@@ -4439,7 +4422,704 @@ button.settings-flow-step:focus-visible {
|
||||
}
|
||||
}
|
||||
|
||||
/* Rules & headers: one card with tabs, like HTTP connections. */
|
||||
.policy-settings-card [data-policy-settings-page]>form {
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.cert-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 10px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.cert-summary-tile {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
justify-items: start;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
padding: 11px 13px;
|
||||
border: 1px solid var(--line);
|
||||
border-left: 3px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
button.cert-summary-tile {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.cert-summary-tile:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.cert-summary-tile.is-ok {
|
||||
border-left-color: var(--green);
|
||||
}
|
||||
|
||||
.cert-summary-tile.is-warn {
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
|
||||
.cert-summary-tile.is-bad {
|
||||
border-left-color: var(--red);
|
||||
}
|
||||
|
||||
.cert-summary-tile b {
|
||||
font-size: 19px;
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.cert-summary-tile span {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cert-summary-tile small {
|
||||
color: var(--muted);
|
||||
font-size: 11.5px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 2px 12px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card .certificate-operation-heading {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card .certificate-operation-heading>div {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 2px 10px;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card #acme-runtime-message {
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
#panel-tls #acme-runtime-card>.fine {
|
||||
grid-column: 1;
|
||||
margin: 0;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.certificate-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.certificate-toolbar input[type=search] {
|
||||
flex: 0 1 320px;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.certificate-filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.certificate-filters button {
|
||||
min-height: 28px;
|
||||
padding: 2px 11px;
|
||||
border: 1px solid var(--line);
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.certificate-filters button[aria-pressed=true] {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
#panel-tls .certificate-inventory-card {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#certificate-list {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.certificate-list-head,
|
||||
.certificate-row-summary {
|
||||
display: grid;
|
||||
grid-template-columns: 10px minmax(150px, 1.15fr) minmax(0, 1.3fr) minmax(150px, 1fr) minmax(120px, .9fr) 14px;
|
||||
align-items: center;
|
||||
gap: 8px 14px;
|
||||
padding: 10px 14px;
|
||||
}
|
||||
|
||||
.certificate-list-head {
|
||||
color: var(--muted);
|
||||
font: 10px var(--mono);
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
#certificate-list>.certificate-row {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
#certificate-list>.certificate-row[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-row-summary {
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.certificate-row-summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-row-summary:hover,
|
||||
.certificate-row[open]>.certificate-row-summary {
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.certificate-row[open]>.certificate-row-summary {
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.certificate-row-chevron::before {
|
||||
content: "▸";
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.certificate-row[open] .certificate-row-chevron::before {
|
||||
content: "▾";
|
||||
}
|
||||
|
||||
.certificate-state-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.certificate-state-dot[data-tone=ok] {
|
||||
background: var(--green);
|
||||
}
|
||||
|
||||
.certificate-state-dot[data-tone=warn] {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.certificate-state-dot[data-tone=bad] {
|
||||
background: var(--red);
|
||||
}
|
||||
|
||||
.certificate-row .certificate-card-identity {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.certificate-row .certificate-card-identity .entity-title {
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-row .certificate-coverage {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.certificate-validity {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.certificate-validity[data-tone=warn] .certificate-validity-text {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.certificate-validity[data-tone=bad] .certificate-validity-text {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.certificate-validity-bar {
|
||||
display: block;
|
||||
height: 4px;
|
||||
background: var(--line);
|
||||
border-radius: var(--rp-progress-radius, 0px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.certificate-validity-bar>i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--green);
|
||||
}
|
||||
|
||||
.certificate-validity[data-tone=warn] .certificate-validity-bar>i {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.certificate-validity[data-tone=bad] .certificate-validity-bar>i {
|
||||
background: var(--red);
|
||||
}
|
||||
|
||||
.certificate-usage-cell {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.certificate-row-body {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
padding: 4px 14px 14px 38px;
|
||||
background: var(--panel2);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.certificate-row-body>.certificate-usage {
|
||||
align-self: start;
|
||||
}
|
||||
|
||||
#panel-tls .certificate-inventory-card .certificate-library-footer {
|
||||
padding: 12px 14px 14px;
|
||||
}
|
||||
|
||||
.certificate-row-side {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.certificate-section {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
padding: 11px 13px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.certificate-section h4 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.certificate-section p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.certificate-usage-group {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.certificate-usage-group>.small-label {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.certificate-usage-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(80px, auto) minmax(0, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
padding: 5px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.certificate-usage-row .mono {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-usage-row .pill {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-usage-open {
|
||||
min-height: 24px;
|
||||
padding: 0 8px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.certificate-kv {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(110px, auto) minmax(0, 1fr);
|
||||
gap: 5px 12px;
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.certificate-kv dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.certificate-kv dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-file-paths {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
white-space: pre-line;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-row .entity-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
#certificate-list>.empty {
|
||||
padding: 14px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.certificate-assign-dialog {
|
||||
width: min(1040px, calc(100vw - 32px));
|
||||
}
|
||||
|
||||
.certificate-assign-dialog .window-heading {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.certificate-assign-dialog .window-heading>div:first-child {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.certificate-assign-domains {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.certificate-assign-body {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.certificate-assign-select {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.certificate-assign-table {
|
||||
display: grid;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
max-height: min(56vh, 560px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.certificate-assign-row {
|
||||
display: grid;
|
||||
grid-template-columns: 24px minmax(110px, .8fr) minmax(0, 1.4fr) minmax(150px, 1fr) minmax(130px, .9fr);
|
||||
align-items: center;
|
||||
gap: 4px 12px;
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.certificate-assign-row.certificate-assign-head {
|
||||
border-top: 0;
|
||||
color: var(--muted);
|
||||
font: 10px var(--mono);
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
cursor: default;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.certificate-assign-row.is-changed {
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.certificate-assign-row.is-disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: .7;
|
||||
}
|
||||
|
||||
.certificate-assign-row .pill {
|
||||
justify-self: start;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.certificate-assign-row b,
|
||||
.certificate-assign-row .fine {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-assign-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 14px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.certificate-assign-footer p {
|
||||
flex: 1 1 320px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.certificate-assign-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
#panel-tls .renewal-entry-identity {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
}
|
||||
|
||||
#panel-tls .renewal-meta {
|
||||
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#panel-tls .renewal-meta-arrow {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
#panel-tls .renewal-actions [data-action=renewalForce] {
|
||||
border-color: color-mix(in srgb, var(--red) 55%, var(--line));
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
#panel-tls .renewal-actions :is([data-action=renewalDisable], [data-action=renewalEnable]) {
|
||||
order: 9;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.certificate-source {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.certificate-source-modes {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-control, 0px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.certificate-source-modes button {
|
||||
min-height: 32px;
|
||||
padding: 4px 14px;
|
||||
border: 0;
|
||||
border-left: 1px solid var(--line);
|
||||
border-radius: 0 !important;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.certificate-source-modes button:first-child {
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.certificate-source-modes button.is-selected {
|
||||
background: var(--panel2);
|
||||
color: var(--accent);
|
||||
box-shadow: inset 0 -2px 0 var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.certificate-source-acme {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 360px));
|
||||
gap: 10px 14px;
|
||||
}
|
||||
|
||||
.certificate-source-acme[hidden],
|
||||
.certificate-dns-provider[hidden],
|
||||
.provider-combo-list[hidden],
|
||||
#panel-tls .provider-picker-legacy[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-source-acme>label,
|
||||
.certificate-dns-provider {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.provider-combo {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.provider-combo input {
|
||||
width: 100%;
|
||||
padding-right: 26px;
|
||||
}
|
||||
|
||||
.provider-combo::after {
|
||||
content: "▾";
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.provider-combo-list {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 2px);
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 4px 0;
|
||||
list-style: none;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-control, 0px);
|
||||
background: var(--panel);
|
||||
box-shadow: 0 12px 30px var(--shadow-strong);
|
||||
}
|
||||
|
||||
.provider-combo-list li {
|
||||
padding: 6px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.provider-combo-list li:hover,
|
||||
.provider-combo-list li.is-active {
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
.provider-combo-list li[aria-selected=true] {
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.provider-combo-list .provider-combo-empty {
|
||||
color: var(--muted);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.cert-summary {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.cert-summary-tile b {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.certificate-list-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-row-summary {
|
||||
grid-template-columns: 10px minmax(0, 1fr) 14px;
|
||||
}
|
||||
|
||||
.certificate-row-summary>:is(.certificate-coverage, .certificate-validity, .certificate-usage-cell) {
|
||||
grid-column: 2;
|
||||
}
|
||||
|
||||
.certificate-row-summary>.certificate-row-chevron {
|
||||
grid-column: 3;
|
||||
grid-row: 1;
|
||||
}
|
||||
|
||||
.certificate-row-body {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
padding-left: 14px;
|
||||
}
|
||||
|
||||
.certificate-assign-row {
|
||||
grid-template-columns: 24px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.certificate-assign-row>:nth-child(n+3) {
|
||||
grid-column: 2;
|
||||
}
|
||||
|
||||
.certificate-assign-row.certificate-assign-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-source-acme {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
#panel-tls .renewal-meta {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
#panel-tls .renewal-meta-arrow {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.certificate-usage-row {
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
}
|
||||
|
||||
.certificate-usage-row>.fine,
|
||||
.certificate-usage-row>.pill {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
/* Shared global, vhost, Docker and location HTTP policy editor. */
|
||||
.http-policy-editor,
|
||||
.policy-visual,
|
||||
.policy-rules,
|
||||
@@ -457,8 +456,6 @@
|
||||
min-width: 520px;
|
||||
}
|
||||
|
||||
/* Docker service "HTTP policies" uses the same disclosure row as the other sections. */
|
||||
|
||||
.docker-policy-editor>.http-policy-editor {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
@@ -251,40 +251,6 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.traffic-donut-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 148px minmax(0, 1fr);
|
||||
gap: 14px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.traffic-donut {
|
||||
position: relative;
|
||||
width: 148px;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
background: var(--chart-surface);
|
||||
box-shadow: inset 0 0 0 1px var(--line);
|
||||
}
|
||||
|
||||
.traffic-donut:before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 23%;
|
||||
border-radius: 50%;
|
||||
background: var(--chart-surface-alt);
|
||||
box-shadow: 0 0 0 1px var(--line);
|
||||
}
|
||||
|
||||
.traffic-donut>span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font: 700 16px var(--mono);
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-tabs {
|
||||
margin: 12px 0 14px;
|
||||
}
|
||||
@@ -1559,4 +1525,311 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
|
||||
#panel-cache .cache-pager>button:last-child {
|
||||
border-radius: 0 0 max(0px, calc(var(--rp-radius-control, 0px) - 1px)) 0 !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
#panel-traffic .traffic-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-toolbar>label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-toolbar select {
|
||||
min-width: 240px;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-toolbar .cache-toolbar-status {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 12px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.traffic-recent {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.traffic-recent-chip {
|
||||
min-height: 24px;
|
||||
padding: 1px 9px;
|
||||
border: 1px solid var(--line);
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font: 11px var(--mono);
|
||||
}
|
||||
|
||||
.traffic-recent-chip[aria-pressed=true] {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.traffic-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: var(--ui-gap, 10px);
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.traffic-kpis .stat {
|
||||
border-left: 3px solid var(--line);
|
||||
}
|
||||
|
||||
.traffic-kpis .stat:first-child {
|
||||
border-left-color: var(--green);
|
||||
}
|
||||
|
||||
.traffic-kpis .stat.is-warn {
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
|
||||
.traffic-kpis .stat strong {
|
||||
display: block;
|
||||
margin: 6px 0 4px;
|
||||
font: 600 20px var(--mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.traffic-kpis .stat small {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.traffic-capture {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
margin: 0 0 12px;
|
||||
padding: 7px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 0px);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.traffic-capture .fine {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.traffic-capture-pills {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.traffic-capture-help {
|
||||
flex: 1 1 260px;
|
||||
}
|
||||
|
||||
.traffic-capture-open,
|
||||
.traffic-more {
|
||||
min-height: 24px;
|
||||
padding: 0 8px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.traffic-distribution {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.traffic-stack-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 130px minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 14px 16px;
|
||||
}
|
||||
|
||||
.traffic-stack-grid>.fine {
|
||||
margin: 0;
|
||||
padding-top: 1px;
|
||||
}
|
||||
|
||||
.traffic-stack-block {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.traffic-stack {
|
||||
display: flex;
|
||||
height: 12px;
|
||||
overflow: hidden;
|
||||
border-radius: var(--rp-progress-radius, 0px);
|
||||
background: var(--chart-surface);
|
||||
box-shadow: inset 0 0 0 1px var(--line);
|
||||
}
|
||||
|
||||
.traffic-stack>i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
min-width: 2px;
|
||||
}
|
||||
|
||||
.traffic-stack-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 16px;
|
||||
}
|
||||
|
||||
.traffic-stack-legend li {
|
||||
justify-content: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.traffic-stack-legend li>b {
|
||||
font: 600 11px var(--mono);
|
||||
}
|
||||
|
||||
.traffic-share {
|
||||
color: var(--muted);
|
||||
font: 11px var(--mono);
|
||||
}
|
||||
|
||||
.traffic-stack-list {
|
||||
display: grid;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.traffic-stack-list li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto 52px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.traffic-stack-list .traffic-share {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.traffic-chart-grid.traffic-two {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.traffic-chart-grid.traffic-three {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.traffic-chart-grid.traffic-three>.traffic-wide-chart {
|
||||
grid-column: auto;
|
||||
}
|
||||
|
||||
.traffic-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-chart {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row {
|
||||
grid-template-columns: minmax(0, 1fr) auto 52px;
|
||||
gap: 2px 10px;
|
||||
padding: 3px 0;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row>.traffic-bar-track {
|
||||
grid-column: 1 / -1;
|
||||
height: 4px;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row.is-other .traffic-bar-label {
|
||||
color: var(--muted);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row.is-other .traffic-bar-fill {
|
||||
background: var(--muted);
|
||||
opacity: .5;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row .traffic-share {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-label {
|
||||
justify-self: start;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
text-align: left;
|
||||
min-height: 0;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-label:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
#panel-traffic .empty .quiet {
|
||||
min-height: 24px;
|
||||
padding: 0 6px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.traffic-kpis {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.traffic-chart-grid.traffic-three {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.traffic-kpis {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.traffic-stack-grid,
|
||||
.traffic-chart-grid.traffic-two,
|
||||
.traffic-chart-grid.traffic-three {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-toolbar .cache-toolbar-status {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-toolbar select {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-bar-row {
|
||||
grid-template-columns: minmax(0, 1fr) auto 46px;
|
||||
}
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-chart-card h3.subheading,
|
||||
#panel-traffic .traffic-distribution h3.subheading {
|
||||
margin: 0 0 10px;
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
letter-spacing: 0;
|
||||
text-transform: none;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-card-head h3.subheading {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#panel-traffic .traffic-card-head {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
@@ -395,14 +395,6 @@
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.traffic-donut-layout {
|
||||
grid-template-columns: 120px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.traffic-donut {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.lb-sim-inputs {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
@@ -503,8 +503,6 @@
|
||||
} catch (error) { showBubble(`${t("dockerTestFailed")}: ${error.message}`, "error"); }
|
||||
finally { testButton.disabled = false; }
|
||||
});
|
||||
// Collapsed: one row (state, name/ID, endpoint, transport security, status, Enabled).
|
||||
// Expanded: provisioning, diagnostics and four sections holding every field.
|
||||
const section = (number, key, cls) => { const box = el("section", undefined, `location-card docker-agent-section ${cls}`), heading = el("h4", undefined, "location-card-title"), grid = el("div", undefined, "field-grid docker-agent-grid"); heading.append(el("span", number, "location-step"), el("span", t(key))); box.append(heading, grid); return [box, grid]; };
|
||||
const [connectionBox, connectionGrid] = section("1", "dockerAgentSectionConnection", "docker-agent-connection");
|
||||
const [authBox, authGrid] = section("2", "dockerAgentSectionAuth", "docker-agent-auth");
|
||||
@@ -607,8 +605,6 @@
|
||||
control.disabled = sections.length === 0; control.dataset.i18n = key; control.textContent = t(key);
|
||||
control.setAttribute("aria-expanded", String(allOpen));
|
||||
}
|
||||
// Only statistics sections near the viewport are redrawn on live updates;
|
||||
// a section scrolled into view is refreshed right away.
|
||||
let metricsFrame = 0;
|
||||
const metricsObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(entries => {
|
||||
let revealed = false;
|
||||
@@ -665,8 +661,6 @@
|
||||
history.snapshot = value; history.metrics = value; metricHistory.set(route.pool_id, history);
|
||||
}
|
||||
}
|
||||
// History is sampled always; the DOM is touched only for open sections of
|
||||
// the visible panel (a section is refreshed when it is opened).
|
||||
if (typeof currentPanel !== "undefined" && currentPanel !== "docker-vhosts") return;
|
||||
for (const section of document.querySelectorAll("#docker-discovery-list .docker-service-metrics")) {
|
||||
if (!section.open || section.dockerInView === false) continue;
|
||||
@@ -912,7 +906,6 @@
|
||||
details.addEventListener("change", sync); sync();
|
||||
return details;
|
||||
}
|
||||
// HTTP policies: an ordinary Docker service section, like Security or Proxy timeouts.
|
||||
function policyEditor(assignment, row) {
|
||||
const details = el("details", undefined, "docker-policy-editor"), summary = el("summary"), state = el("small", "", "fine");
|
||||
summary.append(el("span", t("policyTitle")), state); details.append(summary);
|
||||
@@ -1046,10 +1039,6 @@
|
||||
const headActions = el("div", undefined, "docker-service-head-actions"); headActions.append(runtimeSummary(runtime, assignment, stale), quickActions, visibility); top.append(publishLabel, meta, headActions); row.append(top);
|
||||
|
||||
const editor = el("details", undefined, "docker-service-editor"), editorSummary = el("summary"), editorTitle = el("span", t("dockerConfigureService")), editorHint = el("small", "", "fine docker-config-hint"); editorSummary.append(editorTitle, editorHint); editor.append(editorSummary);
|
||||
// The editor is the largest part of a service card (hundreds of elements
|
||||
// each); build it on first open, or right before saving, instead of for
|
||||
// every service on every render. Until then the summary, search and quick
|
||||
// actions use the stored assignment.
|
||||
const hintFor = ({ hostname, domain, targetLabel, scheme, h2, h3, aliasCount }) => `${expandedHost(hostname || technical, domain) || hostname || technical} → ${String(scheme || "http").toUpperCase()} · ${targetLabel} · H1${h2 ? "/H2" : ""}${h3 ? "/H3" : ""}${aliasCount ? ` · +${aliasCount} ${t("dockerAliasesShort")}` : ""}`;
|
||||
const initialHost = assignment?.hostname || service?.technical_name || "";
|
||||
let host = null, apply = null, editorBuilt = false;
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
const mode = group === "cloudflare" ? (CLOUDFLARE_KINDS.includes($("notfound-variant").value) ? $("notfound-variant").value : "cloudflare") : group;
|
||||
$("notfound-mode").value = mode; syncMode();
|
||||
}
|
||||
// Preview of the selected page through the sandboxed /api/pages/preview.
|
||||
let previewTimer = null;
|
||||
function previewUrl(mode = $("notfound-mode").value, status = $("notfound-status").value, host = editing) {
|
||||
const params = new URLSearchParams({ kind: mode, status: String(status || 404) });
|
||||
@@ -163,6 +162,6 @@
|
||||
form.addEventListener("submit", async event => { event.preventDefault(); if (!envelope || busy) return; const invalid = [...form.elements].find(input => input.willValidate && !input.checkValidity()); if (invalid) { invalid.reportValidity(); return; } if (revision !== envelope.revision) { toast(t("stale"), true); return; } try { const item = collect(), next = structuredClone(envelope.config.not_found_hosts || []); if (!editing && next.some(value => value.id === item.id)) throw new Error(t("notfoundDuplicate")); const index = next.findIndex(value => value.id === editing); if (index < 0) next.push(item); else next[index] = item; if (await saveSection("not-found-hosts", next)) { dirty = false; editing = item.id; dialog.close(); render(); } } catch (error) { toast(error.message, true); } });
|
||||
$("notfound-new").addEventListener("click", () => { window.rustProxyDrafts.prepare(); load(); }); $("notfound-search").addEventListener("input", render); $("notfound-sort")?.addEventListener("change", event => { listPrefs.sort = event.target.value; void saveListPrefs(); render(); }); $("notfound-sort-direction")?.addEventListener("click", () => { listPrefs.descending = !listPrefs.descending; syncSortDirection(); void saveListPrefs(); render(); }); $("notfound-close").addEventListener("click", closeEditor); $("notfound-reset").addEventListener("click", async () => { if (await allowDiscard()) load(editing ? structuredClone((envelope?.config.not_found_hosts || []).find(item => item.id === editing) || defaults()) : defaults()); }); dialog.addEventListener("cancel", event => { event.preventDefault(); closeEditor(); });
|
||||
window.rustProxyDrafts.register("notfound", { labelKey: "notfound", isOpen: () => dialog.open, isDirty: () => dirty, suspend: suspendDraft, restore: restoreDraft, close: () => { dirty = false; if (dialog.open) dialog.close(); } });
|
||||
window.rustProxyNotFound = { render, applyPreferences, reset() { dialog.close(); editing = null; revision = null; dirty = false; listPrefs = { sort: "id", descending: false }; list.replaceChildren(); $("notfound-search").value = ""; if ($("notfound-sort")) $("notfound-sort").value = listPrefs.sort; syncSortDirection(); } };
|
||||
window.rustProxyNotFound = { render, edit(id) { const item = (envelope?.config.not_found_hosts || []).find(entry => entry.id === id); if (!item) return false; window.rustProxyDrafts.prepare(); load(structuredClone(item)); return true; }, applyPreferences, reset() { dialog.close(); editing = null; revision = null; dirty = false; listPrefs = { sort: "id", descending: false }; list.replaceChildren(); $("notfound-search").value = ""; if ($("notfound-sort")) $("notfound-sort").value = listPrefs.sort; syncSortDirection(); } };
|
||||
if (envelope) render();
|
||||
})();
|
||||
+552
-422
File diff suppressed because it is too large.
Load diff
@@ -173,7 +173,6 @@
|
||||
if (!enabled.checked) badges.push([t("vhDisabled"), "danger"]);
|
||||
headBadges.replaceChildren(...badges.map(([text, cls]) => el("span", text, `pill ${cls}`.trim())));
|
||||
};
|
||||
// Two sections like the other editors: identity/addresses and protocols.
|
||||
const listenerSection = (key, cls) => { const box = el("section", undefined, `location-card listener-section ${cls}`), heading = el("h4", undefined, "location-card-title"), sectionGrid = el("div", undefined, "vh-grid"); heading.append(label("span", key)); box.append(heading, sectionGrid); return [box, sectionGrid]; };
|
||||
const [identityBox, identityGrid] = listenerSection("listenerSectionIdentity", "listener-identity"), [protocolBox, protocolGrid] = listenerSection("listenerSectionProtocols", "listener-protocols");
|
||||
identityGrid.append(...[id, name, scope].map(control => control.closest("label")), grid.querySelector(".host-chip-field"));
|
||||
|
||||
@@ -8,11 +8,6 @@
|
||||
const CLOUDFLARE_KINDS = ["cloudflare", "cloudflare_welcome", "cloudflare_placeholder"];
|
||||
const PAGE_KIND_CARDS = [["", "pageInherit", "pageKindInheritHelp"], ["welcome", "pageWelcome", "notfoundKindWelcomeHelp"], ["builtin", "pageBuiltin", "notfoundKindBuiltinHelp"], ["cloudflare", "notfoundKindCloudflare", "notfoundKindCloudflareHelp"], ["empty", "pageEmpty", "notfoundKindEmptyHelp"], ["html", "pageHtml", "notfoundKindHtmlHelp"]];
|
||||
let pageCardSerial = 0;
|
||||
// One default-response slot rendered as a compact row: the summary line shows
|
||||
// the slot, when it is used and its current response; the selected row opens
|
||||
// its controls (response type chips, Cloudflare variant, status, own HTML).
|
||||
// options: slot (preview/saved HTML key), vhostId, scope, title (literal row
|
||||
// title), whenKey, naturalStatus, onSelect, onChange.
|
||||
function pageEditor(parent, key, value = null, options = {}) {
|
||||
const row = el("div", undefined, "page-editor"), heading = options.title ? el("b", options.title, "page-label") : label("b", key, "page-label");
|
||||
const summary = el("button", undefined, "page-editor-summary"); summary.type = "button"; summary.setAttribute("aria-expanded", "false");
|
||||
@@ -31,7 +26,6 @@
|
||||
file.type = "file"; file.accept = ".html,.htm,text/html,text/plain"; file.setAttribute("aria-label", t("pageUploadHtml"));
|
||||
const source = el("div", undefined, "page-source"); source.append(label("span", "pageUploadHtml", "fine"), file, html);
|
||||
const controls = el("div", undefined, "page-editor-controls"); controls.hidden = true;
|
||||
// Chips drive the (hidden) select, which stays the single source of truth.
|
||||
const name = `page-kind-${++pageCardSerial}`, chips = el("div", undefined, "page-kind-chips"); chips.setAttribute("role", "radiogroup"); chips.setAttribute("aria-label", t(key));
|
||||
for (const [kind, titleKey, helpKey] of PAGE_KIND_CARDS) {
|
||||
const chip = el("label", undefined, "page-kind-chip"), radio = el("input"); radio.type = "radio"; radio.name = name; radio.value = kind;
|
||||
@@ -87,8 +81,6 @@
|
||||
sync();
|
||||
return api;
|
||||
}
|
||||
// One shared preview for all slots of an editor: the selected slot is shown
|
||||
// through the sandboxed /api/pages/preview (saved HTML for custom pages).
|
||||
function previewPane(parent, savedPage) {
|
||||
const pane = el("aside", undefined, "page-preview-pane"), headRow = el("div", undefined, "page-preview-head"), titleNode = el("strong", ""), open = el("a", t("notfoundPreviewOpen"), "page-preview-open");
|
||||
open.dataset.i18n = "notfoundPreviewOpen"; open.target = "_blank"; open.rel = "noopener noreferrer";
|
||||
|
||||
@@ -320,8 +320,10 @@
|
||||
<polyline class="traffic-line traffic-line-transform" id="sparkline-transform" points="0,120 600,120">
|
||||
</polyline>
|
||||
</svg>
|
||||
<div class="traffic-protocol-legend" aria-label="Request rate by HTTP protocol and transformed response rate" data-i18n-aria="trafficLegendAria">
|
||||
<span class="legend-total"><i></i><span data-i18n="trafficLegendTotal">Total</span> <b id="rate-total">0.0/s</b></span>
|
||||
<div class="traffic-protocol-legend" aria-label="Request rate by HTTP protocol and transformed response rate"
|
||||
data-i18n-aria="trafficLegendAria">
|
||||
<span class="legend-total"><i></i><span data-i18n="trafficLegendTotal">Total</span> <b
|
||||
id="rate-total">0.0/s</b></span>
|
||||
<span class="legend-h1"><i></i>HTTP/1.1 <b id="rate-h1">0.0/s</b></span>
|
||||
<span class="legend-h2"><i></i>HTTP/2 <b id="rate-h2">0.0/s</b></span>
|
||||
<span class="legend-h3"><i></i>HTTP/3 <b id="rate-h3">0.0/s</b></span>
|
||||
|
||||
@@ -34,7 +34,8 @@
|
||||
<article class="stat stat-cache-outcomes" data-dashboard-widget="cache_outcomes">
|
||||
<div class="cache-mix-header">
|
||||
<span data-i18n="cacheMixTitle">Cache outcomes</span>
|
||||
<small class="cache-mix-caption" id="cache-mix-caption" aria-label="Classified HTTP requests since service start"
|
||||
<small class="cache-mix-caption" id="cache-mix-caption"
|
||||
aria-label="Classified HTTP requests since service start"
|
||||
title="Classified HTTP requests since service start">-</small>
|
||||
</div>
|
||||
<strong id="cache-mix-headline">-</strong>
|
||||
@@ -48,8 +49,10 @@
|
||||
<small class="cache-mix-legend">
|
||||
<span class="cache-mix-hit-key" id="cache-mix-hit-key"><i></i>HIT <b id="cache-mix-hit-count">-</b></span>
|
||||
<span class="cache-mix-miss-key" id="cache-mix-miss-key"><i></i>MISS <b id="cache-mix-miss-count">-</b></span>
|
||||
<span class="cache-mix-bypass-key" id="cache-mix-bypass-key"><i></i>BYPASS <b id="cache-mix-bypass-count">-</b></span>
|
||||
<span class="cache-mix-other-key" id="cache-mix-other-key"><i></i><span data-i18n="cacheMixOther">OTHER</span> <b id="cache-mix-other-count">-</b></span>
|
||||
<span class="cache-mix-bypass-key" id="cache-mix-bypass-key"><i></i>BYPASS <b
|
||||
id="cache-mix-bypass-count">-</b></span>
|
||||
<span class="cache-mix-other-key" id="cache-mix-other-key"><i></i><span data-i18n="cacheMixOther">OTHER</span>
|
||||
<b id="cache-mix-other-count">-</b></span>
|
||||
</small>
|
||||
</article>
|
||||
<article class="stat" data-dashboard-widget="memory"><span data-i18n="processMemory">Process
|
||||
@@ -57,13 +60,15 @@
|
||||
</article>
|
||||
<article class="stat stat-with-action" data-dashboard-widget="websocket"><span data-i18n="wsActive">WebSocket
|
||||
tunnels</span><button class="pill stat-corner-action stat-corner-badge" data-i18n="tunnelsOpen"
|
||||
data-ui-icon-name="none" id="tunnels-open" type="button">Active tunnels</button><div class="stat-value-row"><strong
|
||||
id="metric-ws">0</strong><small class="stat-side-value" title="Established"><span
|
||||
data-i18n="wsEstablished">Established</span> <b id="metric-ws-total">0</b></small></div><small
|
||||
aria-label="Active WebSocket tunnels by frontend protocol"><span data-i18n="wsH1" title="H1 Upgrade">H1</span>
|
||||
data-ui-icon-name="none" id="tunnels-open" type="button">Active tunnels</button>
|
||||
<div class="stat-value-row"><strong id="metric-ws">0</strong><small class="stat-side-value"
|
||||
title="Established"><span data-i18n="wsEstablished">Established</span> <b id="metric-ws-total">0</b></small>
|
||||
</div><small aria-label="Active WebSocket tunnels by frontend protocol"><span data-i18n="wsH1"
|
||||
title="H1 Upgrade">H1</span>
|
||||
<span id="metric-ws-h1">0</span> · <span data-i18n="wsH2Rfc8441" title="H2 RFC 8441">H2</span>
|
||||
<span id="metric-ws-h2">0</span> · <span data-i18n="wsH3Rfc9220" title="H3 RFC 9220">H3</span>
|
||||
<span id="metric-ws-h3">0</span></small></article>
|
||||
<span id="metric-ws-h3">0</span></small>
|
||||
</article>
|
||||
<article class="stat" data-dashboard-widget="http2"><span data-i18n="h2Requests">HTTP/2
|
||||
requests</span><strong id="metric-h2">0</strong><small><span data-i18n="h2ActiveConnections">H2
|
||||
connections</span>: <span id="metric-h2-active">0</span></small></article>
|
||||
@@ -136,7 +141,8 @@
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong id="docker-dashboard-requests">-</strong>
|
||||
<svg preserveAspectRatio="none" data-i18n-aria="dockerWidgetRequests" role="img" viewBox="0 0 300 60">
|
||||
<path class="chart-grid" d="M0 15H300 M0 30H300 M0 45H300"></path>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line" points="0,55 300,55"></polyline>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line" points="0,55 300,55">
|
||||
</polyline>
|
||||
</svg><small id="docker-dashboard-requests-detail" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_host_network" hidden>
|
||||
@@ -168,10 +174,12 @@
|
||||
<small id="docker-dashboard-apps-detail-i2" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_requests_2" hidden>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong id="docker-dashboard-requests-i2">-</strong>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong
|
||||
id="docker-dashboard-requests-i2">-</strong>
|
||||
<svg preserveAspectRatio="none" data-i18n-aria="dockerWidgetRequests" role="img" viewBox="0 0 300 60">
|
||||
<path class="chart-grid" d="M0 15H300 M0 30H300 M0 45H300"></path>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i2" points="0,55 300,55"></polyline>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i2" points="0,55 300,55">
|
||||
</polyline>
|
||||
</svg><small id="docker-dashboard-requests-detail-i2" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_host_network_2" hidden>
|
||||
@@ -203,10 +211,12 @@
|
||||
<small id="docker-dashboard-apps-detail-i3" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_requests_3" hidden>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong id="docker-dashboard-requests-i3">-</strong>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong
|
||||
id="docker-dashboard-requests-i3">-</strong>
|
||||
<svg preserveAspectRatio="none" data-i18n-aria="dockerWidgetRequests" role="img" viewBox="0 0 300 60">
|
||||
<path class="chart-grid" d="M0 15H300 M0 30H300 M0 45H300"></path>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i3" points="0,55 300,55"></polyline>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i3" points="0,55 300,55">
|
||||
</polyline>
|
||||
</svg><small id="docker-dashboard-requests-detail-i3" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_host_network_3" hidden>
|
||||
@@ -238,10 +248,12 @@
|
||||
<small id="docker-dashboard-apps-detail-i4" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_requests_4" hidden>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong id="docker-dashboard-requests-i4">-</strong>
|
||||
<span data-i18n="dockerWidgetRequests">Docker app requests</span><strong
|
||||
id="docker-dashboard-requests-i4">-</strong>
|
||||
<svg preserveAspectRatio="none" data-i18n-aria="dockerWidgetRequests" role="img" viewBox="0 0 300 60">
|
||||
<path class="chart-grid" d="M0 15H300 M0 30H300 M0 45H300"></path>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i4" points="0,55 300,55"></polyline>
|
||||
<polyline class="diagnostic-line proto-h2-line" id="docker-dashboard-requests-line-i4" points="0,55 300,55">
|
||||
</polyline>
|
||||
</svg><small id="docker-dashboard-requests-detail-i4" data-i18n="dockerWidgetUnavailable">No Docker agents</small>
|
||||
</article>
|
||||
<article class="stat stat-chart" data-dashboard-widget="docker_host_network_4" hidden>
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
rules: [{ id: "root", enabled: true, source_scheme: "any", match_type: "prefix", path_prefix: "/", target_type: "url", target: "https://example.com/", target_scheme: "preserve", path_mode: "append", query_mode: "preserve", status_code: 308, cache_seconds: 0 }]
|
||||
});
|
||||
|
||||
// ---- Editor tabs -------------------------------------------------------
|
||||
function activateTab(name) {
|
||||
for (const node of $("redirect-tabs").querySelectorAll("button[data-tab]")) { const on = node.dataset.tab === name; node.classList.toggle("active", on); node.setAttribute("aria-pressed", String(on)); }
|
||||
for (const group of $("redirect-fields").querySelectorAll(".vh-group[data-tab]")) group.hidden = group.dataset.tab !== name;
|
||||
@@ -29,7 +28,6 @@
|
||||
}
|
||||
const activeTab = () => $("redirect-tabs").querySelector("button.active")?.dataset.tab || "details";
|
||||
|
||||
// ---- Rule rows: one line of the rule table, expanded = When / Where ----
|
||||
const ruleBoxes = () => [...rules.querySelectorAll('[data-redirect-rule="1"]')];
|
||||
const nextRuleId = base => { const used = new Set(ruleBoxes().map(box => box.querySelector('[data-field="id"]').value.trim())); if (!used.has(base)) return base; let index = 2; while (used.has(`${base}-${index}`)) index++; return `${base}-${index}`; };
|
||||
function addRule(rule = {}, open = false) {
|
||||
@@ -50,7 +48,6 @@
|
||||
const sourceScheme = select(whenGrid, "redirectSourceScheme", "source_scheme", [["any", "redirectSchemeAny"], ["http", "redirectSchemeHttp"], ["https", "redirectSchemeHttps"]]); sourceScheme.value = data.source_scheme;
|
||||
const matchType = select(whenGrid, "redirectMatchType", "match_type", [["prefix", "redirectMatchPrefix"], ["exact", "redirectMatchExact"]]); matchType.value = data.match_type;
|
||||
const prefix = input(whenGrid, "redirectSourcePath", "path_prefix", "text", "vh-wide"); prefix.required = true; prefix.maxLength = 512; prefix.value = data.path_prefix; prefix.spellcheck = false;
|
||||
// Target type as three choice cards; the radio group carries data-field="target_type".
|
||||
const choices = el("div", undefined, "vh-wide vh-www-choices redirect-target-choices"); choices.setAttribute("role", "radiogroup"); choices.setAttribute("aria-label", t("redirectTargetType"));
|
||||
const kindInputs = [];
|
||||
for (const [kind, key, helpKey] of [["url", "redirectTargetUrl", "redirectTargetUrlHelp"], ["host", "redirectTargetHost", "redirectTargetHostHelp"], ["path", "redirectTargetPath", "redirectTargetPathHelp"]]) {
|
||||
@@ -115,7 +112,6 @@
|
||||
return { id: get("id").value.trim(), enabled: get("enabled").checked, source_scheme: get("source_scheme").value, match_type: get("match_type").value, path_prefix: get("path_prefix").value.trim(), target_type: kindOf(box), target: get("target").value.trim(), target_scheme: get("target_scheme").value, path_mode: get("path_mode").value, query_mode: get("query_mode").value, status_code: Number(get("status_code").value), cache_seconds: Number(get("cache_seconds").value) || 0 };
|
||||
}
|
||||
|
||||
// ---- Rule templates (only pre-fill ordinary fields) ---------------------
|
||||
const firstExactHost = () => { try { return readRedirectHosts().find(host => !host.startsWith("*")) || ""; } catch { return ""; } };
|
||||
function showTemplates(open) { $("redirect-rule-templates").hidden = !open; $("redirect-rule-add").setAttribute("aria-expanded", String(open)); }
|
||||
function buildTemplates() {
|
||||
@@ -132,7 +128,6 @@
|
||||
template("redirectTplBlank", "redirectTplBlankHelp", () => ({ id: nextRuleId(`rule-${ruleBoxes().length + 1}`) }));
|
||||
}
|
||||
|
||||
// ---- Draft tester: mirrors src/redirect/mod.rs matching and Location ---
|
||||
function routingPath(raw) {
|
||||
if (!raw.startsWith("/")) return null;
|
||||
const bytes = [], source = new TextEncoder().encode(raw);
|
||||
@@ -271,7 +266,6 @@
|
||||
return { id, name, enabled: yes("redirect-enabled"), http2_enabled: yes("redirect-http2"), http3_enabled: yes("redirect-http3"), frontend: { hosts, listener_ids }, certificate_id: value("redirect-certificate") || null, rules: values };
|
||||
}
|
||||
|
||||
// ---- List --------------------------------------------------------------
|
||||
function listenerLabel(id) {
|
||||
const endpoint = (envelope?.config.listeners?.endpoints || []).find(item => item.id === id);
|
||||
if (!endpoint) return id;
|
||||
@@ -345,6 +339,6 @@
|
||||
$("redirect-close").addEventListener("click", closeEditor); $("redirect-reset").addEventListener("click", async () => { if (await allowDiscard()) load(editing ? structuredClone((envelope?.config.redirects || []).find(item => item.id === editing) || defaults()) : defaults()); });
|
||||
dialog.addEventListener("cancel", event => { event.preventDefault(); closeEditor(); });
|
||||
window.rustProxyDrafts.register("redirect", { labelKey: "redirects", isOpen: () => dialog.open, isDirty: () => dirty, suspend: suspendDraft, restore: restoreDraft, close: () => { dirty = false; if (dialog.open) dialog.close(); } });
|
||||
window.rustProxyRedirects = { render, applyPreferences, test: { routingPath, normalizeRule, ruleLocation, prefixMatches }, reset() { dialog.close(); editing = null; revision = null; dirty = false; listPrefs = { sort: "id", descending: false }; list.replaceChildren(); rules.replaceChildren(); $("redirect-search").value = ""; if ($("redirect-sort")) $("redirect-sort").value = listPrefs.sort; syncSortDirection(); } };
|
||||
window.rustProxyRedirects = { render, edit(id) { const item = (envelope?.config.redirects || []).find(entry => entry.id === id); if (!item) return false; window.rustProxyDrafts.prepare(); load(structuredClone(item)); return true; }, applyPreferences, test: { routingPath, normalizeRule, ruleLocation, prefixMatches }, reset() { dialog.close(); editing = null; revision = null; dirty = false; listPrefs = { sort: "id", descending: false }; list.replaceChildren(); rules.replaceChildren(); $("redirect-search").value = ""; if ($("redirect-sort")) $("redirect-sort").value = listPrefs.sort; syncSortDirection(); } };
|
||||
if (envelope) render();
|
||||
})();
|
||||
@@ -108,7 +108,6 @@
|
||||
button.addEventListener("keydown", event => { const index = cacheTabs.indexOf(button); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % cacheTabs.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + cacheTabs.length - 1) % cacheTabs.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = cacheTabs.length - 1; else return; event.preventDefault(); selectCacheTab(cacheTabs[next].dataset.cacheSettingsTab, true); });
|
||||
}
|
||||
selectCacheTab("general");
|
||||
// ---- Visual flows (cache request, transformation) ----------------------
|
||||
const FLOW_ICONS = {
|
||||
client: '<rect x="3" y="4" width="18" height="13" rx="1"/><path d="M3 8h18M8 21h8"/>',
|
||||
rules: '<path d="M4 6h16M7 12h10M10 18h4"/>',
|
||||
@@ -171,7 +170,6 @@
|
||||
box.replaceChildren(...steps.map(([title, line, tone]) => { const step = el("div", undefined, `settings-timeline-step is-${tone}`); step.append(el("b", title.startsWith("cache") ? t(title) : title), el("small", line.startsWith("cache") ? t(line) : line)); return step; }));
|
||||
}
|
||||
$("cache-form")?.addEventListener("input", renderCacheFlow); $("cache-form")?.addEventListener("change", renderCacheFlow);
|
||||
// Outputs below are what the built-in minifiers really produce for these inputs.
|
||||
const TRANSFORM_EXAMPLES = {
|
||||
javascript: ["app.js", "function greet ( name ) {\n // greeting\n return \"Hello, \" + name ;\n}", "function greet ( name ) {\n // greeting\n return \"Hello, \" + name ;\n}"],
|
||||
css: ["site.css", ".button {\n color : #ffffff ;\n /* spacing */\n margin : 0 auto ;\n}", ".button{color :#ffffff;margin :0 auto;}"],
|
||||
@@ -210,9 +208,6 @@
|
||||
$("transform-form")?.addEventListener("input", renderTransformFlow); $("transform-form")?.addEventListener("change", renderTransformFlow);
|
||||
window.rustProxySettingsFlow = { renderFlow, flowText, renderCache: renderCacheFlow, renderTransform: renderTransformFlow, num, on, mib };
|
||||
renderTransformFlow();
|
||||
// Security page: summary tiles, default-decision cards and a client-side
|
||||
// simulator that mirrors src/acl.rs (any matching deny wins, then any
|
||||
// matching allow, otherwise the default; IPv4-mapped IPv6 is treated as IPv4).
|
||||
function renderSecuritySummary() {
|
||||
const box = $("security-summary"); if (!box) return;
|
||||
const tokens = $("api-token-list")?.querySelectorAll(".certificate-api-credential-item") || [];
|
||||
@@ -303,9 +298,6 @@
|
||||
let guideIsLocal = false;
|
||||
function openCacheGuide(trigger) {
|
||||
if (!cacheGuideDialog) return;
|
||||
// One guide serves the static global editor and both dynamic vhost editors.
|
||||
// Keep its destination tied to the button that opened it; never silently
|
||||
// insert a vhost example into global rules or vice versa.
|
||||
guideEditor = trigger?.closest(".cache-rules") || $("cache-rules-root")?.querySelector(".cache-rules") || null;
|
||||
guideIsLocal = guideEditor?.classList.contains("cache-rules-vhost") === true;
|
||||
const isDocker = guideIsLocal && !!guideEditor.closest(".docker-cache-editor");
|
||||
@@ -323,8 +315,6 @@
|
||||
$("cache-guide-scope-note").textContent = t(isDocker ? "cacheGuideScopeDocker" : guideIsLocal ? "cacheGuideScopeVhost" : "cacheGuideScopeGlobal");
|
||||
if (!cacheGuideDialog.open) cacheGuideDialog.showModal();
|
||||
}
|
||||
// Event delegation is needed: the ordinary vhost dialog and the Docker
|
||||
// service editors are created after settings.js has registered its events.
|
||||
document.addEventListener("click", event => {
|
||||
const button = event.target.closest?.(".cache-guide-trigger");
|
||||
if (!button) return;
|
||||
@@ -338,7 +328,6 @@
|
||||
const editor = importer?.querySelector("textarea");
|
||||
if (!source || !editor) { toast(t("cacheGuideImporterUnavailable"), true); return; }
|
||||
editor.value = [editor.value.trim(), source].filter(Boolean).join("\n\n");
|
||||
// Invalidates any pending partial-import preview from an older source.
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
importer.hidden = false;
|
||||
cacheGuideDialog.close();
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
if (type === "checkbox") label.append(input, text("span", key)); else label.append(text("span", key), input);
|
||||
parent.append(label); return input;
|
||||
};
|
||||
// Live metrics of the edited stream are shown in its Backends tab, not between the title and the tabs.
|
||||
const setStreamLive = value => { $("stream-live-summary").textContent = value; const tab = $("stream-live-summary-tab"); if (tab) { tab.textContent = value; tab.hidden = !value; } };
|
||||
const group = (key, tab) => { const box = el("fieldset", undefined, "vh-group"); box.dataset.tab = tab; box.append(text("legend", key)); const body = el("div", undefined, "vh-grid"); box.append(body); container.append(box); return body; };
|
||||
const note = (parent, key) => parent.append(text("p", key, "fine vh-wide"));
|
||||
@@ -74,8 +73,6 @@
|
||||
health: { mode: "off", interval_seconds: 10, timeout_ms: 1000, rise: 2, fall: 2, payload_hex: "", expect_hex: null }
|
||||
});
|
||||
let backendList = null, healthList = null;
|
||||
// One backend = one routing-table row (summary) with its connection fields;
|
||||
// its health check lives in the Health tab and is linked through row._health.
|
||||
function renderBackendEditor(parent, backend, protocol, open = false) {
|
||||
if (backendList?.children.length >= 32) { toast(t("streamBackendLimit"), true); return; }
|
||||
const row = el("details", undefined, "vh-location stream-backend-row"); row.open = open;
|
||||
@@ -257,7 +254,6 @@
|
||||
}
|
||||
function closeEditor() { if (dirty) return window.rustProxyDrafts.dock("stream"); if (dialog.open) dialog.close(); return true; }
|
||||
|
||||
// Status JSON from the server is key-sorted; compare structures, not key order.
|
||||
const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value ?? null);
|
||||
function liveState(stream, status = latestStatus) {
|
||||
const streamStatus = status?.streams || {}, live = (streamStatus.active || []).find(item => item.id === stream.id);
|
||||
|
||||
@@ -44,72 +44,104 @@
|
||||
|
||||
function renderDonut(id, entries, enabled = true) {
|
||||
const chart = $(`traffic-chart-${id}`), legend = $(`traffic-chart-${id}-legend`), totalNode = $(`traffic-chart-${id}-total`);
|
||||
if (!chart || !legend || !totalNode) return;
|
||||
if (!chart || !legend) return;
|
||||
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled);
|
||||
const total = values.reduce((sum, item) => sum + Number(item.count || 0), 0);
|
||||
totalNode.textContent = number(total); if (empty) empty.hidden = total > 0;
|
||||
if (totalNode) totalNode.textContent = number(total); if (empty) empty.hidden = total > 0;
|
||||
if (!total) {
|
||||
chart.style.background = "var(--chart-surface)"; chart.setAttribute("aria-label", t("trafficNoData"));
|
||||
chart.replaceChildren(); chart.classList.add("is-empty"); chart.setAttribute("aria-label", t("trafficNoData"));
|
||||
legend.replaceChildren(el("li", t("trafficNoData"), "fine")); return;
|
||||
}
|
||||
chart.classList.remove("is-empty");
|
||||
const shown = values.slice(0, 7).map(item => ({ value: item.value || "-", count: Number(item.count) || 0 }));
|
||||
if (values.length > shown.length) shown.push({ value: t("trafficOther"), count: values.slice(shown.length).reduce((sum, item) => sum + Number(item.count || 0), 0) });
|
||||
let cursor = 0;
|
||||
chart.style.background = `conic-gradient(${shown.map((item, index) => {
|
||||
const start = cursor / total * 100; cursor += item.count; const end = cursor / total * 100;
|
||||
return `${chartPalette[index % chartPalette.length]} ${start.toFixed(4)}% ${end.toFixed(4)}%`;
|
||||
}).join(", ")})`;
|
||||
if (values.length > shown.length) shown.push({ value: t("trafficOther"), count: values.slice(shown.length).reduce((sum, item) => sum + Number(item.count || 0), 0), other: true });
|
||||
chart.replaceChildren(...shown.map((item, index) => {
|
||||
const part = el("i"); part.style.width = `${(item.count / total * 100).toFixed(3)}%`; part.style.background = chartPalette[index % chartPalette.length];
|
||||
part.title = `${item.value}: ${number(item.count)} (${(item.count / total * 100).toFixed(1)}%)`; return part;
|
||||
}));
|
||||
const heading = chart.closest(".traffic-chart-card")?.querySelector("h3")?.textContent || t("trafficDimensionsTitle");
|
||||
chart.setAttribute("aria-label", `${heading}: ${shown.map(item => `${item.value} ${Math.round(item.count / total * 100)}%`).join(", ")}`);
|
||||
legend.replaceChildren(...shown.map((item, index) => {
|
||||
const row = el("li"), label = el("span"), swatch = el("i", undefined, "traffic-chart-swatch");
|
||||
swatch.style.background = chartPalette[index % chartPalette.length];
|
||||
const text = copyButton(item.value || "-", "traffic-chart-label"); text.title = `${t("copyValue")}: ${item.value || "-"}`;
|
||||
label.append(swatch, text); row.append(label, el("b", `${(item.count / total * 100).toFixed(1)}%`)); return row;
|
||||
const text = item.other ? el("span", item.value, "traffic-chart-label") : copyButton(item.value || "-", "traffic-chart-label"); if (!item.other) text.title = `${t("copyValue")}: ${item.value || "-"}`;
|
||||
label.append(swatch, text); row.append(label, el("b", number(item.count)), el("span", `${(item.count / total * 100).toFixed(1)}%`, "traffic-share")); return row;
|
||||
}));
|
||||
}
|
||||
|
||||
function renderBars(id, entries, enabled = true, formatter = number) {
|
||||
function renderBars(id, entries, enabled = true, formatter = number, options = {}) {
|
||||
const chart = $(`traffic-chart-${id}`); if (!chart) return;
|
||||
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled).slice(0, 12);
|
||||
const total = values.reduce((sum, item) => sum + Number(item.count || 0), 0), peak = Math.max(1, ...values.map(item => Number(item.count) || 0));
|
||||
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled).slice(0, options.limit || 12);
|
||||
const listed = values.reduce((sum, item) => sum + Number(item.count || 0), 0), peak = Math.max(1, ...values.map(item => Number(item.count) || 0));
|
||||
const total = Math.max(listed, Number(options.share) || 0);
|
||||
if (empty) empty.hidden = values.length > 0;
|
||||
chart.replaceChildren(...values.map(item => {
|
||||
const count = Number(item.count) || 0, row = el("div", undefined, "traffic-bar-row");
|
||||
const label = copyButton(item.value || "-", "traffic-bar-label"); label.title = `${t("copyValue")}: ${item.value || "-"}`;
|
||||
const track = el("span", undefined, "traffic-bar-track"), fill = el("i", undefined, "traffic-bar-fill"); fill.style.width = `${Math.max(1.5, count / peak * 100)}%`; track.append(fill);
|
||||
const value = el("span", formatter(count), "traffic-bar-value"); value.title = total ? `${(count / total * 100).toFixed(1)}%` : "";
|
||||
row.append(label, track, value); return row;
|
||||
const rows = values.map(item => ({ value: item.value || "-", count: Number(item.count) || 0 }));
|
||||
if (options.share && values.length && total > listed) rows.push({ value: t("trafficOther"), count: total - listed, other: true });
|
||||
chart.replaceChildren(...rows.map(item => {
|
||||
const count = item.count, row = el("div", undefined, `traffic-bar-row${item.other ? " is-other" : ""}`);
|
||||
const label = item.other ? el("span", item.value, "traffic-bar-label") : copyButton(item.value, "traffic-bar-label"); if (!item.other) label.title = `${t("copyValue")}: ${item.value}`;
|
||||
const track = el("span", undefined, "traffic-bar-track"), fill = el("i", undefined, "traffic-bar-fill"); fill.style.width = `${Math.max(1.5, Math.min(100, count / (item.other ? total : peak) * 100))}%`; track.append(fill);
|
||||
const value = el("span", formatter(count), "traffic-bar-value"), share = el("span", total ? `${(count / total * 100).toFixed(1)}%` : "", "traffic-share");
|
||||
row.append(label, value, share, track); return row;
|
||||
}));
|
||||
chart.setAttribute("aria-label", values.length ? values.map(item => `${item.value}: ${formatter(Number(item.count) || 0)}`).join(", ") : t("trafficNoData"));
|
||||
}
|
||||
|
||||
function renderCapture(settings, geoip) {
|
||||
const box = $("traffic-capture-status"); if (!box) return;
|
||||
const pill = (key, on) => { const node = el("span", t(key), `pill${on ? " live" : ""}`); node.dataset.i18n = key; return node; };
|
||||
const country = settings.capture_country ? (geoip?.loaded ? ["trafficCountryEnabled", true] : ["trafficCountryNoDb", false]) : ["trafficCountryDisabled", false];
|
||||
const open = el("button", t("trafficOpenCaptureSettings"), "quiet traffic-capture-open"); open.type = "button"; open.dataset.i18n = "trafficOpenCaptureSettings"; open.dataset.trafficOpenSettings = "logging"; open.dataset.uiIconName = "settings"; open.addEventListener("click", openCaptureSettings);
|
||||
box.replaceChildren(pill(settings.capture_user_agent ? "trafficUserAgentEnabled" : "trafficUserAgentDisabled", !!settings.capture_user_agent), pill(country[0], country[1]), open);
|
||||
}
|
||||
function openCaptureSettings() { setPanel("settings"); window.rustProxySettings?.select("logging"); }
|
||||
|
||||
function render(data) {
|
||||
lastData = data; configure(data);
|
||||
const analytics = data.analytics || {}, stats = analytics.data || {}, settings = data.settings || {};
|
||||
$("traffic-requests").textContent = number(stats.requests); $("traffic-errors").textContent = number(stats.errors);
|
||||
const requests = Number(stats.requests) || 0, errors = Number(stats.errors) || 0;
|
||||
$("traffic-error-ratio").textContent = `${requests ? (errors / requests * 100).toFixed(2) : "0.00"}%`;
|
||||
$("traffic-error-ratio").textContent = `${requests ? (errors / requests * 100).toFixed(2) : "0.00"}% ${t("trafficOfRequests")}`;
|
||||
$("traffic-response-bytes").textContent = fmtBytes(Number(stats.response_bytes) || 0);
|
||||
$("traffic-request-bytes").textContent = `${t("trafficRequestBytes")}: ${fmtBytes(Number(stats.request_bytes) || 0)}`;
|
||||
$("traffic-latency").textContent = stats.mean_duration_ms == null ? "-" : `${fmt(stats.mean_duration_ms, 2)} ms`;
|
||||
$("traffic-dropped").textContent = `${t("trafficDroppedSamples")}: ${number(analytics.queue_dropped)}`;
|
||||
const capture = [settings.capture_user_agent ? t("trafficUserAgentEnabled") : t("trafficUserAgentDisabled")];
|
||||
capture.push(settings.capture_country ? (data.geoip?.loaded ? t("trafficCountryEnabled") : t("trafficCountryNoDb")) : t("trafficCountryDisabled"));
|
||||
$("traffic-capture-status").textContent = capture.join(" · ");
|
||||
$("traffic-dropped").textContent = number(analytics.queue_dropped);
|
||||
$("traffic-dropped-help").textContent = Number(analytics.queue_dropped) ? t("trafficDroppedSome") : t("trafficDroppedNone");
|
||||
document.querySelector(".traffic-kpi-errors")?.classList.toggle("is-warn", errors > 0);
|
||||
renderCapture(settings, data.geoip);
|
||||
|
||||
renderDonut("countries", stats.countries, !!settings.capture_country);
|
||||
renderBars("user-agents", stats.user_agents, !!settings.capture_user_agent);
|
||||
renderBars("client-ips", stats.client_ips);
|
||||
renderBars("paths", stats.paths); renderBars("routes", stats.routes);
|
||||
const share = requests;
|
||||
renderBars("countries", stats.countries, !!settings.capture_country, number, { share });
|
||||
const countryEmpty = $("traffic-chart-countries-empty"); if (countryEmpty) countryEmpty.hidden = chartEntries(stats.countries, !!settings.capture_country).length > 0;
|
||||
renderBars("user-agents", stats.user_agents, !!settings.capture_user_agent, number, { share });
|
||||
renderBars("client-ips", stats.client_ips, true, number, { share });
|
||||
renderBars("client-ips-overview", stats.client_ips, true, number, { share, limit: 5 });
|
||||
renderBars("paths", stats.paths, true, number, { share }); renderBars("paths-overview", stats.paths, true, number, { share, limit: 5 });
|
||||
renderBars("routes", stats.routes, true, number, { share });
|
||||
renderDonut("methods", stats.methods); renderDonut("methods-detail", stats.methods);
|
||||
renderDonut("statuses", stats.statuses); renderDonut("statuses-detail", stats.statuses);
|
||||
renderDonut("cache", stats.cache); renderDonut("cache-detail", stats.cache);
|
||||
renderBars("volume", [
|
||||
{ value: t("trafficRequestBytes"), count: Number(stats.request_bytes) || 0 },
|
||||
{ value: t("trafficResponseBytes"), count: Number(stats.response_bytes) || 0 },
|
||||
{ value: t("trafficRequestBytes"), count: Number(stats.request_bytes) || 0 },
|
||||
], true, fmtBytes);
|
||||
$("traffic-panel-state").textContent = `${t("trafficUpdated")}: ${formatTime(new Date())}`;
|
||||
renderRecent();
|
||||
}
|
||||
|
||||
const RECENT_KEY = "rustproxy.traffic.recent";
|
||||
function readRecent() { try { const value = JSON.parse(localStorage.getItem(RECENT_KEY) || "[]"); return Array.isArray(value) ? value.filter(item => typeof item === "string").slice(0, 3) : []; } catch { return []; } }
|
||||
function rememberScope(value) { if (!value || value === "*") return; try { localStorage.setItem(RECENT_KEY, JSON.stringify([value, ...readRecent().filter(item => item !== value)].slice(0, 3))); } catch { } }
|
||||
function renderRecent() {
|
||||
const box = $("traffic-recent"); if (!box) return;
|
||||
const select = $("traffic-scope"), known = new Set([...select.options].map(option => option.value));
|
||||
const chips = ["*", ...readRecent().filter(value => known.has(value))].map(value => {
|
||||
const chip = el("button", value === "*" ? t("logAllVhosts") : value, "traffic-recent-chip"); chip.type = "button"; chip.dataset.uiIconName = "none";
|
||||
chip.setAttribute("aria-pressed", String(select.value === value));
|
||||
chip.addEventListener("click", () => { if (select.value === value) return; select.value = value; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
return chip;
|
||||
});
|
||||
box.replaceChildren(...(chips.length > 1 ? chips : []));
|
||||
}
|
||||
|
||||
async function loadTraffic({ signal, isCurrent }) {
|
||||
@@ -121,8 +153,6 @@
|
||||
try {
|
||||
data = await api(staticData ? `${base}&view=live` : base, { signal });
|
||||
} catch (error) {
|
||||
// Labels are inventory-derived. If the selected publication
|
||||
// vanished, fall back to All rather than polling a stale ID.
|
||||
if (error?.status !== 404 || scope() === "*") throw error;
|
||||
$("traffic-scope").value = "*";
|
||||
staticData = null; staticRevision = null;
|
||||
@@ -149,7 +179,7 @@
|
||||
document.querySelectorAll(".traffic-bar-chart").forEach(chart => chart.replaceChildren());
|
||||
for (const id of ["countries", "methods", "methods-detail", "statuses", "statuses-detail", "cache", "cache-detail"]) {
|
||||
const chart = $(`traffic-chart-${id}`), legend = $(`traffic-chart-${id}-legend`), total = $(`traffic-chart-${id}-total`);
|
||||
if (chart) chart.style.background = "var(--chart-surface)"; legend?.replaceChildren(); if (total) total.textContent = "-";
|
||||
chart?.replaceChildren(); legend?.replaceChildren(); if (total) total.textContent = "-";
|
||||
}
|
||||
selectTab("overview");
|
||||
}
|
||||
@@ -165,8 +195,10 @@
|
||||
event.preventDefault(); selectTab(trafficTabs[next].dataset.trafficTab); trafficTabs[next].focus();
|
||||
});
|
||||
});
|
||||
$("traffic-refresh")?.addEventListener("click", () => void refresh()); $("traffic-scope")?.addEventListener("change", () => void refresh());
|
||||
$("traffic-settings")?.addEventListener("click", () => { setPanel("settings"); window.rustProxySettings?.select("logging"); });
|
||||
$("traffic-refresh")?.addEventListener("click", () => void refresh()); $("traffic-scope")?.addEventListener("change", () => { rememberScope($("traffic-scope").value); renderRecent(); void refresh(); });
|
||||
$("traffic-settings")?.addEventListener("click", openCaptureSettings);
|
||||
document.querySelectorAll("[data-traffic-more]").forEach(button => button.addEventListener("click", () => selectTab(button.dataset.trafficMore)));
|
||||
document.querySelectorAll("#panel-traffic button[data-traffic-open-settings]").forEach(button => button.addEventListener("click", openCaptureSettings));
|
||||
rustProxyRefresh.register("traffic", {
|
||||
interval: () => rustProxyRefresh.current().traffic_seconds,
|
||||
active: () => currentPanel === "traffic" && !!$("traffic-live")?.checked,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Load-balancing editor (vhost and location) with a consistent-hash distribution
|
||||
// simulator. The pure helpers at the top mirror src/balance/model.rs (rendezvous
|
||||
// scoring and hash keys); keep them in step with tests/fixtures/balance_rendezvous_vectors.txt.
|
||||
const lbSha256 = (() => {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
@@ -32,7 +29,6 @@ const lbSha256 = (() => {
|
||||
})();
|
||||
const lbEncoder = new TextEncoder();
|
||||
const LB_U64_SPAN = Number(2n ** 64n - 1n) + 2, LB_MIN_POSITIVE = 2.2250738585072014e-308;
|
||||
// Same as rendezvous_score() in src/balance/model.rs: lowest score wins.
|
||||
function lbScore(poolId, key, memberId, weight) {
|
||||
const digest = lbSha256(lbEncoder.encode(`${poolId}|${key}|${memberId}`));
|
||||
let n = 0n; for (let i = 0; i < 8; i++) n = (n << 8n) | BigInt(digest[i]);
|
||||
@@ -47,7 +43,6 @@ function lbPathDepth(path, depth) {
|
||||
for (let i = 1; i < path.length; i++) if (path[i] === "/" && ++seen === depth) return path.slice(0, i);
|
||||
return path;
|
||||
}
|
||||
// Parses one simulator sample: "/path?query", "https://host/path?query" or "host/path".
|
||||
function lbParseSample(line) {
|
||||
let rest = line.trim(), host = "";
|
||||
const scheme = rest.match(/^[a-z][a-z0-9+.-]*:\/\//i);
|
||||
@@ -59,7 +54,6 @@ function lbParseSample(line) {
|
||||
host = bracketed ? bracketed[1] : host.includes(":") && host.indexOf(":") === host.lastIndexOf(":") ? host.replace(/:\d*$/, "") : host;
|
||||
return { host: host.replace(/\.$/, "").toLowerCase(), path: mark < 0 ? rest : rest.slice(0, mark), query: mark < 0 ? null : rest.slice(mark + 1) };
|
||||
}
|
||||
// Mirrors HashSettings::key(); header/cookie/IP samples are the raw value itself.
|
||||
function lbHashKey(settings, line) {
|
||||
const source = settings.source || "path", value = String(line).trim(); if (!value) return null;
|
||||
if (source === "ip") return value;
|
||||
@@ -79,8 +73,6 @@ function lbHashKey(settings, line) {
|
||||
if (!key) return null;
|
||||
return settings.ignore_case ? key.toLowerCase() : key;
|
||||
}
|
||||
// Which members a request may use (mirrors candidates: enabled, not draining, backups
|
||||
// only when no primary is left).
|
||||
function lbEligible(members, explicit, down = new Set()) {
|
||||
const usable = members.filter(m => m.enabled && !m.drain && (explicit || m.pool_eligible) && !down.has(m.id));
|
||||
return usable.some(m => !m.backup) ? usable.filter(m => !m.backup) : usable;
|
||||
@@ -106,7 +98,6 @@ const LB_PRESETS = [
|
||||
{ key: "lbPresetIp", algorithm: "hash", hash: { source: "ip" }, samples: "203.0.113.10\n203.0.113.11\n198.51.100.7\n2001:db8::42" },
|
||||
{ key: "lbPresetEven", algorithm: "least_connections", hash: {} }
|
||||
];
|
||||
// HAProxy-style one-liner describing the configuration (helps people migrating).
|
||||
function lbHaproxyLine(algorithm, hash) {
|
||||
const map = { round_robin: "balance roundrobin", least_connections: "balance leastconn", random: "balance random(2)", ip_hash: "balance source\nhash-type consistent" };
|
||||
if (map[algorithm]) return map[algorithm];
|
||||
@@ -117,9 +108,6 @@ function lbHaproxyLine(algorithm, hash) {
|
||||
return `${source}\nhash-type consistent${Number(hash.balance_factor) ? `\nhash-balance-factor ${hash.balance_factor}` : ""}`;
|
||||
}
|
||||
|
||||
// Balancing editor. options: { names: input name prefix, value: {algorithm, hash, sticky},
|
||||
// members(): [{id, weight, enabled, drain, backup, pool_eligible}], explicit(): bool,
|
||||
// poolId(): string, stickyField: include a location affinity select, onChange() }.
|
||||
function balancingEditor(parent, options) {
|
||||
const value = options.value || {}, hash = { ...(value.hash || {}) }, prefix = options.names;
|
||||
const box = el("div", undefined, "vh-wide lb-editor"); parent.append(box);
|
||||
@@ -232,7 +220,6 @@ function balancingEditor(parent, options) {
|
||||
sync(); simulator.open = preset.algorithm === "hash"; if (simulator.open) simulate(); options.onChange?.();
|
||||
}, "quiet lb-preset"));
|
||||
}
|
||||
// The simulator is a scratch pad: its inputs never mark the vhost as changed.
|
||||
for (const type of ["input", "change"]) simulator.addEventListener(type, event => { event.stopPropagation(); if (event.target === samples) simulate(); });
|
||||
box.addEventListener("input", () => { sync(); options.onChange?.(); });
|
||||
box.addEventListener("change", () => { sync(); options.onChange?.(); });
|
||||
@@ -246,7 +233,6 @@ function balancingEditor(parent, options) {
|
||||
validate() { if (algorithm.value === "hash" && ["header", "cookie", "query"].includes(source.value) && !name.value.trim()) throw new Error(t("lbHashNameRequired")); }
|
||||
};
|
||||
}
|
||||
// Reads the vhost backend rows for the balancing editors and simulators.
|
||||
function balancingMembers() {
|
||||
return [...form.querySelectorAll(".vh-member")].map(row => ({
|
||||
id: str("member-id", row), weight: Number(str("member-weight", row)) || 1,
|
||||
|
||||
@@ -426,9 +426,6 @@ function openLocationHelp(topic = "locations") {
|
||||
}
|
||||
dialog.showModal();
|
||||
}
|
||||
// Error fallback = target internal location + the upstream statuses it handles.
|
||||
// The status chips write the legacy comma-separated "<prefix>-statuses" field,
|
||||
// so readers, JSON drawers and saved configuration keep their exact format.
|
||||
const ERROR_FALLBACK_STATUSES = [403, 404, 500, 502, 503, 504];
|
||||
let errorFallbackListId = 0;
|
||||
const internalLocationIds = () => [...form.querySelectorAll('.vh-location [name="location-internal"]')].filter(box => box.checked)
|
||||
@@ -452,7 +449,6 @@ function errorFallbackFields(parent, prefix, value, keys) {
|
||||
const write = () => { hidden.value = boxes.filter(input => input.checked).map(input => input.value).join(", "); };
|
||||
const sync = () => { const off = !target.value.trim(); box.classList.toggle("is-inactive", off); for (const input of boxes) input.disabled = off; };
|
||||
chips.addEventListener("change", event => {
|
||||
// At least one status stays selected; an empty list would silently mean 404.
|
||||
if (!boxes.some(input => input.checked)) event.target.checked = true;
|
||||
write(); hidden.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
@@ -463,7 +459,6 @@ function errorFallbackFields(parent, prefix, value, keys) {
|
||||
const LOCATION_GROUP = "__group__";
|
||||
function locationsEditor(parent, values, onChange = changed) {
|
||||
const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations");
|
||||
// "Add location" opens starting points; each one only pre-fills ordinary fields.
|
||||
const addMenu = el("div", undefined, "location-add-menu"), templates = el("div", undefined, "location-templates"); templates.hidden = true;
|
||||
const showTemplates = open => { templates.hidden = !open; addTop.setAttribute("aria-expanded", String(open)); };
|
||||
const addTop = button("locationAdd", () => showTemplates(templates.hidden), "primary"); addTop.setAttribute("aria-haspopup", "true"); addTop.setAttribute("aria-expanded", "false");
|
||||
@@ -522,7 +517,6 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; }
|
||||
const row = el("details", undefined, "vh-location"); row.open = open;
|
||||
const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body);
|
||||
// Collapsed row = one line of the routing table; expanded = When / What / Options.
|
||||
const sumOrder = el("span", String(rows.children.length + 1), "loc-order"), sumState = el("span", undefined, "loc-state"), sumId = el("span", "", "loc-id");
|
||||
const sumMatch = el("span", "", "loc-match"), sumPath = el("span", "", "loc-path"), sumAction = el("span", "", "loc-action"), sumChips = el("span", undefined, "loc-chips");
|
||||
sumState.setAttribute("role", "img"); summary.append(sumOrder, sumState, sumId, sumMatch, sumPath, sumAction, sumChips); row._order = sumOrder;
|
||||
@@ -722,7 +716,6 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
const headerValue = editor.read(), requestRules = headerValue.request?.length || 0, responseRules = headerValue.response?.length || 0;
|
||||
previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`; headerCount = requestRules + responseRules;
|
||||
} catch { previewValues.headers.textContent = t("headersInvalid"); }
|
||||
// Row summary, headline and option tab states.
|
||||
sumAction.textContent = actionText || "";
|
||||
const fallbackTarget = str("location-error-target", row), fallbackStatuses = str("location-error-statuses", row).replace(/\s+/g, "");
|
||||
const visualRules = policyBody.querySelector(".policy-visual:not([hidden]) .policy-rules"); if (visualRules) policyCount = visualRules.querySelectorAll(":scope > .policy-rule").length;
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
// Headers tab of the vhost editor: live preview of the headers RustProxy sends to the
|
||||
// backend and to the client, example values for %[variables] and diagnostic cards.
|
||||
const HEADER_VARIABLE_NAMES = new Set(HEADER_VARIABLES.map(([name]) => name));
|
||||
const HEADER_RESPONSE_ONLY = new Set(HEADER_VARIABLES.filter(([, only]) => only).map(([name]) => name));
|
||||
let headerExampleContext = { member: "", location: "main", cache: "MISS" };
|
||||
|
||||
// Example values for header variables, based on the draft (first eligible backend…).
|
||||
function headerExampleVars(context = headerExampleContext) {
|
||||
const members = (typeof balancingMembers === "function" ? balancingMembers() : []).filter(m => m.id);
|
||||
const member = members.find(m => m.id === context.member) || members.find(m => m.enabled && m.pool_eligible) || members[0];
|
||||
@@ -19,7 +16,6 @@ function headerExampleVars(context = headerExampleContext) {
|
||||
path: "/media/a.mp3", cache_status: context.cache, backend_time: hits ? "-" : "12.40ms"
|
||||
};
|
||||
}
|
||||
// Checks a header value and renders it with example variables.
|
||||
function headerValueCheck(value, direction, vars = headerExampleVars()) {
|
||||
const text = String(value ?? "");
|
||||
if (!text.includes("%[")) return { dynamic: false, rendered: text };
|
||||
@@ -34,7 +30,6 @@ function headerValueCheck(value, direction, vars = headerExampleVars()) {
|
||||
}
|
||||
return { dynamic: true, rendered: rendered + rest };
|
||||
}
|
||||
// Applies header rules to an ordered header list [{name, value, source, dynamic}].
|
||||
function headerApplyRules(list, rules, source, direction, vars, stage) {
|
||||
for (const rule of rules || []) {
|
||||
if (!rule?.name) continue;
|
||||
@@ -86,7 +81,6 @@ function headersPreview(parent) {
|
||||
cacheSelect.value = headerExampleContext.cache;
|
||||
const vars = headerExampleVars(), route = routes.find(r => r.id === headerExampleContext.location);
|
||||
const global = envelope?.config?.headers || {}, vhost = safe(() => vhostHeadersControl?.read()) || {}, location = route?.headers || {};
|
||||
// Request: static rules (global → vhost → location), then forwarding, then rules with variables.
|
||||
const request = [], requestVars = headerExampleVars({ ...headerExampleContext, cache: "MISS" });
|
||||
if (headerExampleContext.cache === "HIT") request.push({ name: t("hdrPreviewHitNoRequest"), value: undefined, source: "system", system: true });
|
||||
else for (const stage of ["static", "dynamic"]) {
|
||||
@@ -95,7 +89,6 @@ function headersPreview(parent) {
|
||||
headerApplyRules(request, vhost.request, "vhost", "request", requestVars, stage);
|
||||
headerApplyRules(request, location.request, "location", "request", requestVars, stage);
|
||||
}
|
||||
// Response: static rules, diagnostics and identity, then rules with variables.
|
||||
const response = [];
|
||||
headerApplyRules(response, global.response, "global", "response", vars, "static");
|
||||
headerApplyRules(response, vhost.response, "vhost", "response", vars, "static");
|
||||
@@ -121,7 +114,6 @@ function headersPreview(parent) {
|
||||
return { refresh };
|
||||
}
|
||||
|
||||
// One switch as a card that shows the header it produces.
|
||||
function diagnosticCard(parent, { name, key, checked, header, example, help, extra }) {
|
||||
const card = el("div", undefined, "hdr-card"), head = el("div", undefined, "hdr-card-head"); card.append(head);
|
||||
const input = field(head, name, key, checked, "checkbox", { switch: true });
|
||||
@@ -132,6 +124,5 @@ function diagnosticCard(parent, { name, key, checked, header, example, help, ext
|
||||
input.addEventListener("change", sync); sync(); parent.append(card); return input;
|
||||
}
|
||||
|
||||
// The preview follows every edit in the editor and the Headers tab button.
|
||||
for (const type of ["input", "change", "click"]) container.addEventListener(type, () => { headersPreviewControl?.refresh(); presetsRefresh(); });
|
||||
$("vhost-tabs").addEventListener("click", () => headersPreviewControl?.refresh());
|
||||
@@ -178,8 +178,6 @@ function syncVhostSortDirection() {
|
||||
control.setAttribute("aria-label", t(vhostListPrefs.descending ? "backendSortDescending" : "backendSortAscending"));
|
||||
}
|
||||
function applyPreferences(preferences) {
|
||||
// Updating backend columns should never reconstruct the unrelated Vhost list.
|
||||
// Keep any newer local column change while an earlier write is in flight.
|
||||
const nextPool = poolPreferenceSaveQueued ? poolTablePrefs : normalizePoolTablePrefs(preferences);
|
||||
const nextVhost = normalizeVhostListPrefs(preferences);
|
||||
const poolChanged = JSON.stringify(nextPool) !== JSON.stringify(poolTablePrefs);
|
||||
@@ -249,8 +247,6 @@ function applyPoolTableView() {
|
||||
const result = typeof a === "number" && typeof b === "number" ? a - b : compareText(a, b);
|
||||
return poolTablePrefs.descending ? -result : result;
|
||||
});
|
||||
// Retain rows that are already ordered correctly. A needless detach of a
|
||||
// focused/anchored table row can jump the page even when sorting is unchanged.
|
||||
let cursor = body.firstElementChild;
|
||||
for (const row of rows) {
|
||||
if (row === cursor) cursor = cursor.nextElementSibling;
|
||||
@@ -484,8 +480,6 @@ const BO_EXTRA_CELLS = {
|
||||
if (extra.h1 + extra.h2) cell.append(el("small", `H2 ${boPercent(extra.h2, extra.h1 + extra.h2)}`));
|
||||
},
|
||||
};
|
||||
// Keep filter buttons and keyed table rows mounted between live samples.
|
||||
// Replacing them every few seconds discards keyboard focus and browser scroll anchors.
|
||||
const BO_FILTERS = [["all", "backendFilterAll"], ["up", "vhUp"], ["down", "vhDown"], ["other", "backendFilterOther"]];
|
||||
function syncBackendOverviewFilters(filters, counts) {
|
||||
if (filters.getAttribute("aria-label") !== t("backendFilterLabel")) filters.setAttribute("aria-label", t("backendFilterLabel"));
|
||||
@@ -521,7 +515,6 @@ function syncBackendOverviewRows(body, rendered) {
|
||||
if (cell.colSpan !== updated.colSpan) cell.colSpan = updated.colSpan;
|
||||
if (updated.dataset.boColumn && cell.dataset.boColumn !== updated.dataset.boColumn) cell.dataset.boColumn = updated.dataset.boColumn;
|
||||
if (updated.dataset.boColumn === "toggle") {
|
||||
// The expansion control itself must survive refreshes, not just regain focus.
|
||||
const button = cell.querySelector("button"), nextButton = updated.querySelector("button");
|
||||
if (button && nextButton) {
|
||||
if (button.getAttribute("aria-expanded") !== nextButton.getAttribute("aria-expanded")) button.setAttribute("aria-expanded", nextButton.getAttribute("aria-expanded"));
|
||||
@@ -532,8 +525,6 @@ function syncBackendOverviewRows(body, rendered) {
|
||||
}
|
||||
return current;
|
||||
});
|
||||
// Do not detach rows already in the correct position: moving a focused row
|
||||
// needlessly also breaks the scroll anchor on some browsers.
|
||||
let cursor = body.firstElementChild;
|
||||
for (const row of rows) {
|
||||
if (row === cursor) cursor = cursor.nextElementSibling;
|
||||
@@ -628,8 +619,6 @@ function applyBackendOverviewView() {
|
||||
}
|
||||
const scroller = body.closest(".table-scroll"), scrollTop = scroller?.scrollTop ?? 0, scrollLeft = scroller?.scrollLeft ?? 0;
|
||||
syncBackendOverviewRows(body, rows);
|
||||
// Sorting or filtering can change the table height; preserve the user's
|
||||
// scroll position, but avoid forced layout for an untouched scroll offset.
|
||||
if (scroller && (scrollTop || scrollLeft)) { if (scroller.scrollTop !== scrollTop) scroller.scrollTop = scrollTop; if (scroller.scrollLeft !== scrollLeft) scroller.scrollLeft = scrollLeft; }
|
||||
if (hadFocus && document.activeElement?.dataset?.boKey !== focusKey) [...body.querySelectorAll(".bo-expand")].find(button => button.dataset.boKey === focusKey)?.focus({ preventScroll: true });
|
||||
const empty = $("bo-empty");
|
||||
@@ -996,7 +985,6 @@ function renderStatus(status) {
|
||||
const editingHasProxy = editingVhost && vhostRequiresProxy(editingVhost);
|
||||
$("vhost-health-live").hidden = !!editingVhost && !editingHasProxy;
|
||||
$("vhost-health-live").textContent = editing ? (editingHasProxy ? (summaries.get(editing) || t("vhHealthEmpty")) : "") : t("vhNewHealthHint");
|
||||
// The live line is shown inside the Backend health tab, not between the title and the tabs.
|
||||
const liveTab = $("vhost-health-live-tab"); if (liveTab) { liveTab.hidden = $("vhost-health-live").hidden; liveTab.textContent = $("vhost-health-live").textContent; }
|
||||
}
|
||||
form.addEventListener("input", changed); form.addEventListener("change", changed);
|
||||
@@ -1055,5 +1043,5 @@ $("pool-open").addEventListener("click", () => setPanel("vhosts"));
|
||||
initPoolTableTools();
|
||||
$("location-help-close")?.addEventListener("click", () => $("location-help-dialog")?.close());
|
||||
window.rustProxyDrafts.register("vhost", { labelKey: "vhosts", isOpen: () => dialog.open, isDirty: () => dirty, suspend: suspendDraft, restore: restoreDraft, close: () => { dirty = false; if (dialog.open) dialog.close(); } });
|
||||
window.rustProxyVhosts = { render, renderStatus, applyPreferences, flushOverviewViews, reset() { closeVhostBackendPopup(); dialog.close(); draftEpoch++; stagedCertificates = []; uploading = false; editing = null; revision = null; dirty = false; initialized = false; backendHealthEditorControl = null; poolTablePrefs = defaultPoolTablePrefs(); vhostListPrefs = defaultVhostListPrefs(); poolPreferenceSaveRunning = false; poolPreferenceSaveQueued = false; chartHistory.clear(); backendTrafficHistory.clear(); backendRequestHistory.clear(); vhostTrafficHistory.clear(); container.replaceChildren(); $("vhost-search").value = ""; if ($("pool-search")) $("pool-search").value = ""; $("vhost-list").replaceChildren(); $("pool-rows").replaceChildren(); const sort = $("pool-sort"); if (sort) sort.value = poolTablePrefs.sort; const vhostSort = $("vhost-sort"); if (vhostSort) vhostSort.value = vhostListPrefs.sort; syncVhostSortDirection(); applyPoolTableView(); } };
|
||||
window.rustProxyVhosts = { render, edit(id) { const item = (envelope?.config.vhosts || []).find(entry => entry.id === id); if (!item) return false; window.rustProxyDrafts.prepare(); load(structuredClone(item)); return true; }, renderStatus, applyPreferences, flushOverviewViews, reset() { closeVhostBackendPopup(); dialog.close(); draftEpoch++; stagedCertificates = []; uploading = false; editing = null; revision = null; dirty = false; initialized = false; backendHealthEditorControl = null; poolTablePrefs = defaultPoolTablePrefs(); vhostListPrefs = defaultVhostListPrefs(); poolPreferenceSaveRunning = false; poolPreferenceSaveQueued = false; chartHistory.clear(); backendTrafficHistory.clear(); backendRequestHistory.clear(); vhostTrafficHistory.clear(); container.replaceChildren(); $("vhost-search").value = ""; if ($("pool-search")) $("pool-search").value = ""; $("vhost-list").replaceChildren(); $("pool-rows").replaceChildren(); const sort = $("pool-sort"); if (sort) sort.value = poolTablePrefs.sort; const vhostSort = $("vhost-sort"); if (vhostSort) vhostSort.value = vhostListPrefs.sort; syncVhostSortDirection(); applyPoolTableView(); } };
|
||||
if (envelope) render(); if (latestStatus) renderStatus(latestStatus);
|
||||
@@ -1,6 +1,3 @@
|
||||
// Location conditions editor and the routing tester. The pure helpers mirror
|
||||
// src/config/snapshot.rs (select_route) and src/vhost/conditions.rs and are checked
|
||||
// against the cases in tests/fixtures/routing_conditions_cases.json.
|
||||
const RT_SOURCES = [["header", "rtSourceHeader"], ["cookie", "rtSourceCookie"], ["query", "rtSourceQuery"], ["method", "rtSourceMethod"], ["ip", "rtSourceIp"], ["host", "rtSourceHost"], ["country", "rtSourceCountry"]];
|
||||
const RT_OPERATORS = [["equals", "rtOpEquals"], ["exists", "rtOpExists"], ["prefix", "rtOpPrefix"], ["suffix", "rtOpSuffix"], ["contains", "rtOpContains"], ["regex", "rtOpRegex"], ["cidr", "rtOpCidr"]];
|
||||
function rtOperatorsFor(source) {
|
||||
@@ -9,7 +6,6 @@ function rtOperatorsFor(source) {
|
||||
if (source === "host") return ["equals", "prefix", "suffix", "contains", "regex"];
|
||||
return ["equals", "exists", "prefix", "suffix", "contains", "regex"];
|
||||
}
|
||||
// Rust regex → JS RegExp (common subset; a leading (?i) becomes the i flag).
|
||||
function rtRegex(pattern, insensitive = false) {
|
||||
let flags = insensitive ? "i" : "", body = pattern;
|
||||
const inline = body.match(/^\(\?([imsx]+)\)/);
|
||||
@@ -33,7 +29,7 @@ function rtIpToBits(text) {
|
||||
const all = [...left, ...Array(tail === undefined ? 0 : fill).fill("0"), ...right];
|
||||
if (all.length !== 8 || all.some(h => !/^[0-9a-f]{1,4}$/i.test(h))) return null;
|
||||
const bits = all.reduce((acc, h) => (acc << 16n) | BigInt(parseInt(h, 16)), 0n);
|
||||
if (bits >> 32n === 0xffffn) return { v6: false, bits: bits & 0xffffffffn }; // IPv4-mapped, like canonical_ip()
|
||||
if (bits >> 32n === 0xffffn) return { v6: false, bits: bits & 0xffffffffn };
|
||||
return { v6: true, bits };
|
||||
}
|
||||
function rtCidrContains(network, ip) {
|
||||
@@ -59,7 +55,6 @@ function rtConditionValues(condition, request) {
|
||||
default: return [];
|
||||
}
|
||||
}
|
||||
// Mirrors CompiledCondition::matches(). Throws for patterns the browser cannot run.
|
||||
function rtConditionMatches(condition, request) {
|
||||
const op = condition.operator || "equals", source = condition.source || "header";
|
||||
const fold = (condition.ignore_case && ["header", "cookie", "query"].includes(source)) || source === "host";
|
||||
@@ -82,7 +77,6 @@ function rtConditionMatches(condition, request) {
|
||||
}
|
||||
function rtNormalizePrefix(prefix) { let value = String(prefix || "/").trim(); if (!value.startsWith("/")) value = `/${value}`; if (value.length > 1) value = value.replace(/\/+$/, ""); return value || "/"; }
|
||||
function rtPrefixMatches(prefix, path) { return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`); }
|
||||
// Evaluates every location like select_route() and returns the winner plus a trace.
|
||||
function rtEvaluate(routes, request) {
|
||||
const path = String(request.path || "/").replace(/%2f/gi, "/");
|
||||
const trace = routes.map((route, index) => {
|
||||
@@ -112,7 +106,6 @@ function rtEvaluate(routes, request) {
|
||||
}
|
||||
if (typeof window !== "undefined") window.rustProxyRoutingCore = { evaluate: rtEvaluate, conditionMatches: rtConditionMatches, cidrContains: rtCidrContains };
|
||||
|
||||
// Editor for a location's conditions. Returns read() → array of conditions.
|
||||
function conditionsEditor(parent, values = [], onChange = () => { }) {
|
||||
const box = el("div", undefined, "vh-wide rt-conditions"), list = el("div", undefined, "rt-condition-list"); box.append(list); parent.append(box);
|
||||
const empty = text("p", "rtNoConditions", "fine rt-empty"); box.prepend(empty);
|
||||
@@ -129,7 +122,6 @@ function conditionsEditor(parent, values = [], onChange = () => { }) {
|
||||
const fillOperators = chosen => { operator.replaceChildren(...rtOperatorsFor(source.value).map(v => { const o = text("option", RT_OPERATORS.find(([x]) => x === v)[1]); o.value = v; return o; })); operator.value = rtOperatorsFor(source.value).includes(chosen) ? chosen : rtOperatorsFor(source.value)[0]; };
|
||||
const syncRow = () => {
|
||||
const named = ["header", "cookie", "query"].includes(source.value);
|
||||
// .check labels set their own display, so the hidden attribute is not enough.
|
||||
name.hidden = !named; ignoreLabel.hidden = !named; ignoreLabel.style.display = named ? "" : "none"; valuesInput.hidden = operator.value === "exists";
|
||||
name.placeholder = { header: "X-Beta", cookie: "session", query: "tenant" }[source.value] || "";
|
||||
valuesInput.placeholder = { ip: "10.0.0.0/8\n2001:db8::/32", method: "POST\nPUT", country: "PL\nDE", host: "beta.example.com" }[source.value] || t("rtValuesPlaceholder");
|
||||
@@ -153,7 +145,6 @@ function conditionsEditor(parent, values = [], onChange = () => { }) {
|
||||
return { read: () => [...list.children].map(row => row.read()), count: () => list.children.length };
|
||||
}
|
||||
|
||||
// Routing tester for the Locations tab: works on the unsaved draft.
|
||||
function routingTester(parent, readRoutes) {
|
||||
const box = el("details", undefined, "vh-wide rt-tester"); box.append(text("summary", "rtTester")); parent.append(box);
|
||||
const body = el("div", undefined, "rt-tester-body"); box.append(body);
|
||||
@@ -196,7 +187,6 @@ function routingTester(parent, readRoutes) {
|
||||
}
|
||||
out.append(table, text("p", "rtTesterHelp", "fine"));
|
||||
};
|
||||
// Backend for the chosen route: pinned backend, group or vhost pool + algorithm.
|
||||
const rtTarget = (route, request) => {
|
||||
if (route && (route.response || route.redirect)) return t(route.response ? "locationReturnShort" : "locationRedirectShort");
|
||||
if (route?.source?.type === "web_server") return `${t("locationWebServerShort")} ${route.source.web_service_id || ""}`;
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
"use strict";
|
||||
// A local redirect or response terminates in RustProxy and never connects to an
|
||||
// upstream. Disabled custom locations do not create a live backend dependency.
|
||||
// Keep these checks aligned with Vhost::validate and config/routing.rs.
|
||||
function locationRequiresProxy(route) {
|
||||
return route.enabled !== false
|
||||
&& !route.response
|
||||
|
||||
@@ -70,7 +70,6 @@ window.rustProxyPhpProfiles = ({ defaults, mapLines, lines, parseFastCgiParams,
|
||||
nameInput.closest("label").append(el("small", t("phpProfileNameHelp"), "fine fastcgi-profile-identity-help"));
|
||||
const controls = {};
|
||||
const phpOnlyWrappers = [];
|
||||
// Same section blocks as the Web Service editor.
|
||||
const section = key => { const box = el("section", undefined, "vh-wide vh-setting-section fastcgi-profile-section"), heading = el("h3", t(key)), grid = el("div", undefined, "vh-grid"); heading.dataset.i18n = key; box.append(heading, grid); editor.append(box); return { box, grid }; };
|
||||
const identitySection = section("phpProfileSectionConnection");
|
||||
for (const input of [nameInput, idInput]) identitySection.grid.append(input.closest("label"));
|
||||
|
||||
@@ -167,8 +167,6 @@
|
||||
defaults, mapLines, lines, parseFastCgiParams, parsePhpValues, validatePhpCustomData
|
||||
});
|
||||
|
||||
// Radio cards (same look as the Vhost www choice) that drive the existing
|
||||
// selects, so saving and drafts keep using the original controls.
|
||||
function choiceCard(group, value, titleKey, helpKey) {
|
||||
const label = el("label", undefined, "vh-www-choice"), input = document.createElement("input"), copy = el("span", undefined, "vh-www-choice-copy");
|
||||
input.type = "radio"; input.name = group; input.value = value;
|
||||
@@ -445,7 +443,7 @@
|
||||
htaccessWarnings = result.services || {};
|
||||
htaccessWarningsRevision = result.revision;
|
||||
if (currentPanel === "web-server") render();
|
||||
} catch { /* The configuration remains available if diagnostics cannot be loaded. */ }
|
||||
} catch { }
|
||||
finally { htaccessWarningsLoading = false; }
|
||||
}
|
||||
|
||||
@@ -476,7 +474,6 @@
|
||||
});
|
||||
actions.append(edit, copy, remove); head.append(identity, actions); box.append(head);
|
||||
const details = el("div", undefined, "vhost-detail-strip");
|
||||
// One cell per area; "-" means the default for that area.
|
||||
const join = parts => parts.filter(Boolean).join(" · ") || "-";
|
||||
const tryFiles = service.try_files || [];
|
||||
const warningsCount = htaccessWarningsRevision === envelope.revision ? (htaccessWarnings[service.id]?.warnings || []).length : 0;
|
||||
@@ -494,8 +491,6 @@
|
||||
item.append(el("span", t(key), "small-label"), el("b", value));
|
||||
details.append(item);
|
||||
}
|
||||
// Show the real skipped directives from the active configuration, with
|
||||
// file/line context. Security-related errors never appear here: they fail Apply.
|
||||
const ignored = htaccessWarningsRevision === envelope.revision ? (htaccessWarnings[service.id]?.warnings || []) : [];
|
||||
if (service.htaccess?.enabled && ignored.length) {
|
||||
const details = el("details", undefined, "web-service-htaccess-warnings");
|
||||
|
||||
@@ -91,7 +91,6 @@ mod hash_tests {
|
||||
assert_eq!(key(serde_json::json!({"source":"query","name":"missing"})), None);
|
||||
assert_eq!(key(serde_json::json!({"source":"cookie","name":"missing"})), None);
|
||||
assert_eq!(key(serde_json::json!({"source":"header","name":"x-missing"})), None);
|
||||
// HTTP/2 requests carry the authority in the URI.
|
||||
let settings: HashSettings = serde_json::from_value(serde_json::json!({"source":"host"})).unwrap();
|
||||
assert_eq!(
|
||||
settings
|
||||
@@ -232,7 +231,6 @@ mod hash_tests {
|
||||
let path = "/hot/object.mp3";
|
||||
let owner = pool.preview(peer(), &HeaderMap::new(), Some(&uri(path))).0.unwrap();
|
||||
let mut leases = Vec::new();
|
||||
// Keep the owner busy: with 125% and 3 members its cap is soon exceeded.
|
||||
for _ in 0..4 {
|
||||
let selection = pool.select_uri(peer(), &HeaderMap::new(), Some(&uri(path)), false).unwrap();
|
||||
leases.push(selection);
|
||||
@@ -262,7 +260,6 @@ mod hash_tests {
|
||||
|
||||
#[test]
|
||||
fn ip_hash_keeps_previous_member_mapping() {
|
||||
// Same inputs and formula as before 0.40.2: pool id | client IP | member id.
|
||||
let pool = shards(serde_json::json!({"algorithm":"ip_hash","health_check":{"mode":"off"}}));
|
||||
let expected = pool
|
||||
.members
|
||||
@@ -279,8 +276,6 @@ mod hash_tests {
|
||||
assert_eq!(selection.lease.member.definition.id, expected);
|
||||
}
|
||||
|
||||
/// Reference values (tests/fixtures/balance_rendezvous_vectors.txt); the panel
|
||||
/// simulator in balancing.js must rank members the same way.
|
||||
#[test]
|
||||
fn rendezvous_reference_vectors() {
|
||||
let order = |key: &str| {
|
||||
@@ -348,15 +343,12 @@ mod hash_tests {
|
||||
owners.insert(a);
|
||||
}
|
||||
assert_eq!(owners.len(), 3);
|
||||
// The vhost pool itself never uses location-only backends.
|
||||
for _ in 0..10 {
|
||||
let selection = vhost_pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
assert_eq!(selection.lease.member.definition.id, "app");
|
||||
}
|
||||
// Main pages still go to the vhost pool.
|
||||
let main = snapshot.select("site.localhost", "/index.html").unwrap();
|
||||
assert!(Arc::ptr_eq(main.pool.as_ref().unwrap(), &vhost_pool));
|
||||
// Affinity cookies of the vhost pool are not forwarded by the location pool.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("cookie", "RP_AFFINITY_site=abc; keep=1".parse().unwrap());
|
||||
pool.strip_affinity(&mut headers);
|
||||
@@ -385,7 +377,6 @@ mod hash_tests {
|
||||
let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap();
|
||||
let cookie = selection.cookie.unwrap();
|
||||
assert!(cookie.to_str().unwrap().starts_with("RP_AFFINITY_site__api="));
|
||||
// The vhost pool strips location affinity cookies before the origin.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("cookie", "RP_AFFINITY_site__api=x; app=1".parse().unwrap());
|
||||
snapshot.pools[0].strip_affinity(&mut headers);
|
||||
|
||||
@@ -464,13 +464,8 @@ pub struct Pool {
|
||||
cookie_name: String,
|
||||
cursor: AtomicU64,
|
||||
scheduling: Mutex<std::collections::HashMap<String, f64>>,
|
||||
/// Location backend group: members were chosen explicitly, so `pool_eligible`
|
||||
/// (which only controls membership of the vhost-wide pool) is ignored.
|
||||
explicit_members: bool,
|
||||
/// Location id for a pool derived from the vhost pool.
|
||||
pub route: Option<String>,
|
||||
/// Shared by a vhost pool and its location pools: set when any of them issues an
|
||||
/// affinity cookie, so every one of them strips those cookies.
|
||||
affinity_cookies: Arc<AtomicBool>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -29,13 +29,10 @@ pub enum Algorithm {
|
||||
LeastTraffic,
|
||||
Adaptive,
|
||||
IpHash,
|
||||
/// Consistent (rendezvous) hash of a request attribute selected by [`HashSettings`].
|
||||
Hash,
|
||||
/// Power of two random choices: two random members, the less loaded one wins.
|
||||
Random,
|
||||
}
|
||||
impl Algorithm {
|
||||
/// Algorithms usable when a hash key is missing from a request.
|
||||
pub fn valid_hash_fallback(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
@@ -43,24 +40,16 @@ impl Algorithm {
|
||||
)
|
||||
}
|
||||
}
|
||||
/// Request attribute used as the key of the `hash` algorithm.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HashSource {
|
||||
/// Request path without the query string (HAProxy `balance hash path` / `balance uri`).
|
||||
#[default]
|
||||
Path,
|
||||
/// Path and query string (HAProxy `balance uri whole`).
|
||||
Uri,
|
||||
/// Request host name without the port.
|
||||
Host,
|
||||
/// Client address as seen by RustProxy (same input as `ip_hash`).
|
||||
Ip,
|
||||
/// Value of one request header (`name`).
|
||||
Header,
|
||||
/// Value of one request cookie (`name`).
|
||||
Cookie,
|
||||
/// Value of one query string parameter (`name`).
|
||||
Query,
|
||||
}
|
||||
impl HashSource {
|
||||
@@ -71,22 +60,15 @@ impl HashSource {
|
||||
fn default_hash_fallback() -> Algorithm {
|
||||
Algorithm::RoundRobin
|
||||
}
|
||||
/// Settings of the `hash` algorithm. Hashing is always consistent: members are ranked
|
||||
/// with weighted rendezvous hashing, so adding, removing or ejecting a member only moves
|
||||
/// the keys that belong to that member.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HashSettings {
|
||||
pub source: HashSource,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Number of leading path directories to hash; 0 hashes the whole path.
|
||||
pub path_depth: u8,
|
||||
pub ignore_case: bool,
|
||||
/// Consistent hashing with bounded loads (percent of the average load per member);
|
||||
/// 0 disables the bound, otherwise 101..=1000.
|
||||
pub balance_factor: u16,
|
||||
/// Algorithm used when the request has no value for the key.
|
||||
#[serde(default = "default_hash_fallback")]
|
||||
pub fallback: Algorithm,
|
||||
}
|
||||
@@ -142,7 +124,6 @@ impl HashSettings {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
/// Extracts the hash key for a request; `None` when the request has no value.
|
||||
pub fn key(&self, peer: IpAddr, headers: &HeaderMap, uri: Option<&http::Uri>) -> Option<String> {
|
||||
let raw: String = match self.source {
|
||||
HashSource::Ip => return Some(crate::vhost::canonical_ip(peer).to_string()),
|
||||
@@ -226,7 +207,6 @@ fn strip_port(host: &str) -> &str {
|
||||
_ => host,
|
||||
}
|
||||
}
|
||||
/// Keeps the first `depth` directories of a path (`/a/b/c.mp3`, depth 2 → `/a/b`).
|
||||
fn limit_path_depth(path: &str, depth: u8) -> &str {
|
||||
if depth == 0 {
|
||||
return path;
|
||||
@@ -242,7 +222,6 @@ fn limit_path_depth(path: &str, depth: u8) -> &str {
|
||||
}
|
||||
path
|
||||
}
|
||||
/// Rendezvous score of one member for a key; the lowest score wins.
|
||||
pub(crate) fn rendezvous_score(pool_id: &str, key: &str, member_id: &str, weight: u16) -> f64 {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(pool_id.as_bytes());
|
||||
@@ -257,8 +236,6 @@ pub(crate) fn rendezvous_score(pool_id: &str, key: &str, member_id: &str, weight
|
||||
let unit = (n as f64 + 1.0) / (u64::MAX as f64 + 2.0);
|
||||
-unit.max(f64::MIN_POSITIVE).ln() / f64::from(weight.max(1))
|
||||
}
|
||||
/// Per-location balancing override: the location uses its own algorithm over its
|
||||
/// backend group while sharing health state with the vhost pool.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct RouteBalancing {
|
||||
|
||||
@@ -51,10 +51,6 @@ impl Pool {
|
||||
affinity_cookies: Arc::new(AtomicBool::new(settings_cookie)),
|
||||
})
|
||||
}
|
||||
/// Builds the pool of one location from this (vhost) pool. Members are shared, so
|
||||
/// health checks, passive ejection, concurrency limits and statistics stay common;
|
||||
/// only the selection (members, algorithm, hash key, affinity) is location-specific.
|
||||
/// `member_ids` empty means every member of the vhost pool.
|
||||
pub fn derive(
|
||||
&self,
|
||||
route_id: &str,
|
||||
@@ -107,9 +103,6 @@ impl Pool {
|
||||
})
|
||||
}
|
||||
fn affinity_cookie_name(&self, name: &str) -> bool {
|
||||
// A location pool strips the vhost cookie too, and the vhost pool strips the
|
||||
// cookies of its locations (`<vhost cookie>__<location>`), so affinity tokens
|
||||
// never reach an origin.
|
||||
let base = self
|
||||
.route
|
||||
.as_ref()
|
||||
@@ -183,8 +176,6 @@ impl Pool {
|
||||
pub fn ready(&self) -> bool {
|
||||
!self.eligible_healthy_excluding(&[]).is_empty()
|
||||
}
|
||||
/// Hash key the pool uses for this request (consistent `hash` or `ip_hash`), for
|
||||
/// the `%[hash_key]` header variable.
|
||||
pub fn balance_key(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
@@ -196,7 +187,6 @@ impl Pool {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Effective algorithm name (`ip_hash` sticky mode reports `ip_hash`).
|
||||
pub fn algorithm_name(&self) -> &'static str {
|
||||
let algorithm = if self.settings.sticky.mode == StickyMode::IpHash {
|
||||
Algorithm::IpHash
|
||||
@@ -213,7 +203,6 @@ impl Pool {
|
||||
Algorithm::Random => "random",
|
||||
}
|
||||
}
|
||||
/// True when selection reads the request URI (path, URI, host or query hashing).
|
||||
pub fn hashes_request_uri(&self) -> bool {
|
||||
self.settings.algorithm == Algorithm::Hash
|
||||
&& self.settings.sticky.mode != StickyMode::IpHash
|
||||
@@ -398,8 +387,6 @@ impl Pool {
|
||||
cookie,
|
||||
})
|
||||
}
|
||||
/// Effective algorithm and hash key for a request. `ip_hash` affinity overrides the
|
||||
/// algorithm; a `hash` request without a key value uses the configured fallback.
|
||||
fn plan(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
@@ -423,7 +410,6 @@ impl Pool {
|
||||
other => (other, None),
|
||||
}
|
||||
}
|
||||
/// Members ordered by rendezvous score for `key` (best first).
|
||||
fn rendezvous_order<'a>(&self, members: &[&'a Arc<Member>], key: &str) -> Vec<&'a Arc<Member>> {
|
||||
let mut ranked: Vec<(f64, &Arc<Member>)> = members
|
||||
.iter()
|
||||
@@ -457,10 +443,6 @@ impl Pool {
|
||||
if factor == 0 || ordered.len() < 2 {
|
||||
return ordered.first().copied();
|
||||
}
|
||||
// Consistent hashing with bounded loads: a member may take a new request
|
||||
// only while its in-flight count stays within `factor`% of its weighted
|
||||
// share of the pool load; otherwise the next member in the key's
|
||||
// rendezvous order is used, so overflow stays deterministic per key.
|
||||
let total_active: u64 = members
|
||||
.iter()
|
||||
.map(|m| m.state.active.load(Ordering::Relaxed))
|
||||
@@ -559,8 +541,6 @@ impl Pool {
|
||||
}
|
||||
chosen
|
||||
}
|
||||
/// Which member would serve a request right now, without taking a lease. Used by
|
||||
/// the panel and diagnostics; returns the member id and the hash key (if any).
|
||||
pub fn preview(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
|
||||
@@ -73,7 +73,6 @@ impl Pool {
|
||||
) -> Result<Selection, SelectionFailure> {
|
||||
self.select_retry_wait_uri(peer, headers, None, tls, &[]).await
|
||||
}
|
||||
/// Like [`Pool::select_wait`], with the request URI for path/URI/host/query hashing.
|
||||
pub async fn select_wait_uri(
|
||||
&self,
|
||||
peer: IpAddr,
|
||||
|
||||
@@ -162,9 +162,6 @@ fn denied(status: StatusCode, challenge: Option<&HeaderValue>) -> Response {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Unlike external auth providers, a Basic Auth denial may use the
|
||||
// configured Vhost/global error document. The challenge and retry
|
||||
// headers are retained by pages::replace_error.
|
||||
response
|
||||
}
|
||||
|
||||
|
||||
Vendored
-7
@@ -969,8 +969,6 @@ mod tests {
|
||||
variant_key(&[0x52; 32], &[name.to_owned()], &request)
|
||||
}
|
||||
|
||||
// RFC 9111 section 4.1: OWS, equivalent repeated list fields,
|
||||
// case-insensitive language tags and equivalent qvalues.
|
||||
assert_eq!(
|
||||
keyed("accept-language", &["en,pl;q=0.5"]),
|
||||
keyed("accept-language", &["EN ; q=1.0", " PL ; Q=0.500"])
|
||||
@@ -999,8 +997,6 @@ mod tests {
|
||||
keyed("if-none-match", &["\"tag,a\"", "W/\"tag-b\""])
|
||||
);
|
||||
|
||||
// Header order remains significant unless a field's specification
|
||||
// guarantees otherwise; opaque and session-related values stay exact.
|
||||
assert_ne!(
|
||||
keyed("accept-language", &["en,pl"]),
|
||||
keyed("accept-language", &["pl,en"])
|
||||
@@ -1042,7 +1038,6 @@ mod tests {
|
||||
keyed("accept-encoding", &["gzip;q=invalid"]),
|
||||
keyed("accept-encoding", &["gzip"])
|
||||
);
|
||||
// Invalid raw fields cannot collide with a valid canonical value.
|
||||
assert_ne!(
|
||||
keyed("accept-encoding", &["gzip;q=1000"]),
|
||||
keyed("accept-encoding", &["gzip"])
|
||||
@@ -1651,8 +1646,6 @@ mod tests {
|
||||
assert_eq!(h, original, "{policy}");
|
||||
}
|
||||
|
||||
// A positive administrator-configured fallback does make `public`
|
||||
// without an explicit max-age a reusable static response.
|
||||
let mut settings = Settings::default();
|
||||
settings.default_ttl_seconds = 60;
|
||||
let mut h = headers("public");
|
||||
|
||||
Vendored
-2
@@ -190,8 +190,6 @@ impl Candidate {
|
||||
}
|
||||
}
|
||||
|
||||
/// A response body still owns an active cache fill. The proxy uses this
|
||||
/// marker to finish filling a cacheable HEAD miss without sending a body.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct PendingFill {
|
||||
pub max_body_bytes: usize,
|
||||
|
||||
Vendored
-15
@@ -332,8 +332,6 @@ fn vary_names(headers: &HeaderMap) -> Option<Vec<String>> {
|
||||
(names.len() <= 64).then_some(names)
|
||||
}
|
||||
|
||||
// RFC 9111 section 4.1 permits only semantics-preserving Vary comparisons.
|
||||
// In particular, Cookie and arbitrary extension fields are NOT comma lists.
|
||||
fn trim_vary_ows(mut value: &[u8]) -> &[u8] {
|
||||
while value.first().is_some_and(|byte| matches!(*byte, b' ' | b'\t')) {
|
||||
value = &value[1..];
|
||||
@@ -394,7 +392,6 @@ fn is_language_range(value: &[u8]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
// qvalue is 0..1, expressed with at most three fractional digits (RFC 9110).
|
||||
fn parse_vary_quality(value: &[u8]) -> Option<u16> {
|
||||
let (&whole, rest) = value.split_first()?;
|
||||
if whole != b'0' && whole != b'1' {
|
||||
@@ -458,7 +455,6 @@ fn normalize_vary_accept(member: &[u8]) -> Option<Vec<u8>> {
|
||||
if !is_http_token(&media_range[..slash]) || !is_http_token(&media_range[slash + 1..]) {
|
||||
return None;
|
||||
}
|
||||
// Media type/subtype is case-insensitive; parameter values need not be.
|
||||
let mut canonical = media_range.to_ascii_lowercase();
|
||||
for param in parts.iter().skip(1) {
|
||||
if param.is_empty() {
|
||||
@@ -482,12 +478,9 @@ fn normalize_vary_list(name: &str, values: &[&[u8]]) -> Option<Vec<u8>> {
|
||||
let mut canonical = Vec::new();
|
||||
let mut first = true;
|
||||
for value in values {
|
||||
// Commas inside a quoted-string are data, not list separators.
|
||||
for member in split_vary_unquoted(value, b',')? {
|
||||
let normalized = match name {
|
||||
"accept-language" | "accept-encoding" | "accept-charset" => {
|
||||
// Empty list elements are kept distinct. Never confuse an
|
||||
// explicitly empty field with an absent header field.
|
||||
if member.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
@@ -512,8 +505,6 @@ fn variant_key(base_key: &Key, vary: &[String], headers: &HeaderMap) -> Key {
|
||||
return *base_key;
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
// The v2 domain deliberately makes old COLD variant hashes miss instead
|
||||
// of reusing entries that were indexed with the previous bytewise keys.
|
||||
digest.update(b"RustProxy-Vary-v2");
|
||||
digest.update(base_key);
|
||||
for name in vary {
|
||||
@@ -522,17 +513,11 @@ fn variant_key(base_key: &Key, vary: &[String], headers: &HeaderMap) -> Key {
|
||||
let header_values = headers.get_all(name.as_str());
|
||||
let values: Vec<&[u8]> = header_values.iter().map(HeaderValue::as_bytes).collect();
|
||||
if let Some(value) = normalize_vary_list(name, &values) {
|
||||
// Separate normalized values from raw fallback values: a malformed
|
||||
// literal such as "gzip;q=1000" must not match canonical gzip.
|
||||
digest.update([1_u8]);
|
||||
// RFC 9110 allows combining multiple lines for known list fields.
|
||||
digest.update(1_u64.to_be_bytes());
|
||||
digest.update((value.len() as u64).to_be_bytes());
|
||||
digest.update(&value);
|
||||
} else {
|
||||
// Unknown fields are opaque: no comma splitting, token case-folding
|
||||
// or quote rewriting. Leading/trailing HTTP OWS is insignificant.
|
||||
// The count also distinguishes an absent field from an empty one.
|
||||
digest.update([0_u8]);
|
||||
digest.update((values.len() as u64).to_be_bytes());
|
||||
for value in values {
|
||||
|
||||
Vendored
-77
@@ -1,46 +1,14 @@
|
||||
// Central request-gate decision for the shared cache.
|
||||
//
|
||||
// Every reason that can keep a request away from the HOT/COLD cache is
|
||||
// classified here, and its precedence is fixed in one place. The proxy request
|
||||
// path (`proxy/forward/route_cache.rs`) and the administrator "Test a request"
|
||||
// API (`admin/cache_rules.rs`) both use these functions, so diagnostics in the
|
||||
// panel match what live traffic does.
|
||||
//
|
||||
// Precedence, strongest first:
|
||||
//
|
||||
// 1. Security - control-plane traffic, Basic auth, external auth
|
||||
// providers, sticky-cookie pools. Never relaxed.
|
||||
// 2. Configuration - cache disabled globally / per route, protocol upgrade.
|
||||
// 3. VCL `pass` - an explicit `return(pass)` rule. Never relaxed.
|
||||
// 4. VCL `cookie_pass` - a Cookie/session guard. Relaxed **only** for a public
|
||||
// static asset under the "Ignore request cookies for
|
||||
// static files" option, and only when no other rule would
|
||||
// bypass the same request (see
|
||||
// `static_cookie_guard_relaxation`).
|
||||
// 5. Default request policy (`request_policy_with_vcl_cookie`): method,
|
||||
// body, Authorization, Cookie, path/query exclusions, client directives.
|
||||
// 6. Backend response policy (`plan_with`, `response_reason`) and, for a
|
||||
// static request whose Cookie was ignored, `shared_static_response_reason`.
|
||||
|
||||
/// Broad class of a cache reason, for diagnostics and documentation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ReasonClass {
|
||||
/// Absolute security bypass (authentication, credentials, control plane).
|
||||
Security,
|
||||
/// Cache or route disabled by configuration.
|
||||
Configuration,
|
||||
/// Explicit VCL / cache-rule `pass` or rule `no_store`.
|
||||
VclRule,
|
||||
/// VCL / cache-rule Cookie guard (`cookie_pass`).
|
||||
VclCookieGuard,
|
||||
/// RustProxy's built-in Cookie policy.
|
||||
Cookie,
|
||||
/// Other default request policy (method, body, directives, exclusions).
|
||||
RequestPolicy,
|
||||
/// Backend response properties (status, Cache-Control, Set-Cookie, Vary).
|
||||
Response,
|
||||
/// HIT / MISS / revalidation outcomes that are not a bypass.
|
||||
Cache,
|
||||
}
|
||||
|
||||
@@ -59,11 +27,8 @@ impl ReasonClass {
|
||||
}
|
||||
}
|
||||
|
||||
/// `X-Cache-Reason` for an unrelaxed explicit `pass` (unchanged since 0.2x).
|
||||
pub const REASON_VCL_PASS: &str = "cache_rule";
|
||||
/// `X-Cache-Reason` for an unrelaxed `cookie_pass` guard.
|
||||
pub const REASON_VCL_COOKIE_GUARD: &str = "cache_rule_cookie";
|
||||
/// MISS reason when a `cookie_pass` guard was relaxed for a public static.
|
||||
pub const REASON_MISS_STATIC_COOKIE: &str = "cache_miss_static_cookie";
|
||||
|
||||
pub fn reason_class(reason: &str) -> ReasonClass {
|
||||
@@ -85,13 +50,10 @@ pub fn reason_class(reason: &str) -> ReasonClass {
|
||||
{
|
||||
ReasonClass::RequestPolicy
|
||||
}
|
||||
// External authentication provider identifiers (tinyauth, authentik,
|
||||
// oidc, ...) are reported verbatim and are security bypasses.
|
||||
_ => ReasonClass::Security,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs to the request gate that precede cache-rule evaluation results.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct GateInput {
|
||||
pub admin_control_plane: bool,
|
||||
@@ -103,17 +65,11 @@ pub struct GateInput {
|
||||
pub upgrade: bool,
|
||||
}
|
||||
|
||||
/// Effective VCL routing decision after the static-cookie relaxation step.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RuleGate {
|
||||
/// No request-rule bypass.
|
||||
None,
|
||||
/// Explicit `pass`: absolute for every resource type.
|
||||
Pass,
|
||||
/// Unrelaxed `cookie_pass` guard.
|
||||
CookieGuard,
|
||||
/// `cookie_pass` guard relaxed for a public static asset. Treated as
|
||||
/// `None` by the gate; the request continues to the default policy.
|
||||
CookieGuardRelaxed,
|
||||
}
|
||||
|
||||
@@ -127,7 +83,6 @@ impl RuleGate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Request-gate reason, or `None` when the default request policy decides.
|
||||
pub fn request_gate(input: GateInput, rule: RuleGate) -> Option<&'static str> {
|
||||
if input.admin_control_plane {
|
||||
Some("admin_control_plane")
|
||||
@@ -152,32 +107,11 @@ pub fn request_gate(input: GateInput, rule: RuleGate) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of relaxing a `cookie_pass` guard for a public static asset.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaticCookieRelaxation {
|
||||
/// Request-rule outcome without Cookie guards. Its request edits (header,
|
||||
/// cookie and query rewrites, hash variants) replace the guarded outcome,
|
||||
/// so the forwarded request and cache key match what every other client
|
||||
/// gets for the same URL.
|
||||
pub outcome: RequestRuleOutcome,
|
||||
}
|
||||
|
||||
/// Decide whether a `cookie_pass` bypass may be relaxed for this request.
|
||||
///
|
||||
/// `request` must be the request **as received** (before rule edits). All of
|
||||
/// the following must hold, otherwise the guard keeps BYPASS:
|
||||
///
|
||||
/// * the winning bypass is a `cookie_pass` guard (never an explicit `pass`);
|
||||
/// * GET or HEAD; no `Authorization`; a `Cookie` header is present;
|
||||
/// * "Ignore request cookies for static files" is on and the path has one of
|
||||
/// the configured static extensions (the query string does not matter);
|
||||
/// * re-evaluating the rules with every Cookie guard removed produces no
|
||||
/// `pass` (so explicit rules after a terminal guard still apply);
|
||||
/// * re-evaluating the rules with the Cookie header removed produces no
|
||||
/// `pass` (the resource is cacheable for an anonymous client as well).
|
||||
///
|
||||
/// The extension is only a *candidate* signal. Public storage is decided
|
||||
/// later from the backend response (`shared_static_response_reason`).
|
||||
pub fn static_cookie_guard_relaxation(
|
||||
rules: &CompiledRules,
|
||||
request: &RuleRequest,
|
||||
@@ -224,7 +158,6 @@ fn explicit_public_freshness(
|
||||
return true;
|
||||
}
|
||||
if control.contains_key("max-age") {
|
||||
// An explicit max-age (including 0) overrides Expires (RFC 9111 5.3).
|
||||
return false;
|
||||
}
|
||||
let expires = headers
|
||||
@@ -239,14 +172,6 @@ fn explicit_public_freshness(
|
||||
expires.is_some_and(|expires| expires > date)
|
||||
}
|
||||
|
||||
/// Extra storage guard for a static request that carried a Cookie which the
|
||||
/// cache key ignored (the static-cookie policy). Such an object will be served
|
||||
/// to clients with *other* cookies, including anonymous ones, so the backend
|
||||
/// must positively declare it shareable. Evaluated on the backend response
|
||||
/// **before** VCL response rules, so `strip_set_cookie` or
|
||||
/// `ignore_cache_control` cannot turn a private reply into a shared one.
|
||||
///
|
||||
/// Returns the `X-Cache-Reason` when storage must be refused.
|
||||
pub fn shared_static_response_reason(
|
||||
status: StatusCode,
|
||||
headers: &HeaderMap,
|
||||
@@ -280,8 +205,6 @@ pub fn shared_static_response_reason(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Dynamic documents served under a static-looking name (SPA fallbacks,
|
||||
// error pages rendered with 200, "/user.css" generated per session).
|
||||
if headers
|
||||
.get(::http::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
|
||||
Vendored
-10
@@ -72,7 +72,6 @@ mod cache_decision_tests {
|
||||
let error = validate_rules(&invalid, true).unwrap_err().to_string();
|
||||
assert!(error.contains("cookie_pass needs"), "{error}");
|
||||
}
|
||||
// A named-cookie condition is accepted.
|
||||
compile(vec![rule(
|
||||
serde_json::json!({"id": "named", "conditions": [{"field": "cookie", "name": "sessionid", "operator": "exists"}], "actions": [{"type": "cookie_pass"}]}),
|
||||
)]);
|
||||
@@ -86,10 +85,8 @@ mod cache_decision_tests {
|
||||
serde_json::json!({"id": "admin", "conditions": [{"field": "path", "operator": "prefix", "values": ["/admin"]}], "actions": [{"type": "pass"}]}),
|
||||
),
|
||||
]);
|
||||
// stop on the guard: the explicit rule is not reached in normal mode ...
|
||||
let outcome = rules.evaluate_request(&get("/admin/app.css", &[("cookie", "s=1")]), false);
|
||||
assert!(outcome.pass_cookie_guard);
|
||||
// ... but it is reached once guards are ignored.
|
||||
let unguarded = rules
|
||||
.evaluate_request_without_cookie_guards(&get("/admin/app.css", &[("cookie", "s=1")]));
|
||||
assert_eq!(unguarded.pass.as_deref(), Some("admin"));
|
||||
@@ -112,8 +109,6 @@ mod cache_decision_tests {
|
||||
),
|
||||
]);
|
||||
let cookie = [("cookie", "SESSabc=1; _ga=2")];
|
||||
// Public static candidate with a query string: relaxed, and later
|
||||
// request edits (query stripping) are part of the relaxed outcome.
|
||||
let asset = request(
|
||||
Method::GET,
|
||||
"/theme/app.CSS",
|
||||
@@ -133,14 +128,12 @@ mod cache_decision_tests {
|
||||
)
|
||||
.is_some());
|
||||
|
||||
// Not a configured static extension (HTML, extension-less, .php).
|
||||
for path in ["/", "/node/1", "/index.php", "/feed.xml"] {
|
||||
assert!(
|
||||
relax(&rules, &get(path, &cookie), &settings).is_none(),
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
// Unsafe method, Authorization, explicit pass on path or later rule.
|
||||
assert!(relax(
|
||||
&rules,
|
||||
&request(Method::POST, "/app.css", None, &cookie),
|
||||
@@ -164,7 +157,6 @@ mod cache_decision_tests {
|
||||
)
|
||||
.is_none());
|
||||
|
||||
// Options off => the guard keeps BYPASS.
|
||||
let off = Settings {
|
||||
static_ignore_cookies: false,
|
||||
..Settings::default()
|
||||
@@ -180,7 +172,6 @@ mod cache_decision_tests {
|
||||
#[test]
|
||||
fn relaxation_refuses_resources_bypassed_for_anonymous_clients() {
|
||||
let settings = Settings::default();
|
||||
// Explicit pass when the consent cookie is *absent*.
|
||||
let rules = compile(vec![
|
||||
guard("cookies"),
|
||||
rule(
|
||||
@@ -220,7 +211,6 @@ mod cache_decision_tests {
|
||||
request_gate(open, RuleGate::CookieGuard),
|
||||
Some(REASON_VCL_COOKIE_GUARD)
|
||||
);
|
||||
// Security and configuration always win over rules and relaxation.
|
||||
for (input, reason) in [
|
||||
(
|
||||
GateInput {
|
||||
|
||||
Vendored
-2
@@ -219,8 +219,6 @@ pub fn request_policy(
|
||||
request_policy_with_vcl_cookie(method, headers, empty_body, path, has_query, settings, false)
|
||||
}
|
||||
|
||||
/// VCL return(hash) may override the built-in Cookie pass only in compatibility
|
||||
/// mode. Authorization, no-store, invalid methods and other guards remain.
|
||||
pub fn request_policy_with_vcl_cookie(
|
||||
method: &Method,
|
||||
headers: &HeaderMap,
|
||||
|
||||
Vendored
+3
-14
@@ -54,10 +54,6 @@ impl Plan {
|
||||
self
|
||||
}
|
||||
}
|
||||
/// For cookie-independent static files only: remove Cookie from the Vary schema
|
||||
/// presented to both RustProxy and downstream caches. A backend's public cache
|
||||
/// policy must be explicit; private/Set-Cookie/no-store responses are untouched.
|
||||
/// The caller is responsible for applying this only to configured static paths.
|
||||
pub fn normalize_static_cookie_vary(
|
||||
status: StatusCode,
|
||||
headers: &mut HeaderMap,
|
||||
@@ -106,9 +102,6 @@ pub fn normalize_static_cookie_vary(
|
||||
};
|
||||
candidate.insert(::http::header::VARY, value);
|
||||
}
|
||||
// A response may have a storage plan with zero freshness (e.g. `public`
|
||||
// with no fallback TTL, or `max-age=0`). Such a response must retain the
|
||||
// origin's Vary: Cookie. The same applies when reuse needs revalidation.
|
||||
let Some(plan) = plan_with(status, &candidate, settings, response_delay, overrides) else {
|
||||
return false;
|
||||
};
|
||||
@@ -187,8 +180,6 @@ pub fn plan_with(
|
||||
if !forced && settings.varnish_compatible && surrogate_no_store(headers) {
|
||||
return None;
|
||||
}
|
||||
// Explicit compatibility-mode fallback overrides origin no-cache even when
|
||||
// it does not contain public. Strict mode always follows RFC 9111.
|
||||
let override_no_cache = settings.varnish_compatible
|
||||
&& control.contains_key("no-cache")
|
||||
&& (settings.default_ttl_seconds > 0 || overrides.ttl.is_some_and(|ttl| ttl > 0));
|
||||
@@ -232,11 +223,9 @@ pub fn plan_with(
|
||||
.ok()?
|
||||
.as_secs(),
|
||||
)
|
||||
} else if control.contains_key("public") {
|
||||
Some(settings.default_ttl_seconds)
|
||||
} else if settings.varnish_compatible && settings.default_ttl_seconds > 0 {
|
||||
// In compatibility mode a configured default TTL can also be used
|
||||
// for headerless, otherwise eligible 200s (Varnish default_ttl style).
|
||||
} else if control.contains_key("public")
|
||||
|| (settings.varnish_compatible && settings.default_ttl_seconds > 0)
|
||||
{
|
||||
Some(settings.default_ttl_seconds)
|
||||
} else {
|
||||
None
|
||||
|
||||
Vendored
-1
@@ -1406,7 +1406,6 @@ pub struct ResponseOverrides {
|
||||
pub no_store: bool,
|
||||
pub ignore_cache_control: bool,
|
||||
pub strip_set_cookie: bool,
|
||||
/// Ordered backend header mutations. Global rules cannot replace vhost edits.
|
||||
pub header_edits: Vec<BackendHeaderEdit>,
|
||||
}
|
||||
|
||||
|
||||
Vendored
-1
@@ -898,7 +898,6 @@ sub vcl_deliver {
|
||||
let outcome = rules.evaluate_request(&request("/catalog", Some("lang=pl"), &[]), false);
|
||||
assert!(outcome.lookup.is_some());
|
||||
assert!(outcome.pass.is_none());
|
||||
// The path, query and authority already form the base cache key.
|
||||
assert_eq!(outcome.hash, vec!["h:x-device=mobile"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ mod routing_conditions_tests {
|
||||
compile(cfg, 0, &policy())
|
||||
}
|
||||
|
||||
/// The panel routing tester (routing.js) must agree with these cases.
|
||||
#[test]
|
||||
fn fixture_cases_select_the_expected_location() {
|
||||
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
|
||||
@@ -74,7 +73,6 @@ mod routing_conditions_tests {
|
||||
.filter(|r| r.get("conditions").is_some())
|
||||
.count();
|
||||
assert!(conditional >= 5);
|
||||
// A conditional location never uses the cache.
|
||||
let headers = {
|
||||
let mut h = http::HeaderMap::new();
|
||||
h.insert("x-beta", "1".parse().unwrap());
|
||||
@@ -130,8 +128,6 @@ mod routing_conditions_tests {
|
||||
] {
|
||||
assert!(config(vhost(routes.clone())).is_err(), "{routes} should be rejected");
|
||||
}
|
||||
// A conditional copy before the unconditional regex is fine, and two
|
||||
// conditional prefixes may share a path.
|
||||
assert!(config(vhost(serde_json::json!([
|
||||
{"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]},
|
||||
{"id":"x","match_type":"regex","path_prefix":"\\.js$"},
|
||||
|
||||
@@ -171,7 +171,6 @@ pub fn allocator_stats() -> Option<AllocatorStats> {
|
||||
return Some(stats);
|
||||
}
|
||||
}
|
||||
// SAFETY: mallinfo2 has no preconditions and only reads allocator state.
|
||||
let info = unsafe { libc::mallinfo2() };
|
||||
let stats = AllocatorStats {
|
||||
allocator: "glibc",
|
||||
|
||||
@@ -30,14 +30,10 @@ pub struct CompiledRule {
|
||||
op: Operation,
|
||||
name: HeaderName,
|
||||
value: Option<HeaderValue>,
|
||||
/// Value with `%[variable]` placeholders, rendered per request.
|
||||
template: Option<Template>,
|
||||
/// Applied only on the wire (final delivery): `Age` and every response rule with
|
||||
/// variables, so per-request values are never stored in the cache.
|
||||
wire_only: bool,
|
||||
}
|
||||
|
||||
/// Variables available in header values as `%[name]` (HAProxy-style sample fetches).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Var {
|
||||
SrvId,
|
||||
@@ -78,7 +74,6 @@ impl Var {
|
||||
.find(|(candidate, _)| *candidate == name)
|
||||
.map(|(_, var)| *var)
|
||||
}
|
||||
/// Known only once the response exists.
|
||||
fn response_only(self) -> bool {
|
||||
matches!(self, Var::CacheStatus | Var::BackendTime)
|
||||
}
|
||||
@@ -137,12 +132,9 @@ impl Template {
|
||||
Segment::Var(var) => out.push_str(vars.get(*var).unwrap_or("-")),
|
||||
}
|
||||
}
|
||||
// Values reflected from the request are visible ASCII; anything that is not a
|
||||
// valid header value (e.g. control characters) drops the header.
|
||||
HeaderValue::from_str(&out).ok()
|
||||
}
|
||||
}
|
||||
/// Values for header variables; `None` renders as `-`.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Vars<'a> {
|
||||
pub srv_id: Option<&'a str>,
|
||||
@@ -181,7 +173,6 @@ impl Vars<'_> {
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
}
|
||||
/// Request facts captured when the request is routed, for response-side variables.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct RequestVars {
|
||||
pub location: Option<String>,
|
||||
@@ -200,7 +191,6 @@ pub struct CompiledHeaders {
|
||||
pub response: Vec<CompiledRule>,
|
||||
}
|
||||
impl CompiledHeaders {
|
||||
/// True when a rule value uses `var`.
|
||||
pub fn uses(&self, var: Var) -> bool {
|
||||
self.request
|
||||
.iter()
|
||||
@@ -278,7 +268,6 @@ fn compile_rules(rules: &[Rule], direction: Direction) -> Result<Vec<CompiledRul
|
||||
ensure!(value.len() <= 8192, "header value too long");
|
||||
match Template::parse(value)? {
|
||||
Some(template) => {
|
||||
// The literal parts must form a valid header value too.
|
||||
let _: HeaderValue = value
|
||||
.replace("%[", "")
|
||||
.replace(']', "")
|
||||
@@ -322,7 +311,6 @@ fn compile_rules(rules: &[Rule], direction: Direction) -> Result<Vec<CompiledRul
|
||||
}
|
||||
fn apply_rule(headers: &mut HeaderMap, rule: &CompiledRule) {
|
||||
if rule.template.is_some() {
|
||||
// Templates need request values; see apply_with_vars / apply_wire.
|
||||
return;
|
||||
}
|
||||
match (&rule.op, &rule.value) {
|
||||
@@ -362,13 +350,11 @@ fn apply_template(headers: &mut HeaderMap, rule: &CompiledRule, vars: &Vars<'_>)
|
||||
Operation::Remove => {}
|
||||
}
|
||||
}
|
||||
/// Request rules with variables (static request rules use [`apply`]).
|
||||
pub fn apply_with_vars(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
|
||||
for rule in rules {
|
||||
apply_template(headers, rule, vars);
|
||||
}
|
||||
}
|
||||
/// Final-delivery stage for response rules: `Age` rules and rules with variables.
|
||||
pub fn apply_wire(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
|
||||
for rule in rules {
|
||||
if rule.wire_only {
|
||||
|
||||
@@ -130,7 +130,6 @@ mod tests {
|
||||
cache_status: Some("HIT"),
|
||||
..Default::default()
|
||||
};
|
||||
// Static stage: templates are skipped, so cached objects never carry them.
|
||||
let mut headers = HeaderMap::new();
|
||||
apply(&mut headers, &compiled.response);
|
||||
assert_eq!(headers["x-plain"], "yes");
|
||||
@@ -145,7 +144,6 @@ mod tests {
|
||||
assert!(!request.contains_key("x-shard"));
|
||||
apply_with_vars(&mut request, &compiled.request, &vars);
|
||||
assert_eq!(request["x-shard"], "mp3_2");
|
||||
// Values that are not valid header values drop the header instead of failing.
|
||||
let mut bad = HeaderMap::new();
|
||||
apply_wire(&mut bad, &compiled.response, &Vars { srv_id: Some("a b"), ..vars.clone() });
|
||||
assert_eq!(bad["x-s"], "a b@mp3 (HIT, -)");
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
//! Lowercase hexadecimal encoding shared by SHA-256 checksums and request IDs.
|
||||
//!
|
||||
//! Keep this independent of SHA-2's output type: digest 0.11 uses HybridArray,
|
||||
//! which no longer implements `LowerHex` for `format!("{:x}", digest)`.
|
||||
|
||||
pub(crate) fn encode_lower(bytes: &[u8]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut encoded = vec![0u8; bytes.len() * 2];
|
||||
|
||||
@@ -268,7 +268,6 @@ async fn error_log_loop(
|
||||
open_path = Some(path.clone());
|
||||
retry_after = None;
|
||||
}
|
||||
// Reopen after external rotation (logrotate `create`, mv, rm).
|
||||
if let Some((_, rotation)) = file.as_mut() {
|
||||
if rotation.rotated(&path).await {
|
||||
file = None;
|
||||
|
||||
@@ -11,10 +11,8 @@ pub struct LogEntry {
|
||||
pub authority: Option<String>,
|
||||
pub matched_by: Option<&'static str>,
|
||||
pub vhost: Option<String>,
|
||||
/// Redirect host that answered the request (its own per-site log file).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub redirect_host: Option<String>,
|
||||
/// Local 404 host that answered the request (its own per-site log file).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub local_host: Option<String>,
|
||||
pub route: Option<String>,
|
||||
|
||||
@@ -144,8 +144,6 @@ struct FileState {
|
||||
rotation: RotationCheck,
|
||||
}
|
||||
|
||||
/// Identity of an open log file, used to notice external rotation (logrotate
|
||||
/// `create`, mv, rm): the path then names a different file or none at all.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct FileIdentity {
|
||||
device: u64,
|
||||
@@ -179,8 +177,6 @@ impl RotationCheck {
|
||||
checked: Instant::now(),
|
||||
}
|
||||
}
|
||||
/// True when `path` no longer refers to the open file. Checked at most once per
|
||||
/// second, so a busy log costs one `stat` per second.
|
||||
async fn rotated(&mut self, path: &std::path::Path) -> bool {
|
||||
let Some(identity) = self.identity else {
|
||||
return false;
|
||||
@@ -197,9 +193,6 @@ impl RotationCheck {
|
||||
}
|
||||
const PER_VHOST_OPEN_FILES: usize = 64;
|
||||
|
||||
/// File name (without `.jsonl`) of a per-site access log: the vhost id, or
|
||||
/// `<id>.redirect` / `<id>.host404` for redirect and local 404 hosts (ids cannot
|
||||
/// contain dots, so these never collide with a vhost), else `_unmatched`.
|
||||
fn entry_log_name(entry: &LogEntry) -> String {
|
||||
if let Some(id) = entry.redirect_host.as_deref().filter(|id| crate::config::valid_id(id)) {
|
||||
return format!("{id}.redirect");
|
||||
|
||||
@@ -663,14 +663,12 @@ mod tests {
|
||||
let (_file, mut check) = open_access_file(path.clone()).await.unwrap();
|
||||
check.checked -= ROTATION_CHECK_INTERVAL * 2;
|
||||
assert!(!check.rotated(&path).await, "same file is not a rotation");
|
||||
// logrotate `create`: the old file is renamed and a new one created.
|
||||
std::fs::rename(&path, dir.path().join("app.jsonl.1")).unwrap();
|
||||
check.checked -= ROTATION_CHECK_INTERVAL * 2;
|
||||
assert!(check.rotated(&path).await, "missing path means rotated");
|
||||
std::fs::write(&path, b"").unwrap();
|
||||
check.checked -= ROTATION_CHECK_INTERVAL * 2;
|
||||
assert!(check.rotated(&path).await, "new file means rotated");
|
||||
// Checks are rate-limited.
|
||||
let (_file, mut fresh) = open_access_file(path.clone()).await.unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(!fresh.rotated(&path).await);
|
||||
|
||||
@@ -422,7 +422,6 @@ async fn run(
|
||||
};
|
||||
if headless {
|
||||
tasks.spawn(headless_reload_loop(state.clone(), shutdown.clone()));
|
||||
// Both tasks follow reloads: ACME settings or watch targets may change.
|
||||
state.tunnels.spawn(rust_proxy::acme::headless_loop(
|
||||
Arc::downgrade(&state),
|
||||
state.shutdown.clone(),
|
||||
|
||||
@@ -166,19 +166,11 @@ enum TlsCommand {
|
||||
key: PathBuf,
|
||||
},
|
||||
Reload,
|
||||
/// Check or force renewal of ACME certificates.
|
||||
///
|
||||
/// Panel mode: one managed certificate (`--id`) through the administration
|
||||
/// API. Headless mode: the running service's ACME certificates (all, or
|
||||
/// those matching `--id` by certificate id or domain name).
|
||||
Renew {
|
||||
/// Certificate id; in headless mode also a domain name (repeatable)
|
||||
#[arg(long = "id", value_delimiter = ',')]
|
||||
ids: Vec<String>,
|
||||
/// Request a new certificate even if it is not due yet (counts against CA rate limits)
|
||||
#[arg(long, conflicts_with = "dry_run")]
|
||||
force: bool,
|
||||
/// Panel mode only: validate the renewal without deploying it
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
},
|
||||
@@ -217,60 +209,43 @@ struct ServeOptions {
|
||||
headless_tls: Box<HeadlessTlsArgs>,
|
||||
}
|
||||
|
||||
/// Headless-only TLS sources: certificate files and automatic ACME (DV) certificates.
|
||||
#[derive(Args, Clone, Default)]
|
||||
struct HeadlessTlsArgs {
|
||||
/// Certificate chain (PEM) to serve; pair each with --tls-key-file (headless only, repeatable)
|
||||
#[arg(long = "tls-cert-file", env = "RUST_PROXY_TLS_CERT_FILE", value_delimiter = ',', value_name = "PEM")]
|
||||
tls_cert_file: Vec<PathBuf>,
|
||||
/// Private key (PEM) for the --tls-cert-file at the same position
|
||||
#[arg(long = "tls-key-file", env = "RUST_PROXY_TLS_KEY_FILE", value_delimiter = ',', value_name = "PEM")]
|
||||
tls_key_file: Vec<PathBuf>,
|
||||
/// Directory with certificate/key pairs, e.g. /etc/letsencrypt/live (headless only, repeatable)
|
||||
#[arg(long = "tls-cert-dir", env = "RUST_PROXY_TLS_CERT_DIR", value_delimiter = ',', value_name = "DIR")]
|
||||
tls_cert_dir: Vec<PathBuf>,
|
||||
/// Names of one ACME certificate, comma-separated (repeat for more certificates; ';' in the environment)
|
||||
#[arg(long = "acme-domains", env = "RUST_PROXY_ACME_DOMAINS", value_delimiter = ';', value_name = "NAMES")]
|
||||
acme_domains: Vec<String>,
|
||||
/// Contact e-mail for the ACME account
|
||||
#[arg(long = "acme-email", env = "RUST_PROXY_ACME_EMAIL")]
|
||||
acme_email: Option<String>,
|
||||
/// Accept the ACME CA terms of service (Let's Encrypt Subscriber Agreement)
|
||||
#[arg(long = "acme-agree-tos", env = "RUST_PROXY_ACME_AGREE_TOS", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_agree_tos: bool,
|
||||
/// Use the Let's Encrypt staging CA (untrusted test certificates, high rate limits)
|
||||
#[arg(long = "acme-staging", env = "RUST_PROXY_ACME_STAGING", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_staging: bool,
|
||||
/// Challenge: http01 (default) or DNS-01 via cloudflare, ovh, rfc2136 (required for wildcards)
|
||||
#[arg(long = "acme-provider", env = "RUST_PROXY_ACME_PROVIDER",
|
||||
value_parser = ["http01", "cloudflare", "ovh", "rfc2136"])]
|
||||
acme_provider: Option<String>,
|
||||
/// Certbot-style INI file with DNS provider credentials (mode 0600)
|
||||
#[arg(long = "acme-dns-credentials", env = "RUST_PROXY_ACME_DNS_CREDENTIALS", value_name = "INI")]
|
||||
acme_dns_credentials: Option<PathBuf>,
|
||||
/// DNS-01 propagation wait in seconds [default: 60]
|
||||
#[arg(long = "acme-propagation-seconds", env = "RUST_PROXY_ACME_PROPAGATION_SECONDS",
|
||||
value_parser = clap::value_parser!(u64).range(10..=900))]
|
||||
acme_propagation_seconds: Option<u64>,
|
||||
/// Renew when this many days or fewer remain [default: 30]
|
||||
#[arg(long = "acme-renew-days", env = "RUST_PROXY_ACME_RENEW_DAYS",
|
||||
value_parser = clap::value_parser!(u64).range(1..=60))]
|
||||
acme_renew_days: Option<u64>,
|
||||
/// Also issue certificates for every vhost host that no other certificate covers
|
||||
#[arg(long = "acme-auto", env = "RUST_PROXY_ACME_AUTO", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_auto: bool,
|
||||
/// Vhost without a configuration file: HOSTS=URLS, e.g. app.example.com=http://127.0.0.1:3000
|
||||
/// (repeatable; ';' between routes in the environment)
|
||||
#[arg(long = "route", env = "RUST_PROXY_ROUTES", value_delimiter = ';', value_name = "HOSTS=URLS")]
|
||||
route: Vec<String>,
|
||||
/// Redirect plain HTTP to HTTPS for --route vhosts (308)
|
||||
#[arg(long = "force-https", env = "RUST_PROXY_FORCE_HTTPS", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
force_https: bool,
|
||||
/// Reload automatically when the configuration or certificate files change
|
||||
#[arg(long = "watch", env = "RUST_PROXY_WATCH", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
watch: bool,
|
||||
@@ -287,9 +262,6 @@ impl HeadlessTlsArgs {
|
||||
|| self.watch
|
||||
}
|
||||
|
||||
/// Command-line headless options. ACME settings are validated when the
|
||||
/// configuration is loaded, because they may be completed by the
|
||||
/// `"headless"` section of the file.
|
||||
fn resolve(self, headless: bool) -> Result<rust_proxy::runtime::HeadlessOptions> {
|
||||
if !self.requested() {
|
||||
return Ok(Default::default());
|
||||
|
||||
@@ -33,7 +33,6 @@ async fn headless_reload_loop(
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
|
||||
// SIGUSR1: `rust-proxy --headless tls renew` left a renewal request.
|
||||
let mut renew =
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::user_defined1())?;
|
||||
loop {
|
||||
@@ -70,7 +69,6 @@ async fn headless_reload_loop(
|
||||
}
|
||||
}
|
||||
|
||||
/// Process id of the running headless service, from `<data-dir>/rustproxy.pid`.
|
||||
fn headless_service_pid(data_dir: &Path) -> Result<i32> {
|
||||
let path = data_dir.join(HEADLESS_PID_FILE);
|
||||
let text = std::fs::read_to_string(&path).with_context(|| {
|
||||
@@ -125,8 +123,6 @@ fn signal_headless_reload(data_dir: &Path) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the process handles SIGUSR1 (0.40.1+). Older services would be
|
||||
/// terminated by it, so the request is refused instead.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn headless_service_handles_renew(pid: i32) -> bool {
|
||||
std::fs::read_to_string(format!("/proc/{pid}/status"))
|
||||
@@ -140,8 +136,6 @@ fn headless_service_handles_renew(pid: i32) -> bool {
|
||||
.is_some_and(|mask| mask & (1 << (libc::SIGUSR1 - 1)) != 0)
|
||||
}
|
||||
|
||||
/// `rust-proxy --headless tls renew [--force] [--id ID|DOMAIN ...]`: asks the
|
||||
/// running headless service to check (or re-issue) its ACME certificates now.
|
||||
fn signal_headless_renew(data_dir: &Path, targets: Vec<String>, force: bool) -> Result<()> {
|
||||
let pid = headless_service_pid(data_dir)?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -275,9 +269,6 @@ async fn validate_headless_file(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fingerprint of everything a headless reload reads from disk: the
|
||||
/// configuration file, certificate files and the contents of certificate
|
||||
/// directories (symbolic links are followed, so a Certbot renewal is seen).
|
||||
async fn headless_watch_stamp(state: &Arc<App>) -> Vec<(PathBuf, [i64; 4])> {
|
||||
let file = state
|
||||
.config_file
|
||||
@@ -339,8 +330,6 @@ async fn headless_watch_stamp(state: &Arc<App>) -> Vec<(PathBuf, [i64; 4])> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `--watch`: reloads when a watched file has changed and then stayed
|
||||
/// unchanged for one more poll (so half-written files are not applied).
|
||||
async fn headless_watch_loop(state: Arc<App>, shutdown: tokio_util::sync::CancellationToken) {
|
||||
let mut applied = headless_watch_stamp(&state).await;
|
||||
let mut pending: Option<Vec<(PathBuf, [i64; 4])>> = None;
|
||||
@@ -376,7 +365,6 @@ async fn headless_watch_loop(state: Arc<App>, shutdown: tokio_util::sync::Cancel
|
||||
);
|
||||
}
|
||||
}
|
||||
// Re-read after the reload: the watched set may have changed.
|
||||
applied = headless_watch_stamp(&state).await;
|
||||
}
|
||||
}
|
||||
@@ -314,7 +314,6 @@ pub fn replace_error(response: &mut Response, page: &Page) {
|
||||
replacement.headers_mut().append(name, value.clone());
|
||||
}
|
||||
}
|
||||
// Authentication challenges must never become shared-cache entries.
|
||||
if response
|
||||
.headers()
|
||||
.get(::http::header::CACHE_CONTROL)
|
||||
|
||||
@@ -192,8 +192,6 @@ impl CompiledPolicy {
|
||||
pub fn has_stage(&self, stage: Stage) -> bool {
|
||||
self.rules.iter().any(|r| r.stage == stage)
|
||||
}
|
||||
/// A backend response selected or changed using client-specific facts must
|
||||
/// not be admitted to a shared cache merely because it has a public TTL.
|
||||
pub fn requires_private_response(&self) -> bool {
|
||||
self.private_response
|
||||
}
|
||||
@@ -608,7 +606,6 @@ pub(super) fn compile(settings: &Settings) -> Result<CompiledPolicy> {
|
||||
<= 1024,
|
||||
"at most 1024 policy map entries per scope"
|
||||
);
|
||||
// Bound total regex programs, including converters, before allocation.
|
||||
fn regex_count(c: &Condition) -> usize {
|
||||
match c {
|
||||
Condition::All { all } | Condition::Any { any: all } => {
|
||||
@@ -667,8 +664,6 @@ pub(super) fn compile(settings: &Settings) -> Result<CompiledPolicy> {
|
||||
expression::identifier(name),
|
||||
"invalid policy ACL name {name:?}"
|
||||
);
|
||||
// Unused definitions must still be well formed, and cycles must never
|
||||
// become latent errors activated by a later edit.
|
||||
condition(
|
||||
acl,
|
||||
Stage::AfterResponse,
|
||||
|
||||
@@ -243,8 +243,6 @@ fn apply_action_inner(
|
||||
if location.is_empty() || HeaderValue::from_str(location).is_err() {
|
||||
return Err("invalid redirect Location; action skipped".into());
|
||||
}
|
||||
// Literal local paths and absolute HTTP(S) URLs only; prevent
|
||||
// network-path targets or non-HTTP URI schemes.
|
||||
let local = location.starts_with('/')
|
||||
&& !location.starts_with("//")
|
||||
&& !location.contains('\\');
|
||||
@@ -324,7 +322,6 @@ fn normalize(
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Wildcard Vary remains uncacheable, irrespective of any other tokens.
|
||||
if name == http::header::VARY && tokens.iter().any(|token| token == "*") {
|
||||
tokens = vec!["*".into()];
|
||||
}
|
||||
|
||||
@@ -49,8 +49,6 @@ fn read_effective(value: u8) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Redirect or local 404 host that answered instead of a vhost; it gets its own
|
||||
/// per-site access log file.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LogSite {
|
||||
Redirect(String),
|
||||
@@ -60,10 +58,7 @@ pub struct Exchange {
|
||||
pub vhost_metrics: Option<Arc<crate::metrics::VhostMetrics>>,
|
||||
pub vhost: Option<String>,
|
||||
pub route: Mutex<Option<String>>,
|
||||
/// Location chosen by conditional routing when it differs from the route the
|
||||
/// response layer saw before the request was forwarded.
|
||||
pub routed: Mutex<Option<Arc<crate::config::CompiledRoute>>>,
|
||||
/// Request values for response header rules with `%[variables]`.
|
||||
pub header_vars: Mutex<Option<Arc<crate::headers::RequestVars>>>,
|
||||
pub log_site: Mutex<Option<LogSite>>,
|
||||
pub source: AtomicU8,
|
||||
|
||||
@@ -261,7 +261,6 @@ fn apply_response_age_rules(
|
||||
crate::headers::apply_wire_age(headers, &route.headers.response);
|
||||
}
|
||||
}
|
||||
/// Final-delivery response rules: `Age` and rules with `%[variables]`.
|
||||
fn apply_response_wire_rules(
|
||||
headers: &mut http::HeaderMap,
|
||||
snapshot: &crate::config::Snapshot,
|
||||
|
||||
@@ -251,9 +251,6 @@ fn intercept_route_origin_error(
|
||||
response
|
||||
}
|
||||
|
||||
// Web Server responses are not necessarily origin responses. PHP/FastCGI and
|
||||
// local .htaccess ErrorDocument responses carry OriginProvidedResponse from
|
||||
// web_server::serve; generated filesystem errors do not.
|
||||
fn intercept_route_web_error(
|
||||
response: Response,
|
||||
route: &crate::config::CompiledRoute,
|
||||
|
||||
@@ -546,8 +546,6 @@ mod cache_fast_path_tests {
|
||||
"authorization",
|
||||
"x-request-id",
|
||||
] {
|
||||
// Static asset responses in this fixture must not echo a
|
||||
// request cookie into a publicly shared response header.
|
||||
if name == "cookie" && parts.uri.path().starts_with("/vary-cookie") {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
// End-to-end regression tests for the static-asset Cookie policy and the
|
||||
// central cache decision (cache::request_gate / static_cookie_guard_relaxation
|
||||
// / shared_static_response_reason). They drive the real proxy router against
|
||||
// an in-process origin and inspect X-Cache, X-Cache-Reason, Cache-Status and
|
||||
// the number of origin requests.
|
||||
mod static_cookie_policy_tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
@@ -148,8 +143,6 @@ mod static_cookie_policy_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Origin with one behaviour per path. Bodies of *private* resources embed
|
||||
/// the request Cookie, so any cross-user leak is visible in assertions.
|
||||
async fn start_origin() -> Origin {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
@@ -185,7 +178,6 @@ mod static_cookie_policy_tests {
|
||||
body = "body{color:red}".into();
|
||||
}
|
||||
"/assets/drupal.js" => {
|
||||
// Typical web-server static reply: max-age without public.
|
||||
headers.push(("content-type", "application/javascript".into()));
|
||||
headers.push(("cache-control", "max-age=1209600".into()));
|
||||
body = "Drupal.behaviors={};".into();
|
||||
@@ -210,7 +202,6 @@ mod static_cookie_policy_tests {
|
||||
}
|
||||
}
|
||||
"/user/avatar.png" => {
|
||||
// Private route: session required by the application.
|
||||
match &cookie {
|
||||
Some(cookie) => {
|
||||
headers.push(("content-type", "image/png".into()));
|
||||
@@ -235,7 +226,6 @@ mod static_cookie_policy_tests {
|
||||
body = format!("refresh[{}]", cookie.as_deref().unwrap_or("-"));
|
||||
}
|
||||
"/assets/fallback.js" => {
|
||||
// SPA fallback: HTML (personalised) under a .js name.
|
||||
headers.push(("content-type", "text/html; charset=utf-8".into()));
|
||||
headers.push(("cache-control", "public, max-age=600".into()));
|
||||
body = format!("<html>hello [{}]</html>", cookie.as_deref().unwrap_or("-"));
|
||||
@@ -271,8 +261,6 @@ mod static_cookie_policy_tests {
|
||||
serde_json::from_value(value).unwrap()
|
||||
}
|
||||
|
||||
/// The security and session templates as shipped in 0.39.2 (cookie
|
||||
/// guards use cookie_pass, everything else an explicit pass).
|
||||
fn shipped_rules() -> Vec<crate::cache::Rule> {
|
||||
vec![
|
||||
rule(
|
||||
@@ -315,13 +303,11 @@ mod static_cookie_policy_tests {
|
||||
let origin = start_origin().await;
|
||||
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
|
||||
|
||||
// Anonymous: MISS -> HIT.
|
||||
let first = fixture.get("/assets/app.css", &[]).await;
|
||||
assert_eq!((first.cache(), first.reason()), ("MISS", "cache_miss"));
|
||||
let second = fixture.get("/assets/app.css", &[]).await;
|
||||
assert_eq!(second.cache(), "HIT");
|
||||
|
||||
// Logged-in on a different public asset: MISS (guard relaxed) -> HIT.
|
||||
let logged = fixture
|
||||
.get("/assets/auth.css", &[("cookie", SESSION)])
|
||||
.await;
|
||||
@@ -334,7 +320,6 @@ mod static_cookie_policy_tests {
|
||||
.get("/assets/auth.css", &[("cookie", SESSION)])
|
||||
.await;
|
||||
assert_eq!(again.cache(), "HIT");
|
||||
// The same object is shared with anonymous clients and other users.
|
||||
let anonymous = fixture.get("/assets/auth.css", &[]).await;
|
||||
assert_eq!(anonymous.cache(), "HIT");
|
||||
let other = fixture
|
||||
@@ -342,7 +327,6 @@ mod static_cookie_policy_tests {
|
||||
.await;
|
||||
assert_eq!(other.cache(), "HIT");
|
||||
assert_eq!(origin.count("/assets/auth.css"), 1);
|
||||
// Anonymous fill is reused by a logged-in client too.
|
||||
let logged_app = fixture.get("/assets/app.css", &[("cookie", SESSION)]).await;
|
||||
assert_eq!(logged_app.cache(), "HIT");
|
||||
assert_eq!(origin.count("/assets/app.css"), 1);
|
||||
@@ -369,13 +353,11 @@ mod static_cookie_policy_tests {
|
||||
.get("/assets/drupal.js?v=7.1", &[("cookie", DRUPAL6)])
|
||||
.await;
|
||||
assert_eq!(second.cache(), "HIT");
|
||||
// Query string is part of the key: another version is a new object.
|
||||
let other_version = fixture
|
||||
.get("/assets/drupal.js?v=7.2", &[("cookie", DRUPAL6)])
|
||||
.await;
|
||||
assert_eq!(other_version.cache(), "MISS");
|
||||
assert_eq!(origin.count("/assets/drupal.js"), 2);
|
||||
// Drupal HTML for the same session is still bypassed by the guard.
|
||||
let page = fixture.get("/node/1", &[("cookie", DRUPAL6)]).await;
|
||||
assert_eq!(
|
||||
(page.cache(), page.reason()),
|
||||
@@ -426,7 +408,6 @@ mod static_cookie_policy_tests {
|
||||
.await;
|
||||
assert_eq!(logged_gzip.cache(), "HIT");
|
||||
assert_eq!(logged_gzip.body(), "gzip-css");
|
||||
// A different Accept-Encoding is a different variant ...
|
||||
let logged_plain = fixture
|
||||
.get(
|
||||
"/assets/vary.css",
|
||||
@@ -435,7 +416,6 @@ mod static_cookie_policy_tests {
|
||||
.await;
|
||||
assert_eq!(logged_plain.cache(), "MISS");
|
||||
assert_eq!(logged_plain.body(), "plain-css");
|
||||
// ... and that variant is shared with anonymous identity clients.
|
||||
let anon_plain = fixture
|
||||
.get("/assets/vary.css", &[("accept-encoding", "identity")])
|
||||
.await;
|
||||
@@ -444,7 +424,6 @@ mod static_cookie_policy_tests {
|
||||
assert_eq!(origin.count("/assets/vary.css"), 2);
|
||||
fixture.stop().await;
|
||||
|
||||
// Without the Vary: Cookie option nothing with Vary: Cookie is stored.
|
||||
let origin = start_origin().await;
|
||||
let mut config = test_config(origin.addr, shipped_rules());
|
||||
config.cache.static_ignore_vary_cookie = false;
|
||||
@@ -477,8 +456,6 @@ mod static_cookie_policy_tests {
|
||||
("BYPASS", crate::cache::REASON_VCL_COOKIE_GUARD)
|
||||
);
|
||||
assert_eq!(page.body(), format!("<p>page for [{SESSION}]</p>"));
|
||||
// A private-route image is protected by an explicit pass, which the
|
||||
// static policy must never relax, even with a public-looking reply.
|
||||
let avatar = fixture
|
||||
.get("/user/avatar.png", &[("cookie", SESSION)])
|
||||
.await;
|
||||
@@ -496,7 +473,6 @@ mod static_cookie_policy_tests {
|
||||
#[tokio::test]
|
||||
async fn authorization_is_an_absolute_bypass_for_static_assets() {
|
||||
let origin = start_origin().await;
|
||||
// With the shipped Authorization rule ...
|
||||
let fixture = Fixture::new(test_config(origin.addr, shipped_rules())).await;
|
||||
let response = fixture
|
||||
.get(
|
||||
@@ -509,7 +485,6 @@ mod static_cookie_policy_tests {
|
||||
("BYPASS", "cache_rule")
|
||||
);
|
||||
fixture.stop().await;
|
||||
// ... and without any rules (built-in policy).
|
||||
let fixture = Fixture::new(test_config(origin.addr, Vec::new())).await;
|
||||
for headers in [
|
||||
vec![("authorization", "Bearer t")],
|
||||
@@ -529,8 +504,6 @@ mod static_cookie_policy_tests {
|
||||
async fn private_set_cookie_dynamic_and_unproven_statics_are_not_shared() {
|
||||
let origin = start_origin().await;
|
||||
let mut rules = shipped_rules();
|
||||
// Operator response rules must not turn a private Cookie-bearing fill
|
||||
// into a shared object.
|
||||
rules.push(rule(serde_json::json!({"id": "force-png", "stage": "response", "conditions": [{"field": "path", "operator": "prefix", "values": ["/assets/private.png"]}], "actions": [{"type": "ignore_cache_control"}, {"type": "ttl", "seconds": 600}]})));
|
||||
rules.push(rule(serde_json::json!({"id": "strip-sc", "stage": "response", "conditions": [{"field": "path", "operator": "prefix", "values": ["/assets/set-cookie.css"]}], "actions": [{"type": "strip_set_cookie"}]})));
|
||||
let fixture = Fixture::new(test_config(origin.addr, rules)).await;
|
||||
@@ -547,7 +520,6 @@ mod static_cookie_policy_tests {
|
||||
"{path}"
|
||||
);
|
||||
assert!(logged.body().contains(SESSION), "{path}");
|
||||
// The next client must reach the origin and never see that body.
|
||||
let anonymous = fixture.get(path, &[]).await;
|
||||
assert_ne!(anonymous.cache(), "HIT", "{path}");
|
||||
assert!(!anonymous.body().contains(SESSION), "{path}");
|
||||
@@ -560,7 +532,6 @@ mod static_cookie_policy_tests {
|
||||
#[tokio::test]
|
||||
async fn explicit_vcl_pass_keeps_its_semantics() {
|
||||
let origin = start_origin().await;
|
||||
// 0.39.1 template shape: a plain pass on any Cookie.
|
||||
let legacy = vec![rule(
|
||||
serde_json::json!({"id": "any-cookie", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "pass"}], "stop": true}),
|
||||
)];
|
||||
@@ -579,7 +550,6 @@ mod static_cookie_policy_tests {
|
||||
fixture.get("/assets/explicit.css", &[]).await.cache(),
|
||||
"HIT"
|
||||
);
|
||||
// The anonymous object is still not served to the explicitly passed client.
|
||||
let logged = fixture
|
||||
.get("/assets/explicit.css", &[("cookie", SESSION)])
|
||||
.await;
|
||||
@@ -587,7 +557,6 @@ mod static_cookie_policy_tests {
|
||||
assert_eq!(origin.count("/assets/explicit.css"), 4);
|
||||
fixture.stop().await;
|
||||
|
||||
// An explicit pass placed after a terminal Cookie guard still applies.
|
||||
let origin = start_origin().await;
|
||||
let mut rules = vec![rule(
|
||||
serde_json::json!({"id": "any-cookie", "conditions": [{"field": "header", "name": "Cookie", "operator": "exists"}], "actions": [{"type": "cookie_pass"}], "stop": true}),
|
||||
@@ -618,8 +587,6 @@ mod static_cookie_policy_tests {
|
||||
let mut anonymous = Vec::new();
|
||||
let mut logged = Vec::new();
|
||||
for method in [Method::HEAD, Method::GET, Method::HEAD] {
|
||||
// A HEAD miss is filled from an upstream GET whose body is stored
|
||||
// in the background; let both fills settle before the next step.
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
anonymous.push(
|
||||
fixture
|
||||
@@ -638,7 +605,6 @@ mod static_cookie_policy_tests {
|
||||
}
|
||||
assert_eq!(anonymous, logged);
|
||||
assert_eq!(logged, ["MISS", "HIT", "HIT"]);
|
||||
// GET-filled object answers a logged HEAD and vice versa.
|
||||
let head = fixture
|
||||
.request(Method::HEAD, "/assets/app.css", &[("cookie", DRUPAL6)])
|
||||
.await;
|
||||
@@ -668,7 +634,6 @@ mod static_cookie_policy_tests {
|
||||
assert_eq!(origin.count("/assets/app.css"), 2);
|
||||
fixture.stop().await;
|
||||
|
||||
// Without rules, the built-in Cookie policy still bypasses.
|
||||
let origin = start_origin().await;
|
||||
let mut config = test_config(origin.addr, Vec::new());
|
||||
config.cache.static_ignore_cookies = false;
|
||||
@@ -711,7 +676,6 @@ mod static_cookie_policy_tests {
|
||||
.cache(),
|
||||
"HIT"
|
||||
);
|
||||
// A lowered entry limit evicts instead of purging.
|
||||
fixture.change(|config| config.cache.max_entries = 1).await;
|
||||
let kept = [
|
||||
fixture.get("/assets/app.css", &[]).await.cache().to_owned(),
|
||||
@@ -727,7 +691,6 @@ mod static_cookie_policy_tests {
|
||||
.await;
|
||||
assert_eq!(fixture.get("/fonts/site.woff2", &[]).await.cache(), "MISS");
|
||||
assert_eq!(fixture.get("/fonts/site.woff2", &[]).await.cache(), "HIT");
|
||||
// Representation/privacy changes still purge.
|
||||
fixture
|
||||
.change(|config| config.cache.default_ttl_seconds = 30)
|
||||
.await;
|
||||
|
||||
@@ -139,8 +139,6 @@
|
||||
} else {
|
||||
(std::mem::take(&mut request_headers), false)
|
||||
};
|
||||
// Vhost Basic authentication already removed untrusted credentials. Forward
|
||||
// only the verified value, when the operator selected forward_credentials.
|
||||
let mut origin_request_headers = origin_request_headers;
|
||||
if let Some(auth) = frontend.and_then(|f| f.basic_auth.as_ref()) {
|
||||
auth.apply_upstream(&mut origin_request_headers, basic_identity.clone());
|
||||
|
||||
@@ -27,20 +27,14 @@ pub fn read_headless(
|
||||
Ok((load.config, load.fingerprint))
|
||||
}
|
||||
|
||||
/// A headless configuration with every command-line and file TLS source applied.
|
||||
pub struct HeadlessLoad {
|
||||
pub config: Config,
|
||||
pub fingerprint: Fingerprint,
|
||||
/// Effective TLS sources (command line + `"headless"` section of the file).
|
||||
pub tls: crate::runtime::HeadlessTls,
|
||||
/// Number of certificates the TLS sources added.
|
||||
pub added_certificates: usize,
|
||||
/// Automatic reload on file changes (`--watch` or `"headless": {"watch": true}`).
|
||||
pub watch: bool,
|
||||
}
|
||||
|
||||
/// Loads the headless configuration with the options registered at start.
|
||||
/// Without a file (only `--route`) an empty document is used.
|
||||
pub fn load_headless(
|
||||
path: Option<&Path>,
|
||||
listeners: &crate::settings::Listeners,
|
||||
@@ -85,8 +79,6 @@ pub fn load_headless_with(
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads a headless document without command-line options; the `"headless"`
|
||||
/// section is accepted and ignored.
|
||||
pub fn headless_config(contents: &[u8], listeners: &crate::settings::Listeners) -> Result<Config> {
|
||||
Ok(headless_document(contents, listeners, &Default::default())?.0)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
// Headless TLS sources given on the command line (or in the service
|
||||
// environment): certificate files, certificate directories and certificates
|
||||
// issued by the headless ACME loop. They are merged into the configuration
|
||||
// read from `--config` on every start, reload and `config validate`; the file
|
||||
// itself is never changed.
|
||||
|
||||
/// File in `<data-dir>/certs` recording the certificates issued in headless mode.
|
||||
pub const HEADLESS_ACME_STATE: &str = "headless-acme.json";
|
||||
const HEADLESS_ACME_STATE_LIMIT: u64 = 262_144;
|
||||
const MAX_HEADLESS_TLS_CERTIFICATES: usize = 256;
|
||||
@@ -13,29 +7,20 @@ const MAX_HEADLESS_ACME_NAMES: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HeadlessTls {
|
||||
/// Absolute (certificate chain, private key) pairs.
|
||||
pub cert_files: Vec<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
/// Absolute directories scanned for certificate/key pairs on every load.
|
||||
pub cert_dirs: Vec<std::path::PathBuf>,
|
||||
pub acme: Option<HeadlessAcme>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HeadlessAcme {
|
||||
/// One entry per certificate; each holds 1..=16 normalized names
|
||||
/// (`*.example.com` for wildcards).
|
||||
pub certificates: Vec<Vec<String>>,
|
||||
pub email: String,
|
||||
/// `production` or `staging`.
|
||||
pub environment: String,
|
||||
/// `http01`, `cloudflare`, `ovh` or `rfc2136`.
|
||||
pub provider: String,
|
||||
/// Certbot-style INI credentials for DNS-01 providers.
|
||||
pub dns_credentials: Option<std::path::PathBuf>,
|
||||
pub propagation_seconds: u64,
|
||||
pub renew_before_days: i64,
|
||||
/// Also issue certificates for every vhost/redirect host that no other
|
||||
/// certificate covers (like a Traefik certificate resolver on all routers).
|
||||
pub auto: bool,
|
||||
}
|
||||
|
||||
@@ -128,7 +113,6 @@ fn valid_acme_email(value: &str) -> bool {
|
||||
.is_some_and(|(left, right)| !left.is_empty() && !right.is_empty())
|
||||
}
|
||||
|
||||
/// Parses one `--acme-domains` value (`example.com,www.example.com`).
|
||||
pub fn parse_headless_acme_names(value: &str) -> anyhow::Result<Vec<String>> {
|
||||
let mut names = Vec::new();
|
||||
for raw in value.split(',').map(str::trim).filter(|raw| !raw.is_empty()) {
|
||||
@@ -192,7 +176,6 @@ fn short_digest(value: &[u8]) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stable certificate id of a headless ACME certificate (independent of name order).
|
||||
pub fn headless_acme_certificate_id(names: &[String]) -> String {
|
||||
let mut sorted = names.to_vec();
|
||||
sorted.sort();
|
||||
@@ -220,7 +203,6 @@ pub struct HeadlessAcmeEntry {
|
||||
pub key_file: String,
|
||||
#[serde(default)]
|
||||
pub issued_at: i64,
|
||||
/// Issued by `acme.auto` for vhost hosts rather than listed explicitly.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub auto: bool,
|
||||
}
|
||||
@@ -329,11 +311,6 @@ fn headless_pair(id: String, cert: &std::path::Path, key: &std::path::Path) -> c
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds certificate/key pairs in a directory. Supported layouts:
|
||||
/// - the directory itself holds `fullchain.pem` + `privkey.pem` (one Certbot lineage),
|
||||
/// - subdirectories with `fullchain.pem` + `privkey.pem` (Certbot `/etc/letsencrypt/live`),
|
||||
/// - subdirectories `<name>/` with `fullchain.cer` + `<name>.key` (acme.sh),
|
||||
/// - flat files `<name>.crt|.pem|.cer` + `<name>.key`.
|
||||
pub fn scan_headless_certificate_dir(
|
||||
dir: &std::path::Path,
|
||||
) -> anyhow::Result<Vec<crate::tls::Certificate>> {
|
||||
@@ -414,7 +391,6 @@ pub fn scan_headless_certificate_dir(
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Certificates that the headless TLS options contribute right now.
|
||||
pub fn headless_tls_certificates(
|
||||
tls: &HeadlessTls,
|
||||
cert_dir: Option<&std::path::Path>,
|
||||
@@ -487,9 +463,6 @@ pub fn headless_tls_certificates(
|
||||
Ok(certificates)
|
||||
}
|
||||
|
||||
/// Adds the headless TLS certificates to a configuration read from the file.
|
||||
/// Host names are taken from each certificate's subject alternative names, so
|
||||
/// a vhost whose host the certificate covers serves it without any binding.
|
||||
pub fn apply_headless_tls(
|
||||
config: &mut config::Config,
|
||||
tls: &HeadlessTls,
|
||||
@@ -512,12 +485,9 @@ pub fn apply_headless_tls(
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// ACME settings as given on the command line or in the `headless.acme`
|
||||
/// section of the configuration file; merged and validated into [`HeadlessAcme`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessAcmeSettings {
|
||||
/// One entry per certificate: a list of names or a comma-separated string.
|
||||
pub domains: Vec<HeadlessNames>,
|
||||
pub auto: bool,
|
||||
pub email: Option<String>,
|
||||
@@ -550,7 +520,6 @@ impl HeadlessAcmeSettings {
|
||||
!self.domains.is_empty() || self.auto
|
||||
}
|
||||
|
||||
/// `primary` (command line) wins for single values; lists are joined.
|
||||
fn merge(primary: &Self, secondary: &Self) -> Self {
|
||||
let mut domains = primary.domains.clone();
|
||||
domains.extend(secondary.domains.iter().cloned());
|
||||
@@ -626,9 +595,6 @@ pub struct HeadlessFileTls {
|
||||
pub directories: Vec<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// The optional top-level `"headless"` object of a headless configuration
|
||||
/// file. It is removed before the rest is read as a normal configuration, so
|
||||
/// the panel format is unchanged. Relative paths are relative to the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessFileSettings {
|
||||
@@ -637,7 +603,6 @@ pub struct HeadlessFileSettings {
|
||||
pub watch: bool,
|
||||
}
|
||||
|
||||
/// `--route HOSTS=URLS`: a vhost generated without a configuration file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HeadlessRoute {
|
||||
pub hosts: Vec<String>,
|
||||
@@ -645,7 +610,6 @@ pub struct HeadlessRoute {
|
||||
}
|
||||
|
||||
impl HeadlessRoute {
|
||||
/// Parses `app.example.com,www.app.example.com=http://10.0.0.1:3000,http://10.0.0.2:3000`.
|
||||
pub fn parse(value: &str) -> anyhow::Result<Self> {
|
||||
let (hosts, backends) = value.split_once('=').ok_or_else(|| {
|
||||
anyhow::anyhow!("--route expects HOSTS=URLS, for example app.example.com=http://127.0.0.1:3000")
|
||||
@@ -694,7 +658,6 @@ impl HeadlessRoute {
|
||||
)
|
||||
}
|
||||
|
||||
/// The vhost as configuration JSON (defaults are applied by the normal parser).
|
||||
pub fn vhost_json(&self, force_https: bool) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"id": self.id(),
|
||||
@@ -711,7 +674,6 @@ impl HeadlessRoute {
|
||||
}
|
||||
}
|
||||
|
||||
/// Headless options from the command line / service environment.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HeadlessOptions {
|
||||
pub cert_files: Vec<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
@@ -727,7 +689,6 @@ impl HeadlessOptions {
|
||||
self == &Self::default()
|
||||
}
|
||||
|
||||
/// Effective TLS sources: command line first, then the file section.
|
||||
pub fn resolve(
|
||||
&self,
|
||||
file: &HeadlessFileSettings,
|
||||
@@ -742,7 +703,6 @@ impl HeadlessOptions {
|
||||
}));
|
||||
let mut cert_dirs = self.cert_dirs.clone();
|
||||
cert_dirs.extend(file.tls.directories.iter().map(|dir| absolute_in(file_dir, dir)));
|
||||
// Command-line relative paths were already resolved against the working directory.
|
||||
let acme = HeadlessAcmeSettings::merge(&self.acme, &file.acme).resolve(file_dir)?;
|
||||
Ok(HeadlessTls {
|
||||
cert_files,
|
||||
@@ -759,7 +719,6 @@ static HEADLESS_EFFECTIVE: std::sync::Mutex<Option<(HeadlessTls, bool)>> =
|
||||
static HEADLESS_CHANGED: std::sync::LazyLock<tokio::sync::Notify> =
|
||||
std::sync::LazyLock::new(tokio::sync::Notify::new);
|
||||
|
||||
/// Registers the command-line headless options of the running service (once, at start).
|
||||
pub fn configure_headless_options(options: HeadlessOptions, cert_dir: std::path::PathBuf) -> bool {
|
||||
HEADLESS_OPTIONS.set((options, cert_dir)).is_ok()
|
||||
}
|
||||
@@ -772,8 +731,6 @@ pub fn headless_cert_dir() -> Option<&'static std::path::Path> {
|
||||
HEADLESS_OPTIONS.get().map(|(_, dir)| dir.as_path())
|
||||
}
|
||||
|
||||
/// Records the TLS sources of the configuration that is now active and wakes
|
||||
/// the headless ACME and watch tasks.
|
||||
pub fn publish_headless_tls(tls: HeadlessTls, watch: bool) {
|
||||
if let Ok(mut slot) = HEADLESS_EFFECTIVE.lock() {
|
||||
*slot = Some((tls, watch));
|
||||
@@ -781,7 +738,6 @@ pub fn publish_headless_tls(tls: HeadlessTls, watch: bool) {
|
||||
HEADLESS_CHANGED.notify_one();
|
||||
}
|
||||
|
||||
/// TLS sources of the active configuration (`None` before the first load).
|
||||
pub fn headless_tls() -> Option<HeadlessTls> {
|
||||
HEADLESS_EFFECTIVE
|
||||
.lock()
|
||||
@@ -797,7 +753,6 @@ pub fn headless_watch_requested() -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Waits until the active headless configuration changes.
|
||||
pub async fn headless_changed() {
|
||||
HEADLESS_CHANGED.notified().await;
|
||||
}
|
||||
@@ -810,9 +765,6 @@ fn covers(name: &str, host: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Host names that `acme.auto` should request: hosts of enabled vhosts and
|
||||
/// redirects that no other certificate (configured, file or explicit ACME)
|
||||
/// covers. One certificate per vhost (split into groups of 16 names).
|
||||
pub fn headless_auto_acme_groups(
|
||||
config: &config::Config,
|
||||
acme: &HeadlessAcme,
|
||||
@@ -865,7 +817,6 @@ pub fn headless_auto_acme_groups(
|
||||
|
||||
pub const MAX_HEADLESS_AUTO_CERTIFICATES: usize = 64;
|
||||
|
||||
/// Every host name served by enabled vhosts and redirects (lower case).
|
||||
pub fn headless_served_hosts(config: &config::Config) -> std::collections::HashSet<String> {
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for vhost in config.vhosts.iter().filter(|vhost| vhost.enabled) {
|
||||
@@ -879,8 +830,6 @@ pub fn headless_served_hosts(config: &config::Config) -> std::collections::HashS
|
||||
hosts
|
||||
}
|
||||
|
||||
/// Reads a Certbot-style DNS credentials INI file and returns the matching
|
||||
/// ACME request fields for the provider.
|
||||
pub fn headless_dns_credential_fields(
|
||||
provider: &str,
|
||||
path: &std::path::Path,
|
||||
|
||||
@@ -41,7 +41,6 @@ mod headless_tls_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a self-signed pair `<name>.pem`/`<name>.key` in `dir`.
|
||||
fn pair(dir: &std::path::Path, name: &str, hosts: &[&str]) {
|
||||
crate::tls::generate(dir, name, hosts.iter().map(|h| h.to_string()).collect()).unwrap();
|
||||
}
|
||||
@@ -81,7 +80,6 @@ mod headless_tls_tests {
|
||||
let c = headless_acme_certificate_id(&["example.com".into()]);
|
||||
assert!(a.starts_with("hl-acme-"));
|
||||
assert_ne!(a, c);
|
||||
// The label follows the first name, the digest the whole set.
|
||||
assert_eq!(&a[..a.len() - 8], "hl-acme-example-com-");
|
||||
assert_eq!(&a[a.len() - 8..], &b[b.len() - 8..]);
|
||||
let long = headless_acme_certificate_id(&[format!("{}.example.com", "a".repeat(63))]);
|
||||
@@ -145,13 +143,11 @@ mod headless_tls_tests {
|
||||
assert!(certificate.id.starts_with("hl-file-site-"));
|
||||
assert!(certificate.hosts.is_empty());
|
||||
assert!(certificate.issuer.is_none());
|
||||
// Same input, same id: reloads keep the identity stable.
|
||||
let mut again = minimal(&["app.example.com"]);
|
||||
apply_headless_tls(&mut again, &tls, Some(&cert_dir)).unwrap();
|
||||
assert_eq!(again.tls.certificates[0].id, certificate.id);
|
||||
config::compile(config, 1, &policy(&cert_dir)).unwrap();
|
||||
|
||||
// A configured certificate with the same id is a conflict, not a silent override.
|
||||
let mut duplicate = minimal(&["app.example.com"]);
|
||||
duplicate.tls.certificates.push(again.tls.certificates[0].clone());
|
||||
assert!(apply_headless_tls(&mut duplicate, &tls, Some(&cert_dir)).is_err());
|
||||
@@ -168,20 +164,17 @@ mod headless_tls_tests {
|
||||
let root = private_dir();
|
||||
let live = root.path().join("live");
|
||||
std::fs::create_dir(&live).unwrap();
|
||||
// Certbot: live/<name>/fullchain.pem + privkey.pem
|
||||
let scratch = private_dir();
|
||||
pair(scratch.path(), "a", &["a.example.com"]);
|
||||
let lineage = live.join("a.example.com");
|
||||
std::fs::create_dir(&lineage).unwrap();
|
||||
std::fs::copy(scratch.path().join("a.pem"), lineage.join("fullchain.pem")).unwrap();
|
||||
std::fs::copy(scratch.path().join("a.key"), lineage.join("privkey.pem")).unwrap();
|
||||
// acme.sh: <name>/fullchain.cer + <name>/<name>.key
|
||||
pair(scratch.path(), "b", &["b.example.com"]);
|
||||
let acme_sh = live.join("b.example.com");
|
||||
std::fs::create_dir(&acme_sh).unwrap();
|
||||
std::fs::copy(scratch.path().join("b.pem"), acme_sh.join("fullchain.cer")).unwrap();
|
||||
std::fs::copy(scratch.path().join("b.key"), acme_sh.join("b.example.com.key")).unwrap();
|
||||
// flat: <name>.crt + <name>.key; unmatched files and dot entries are ignored
|
||||
pair(scratch.path(), "c", &["c.example.com"]);
|
||||
std::fs::copy(scratch.path().join("c.pem"), live.join("c.crt")).unwrap();
|
||||
std::fs::copy(scratch.path().join("c.key"), live.join("c.key")).unwrap();
|
||||
@@ -211,7 +204,6 @@ mod headless_tls_tests {
|
||||
);
|
||||
assert!(found[0].id.starts_with("hl-file-a-example-com-"));
|
||||
|
||||
// A single lineage directory given directly.
|
||||
let single = scan_headless_certificate_dir(&lineage).unwrap();
|
||||
assert_eq!(single.len(), 1);
|
||||
assert!(single[0].cert_file.ends_with("fullchain.pem"));
|
||||
@@ -245,7 +237,6 @@ mod headless_tls_tests {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Nothing issued yet: no certificate and no error.
|
||||
let mut config = minimal(&["example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
|
||||
@@ -280,7 +271,6 @@ mod headless_tls_tests {
|
||||
assert_eq!(config.tls.certificates[0].cert_file, "acme-0123.pem");
|
||||
config::compile(config, 1, &policy(&cert_dir)).unwrap();
|
||||
|
||||
// A different environment, provider or name set waits for a new certificate.
|
||||
for changed in [
|
||||
HeadlessAcme {
|
||||
environment: "staging".into(),
|
||||
@@ -299,12 +289,10 @@ mod headless_tls_tests {
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
}
|
||||
|
||||
// Missing files are skipped rather than breaking the reload.
|
||||
std::fs::remove_file(cert_dir.join("acme-0123.key")).unwrap();
|
||||
let mut config = minimal(&["example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
|
||||
// Paths in the state file are confined to the certificate directory.
|
||||
std::fs::write(
|
||||
cert_dir.join(HEADLESS_ACME_STATE),
|
||||
format!(r#"{{"{id}":{{"provider":"http01","environment":"production","domains":["example.com"],"cert_file":"../x.pem","key_file":"acme-1.key"}}}}"#),
|
||||
@@ -402,7 +390,6 @@ mod headless_tls_tests {
|
||||
.unwrap();
|
||||
assert!(load.watch);
|
||||
assert_eq!(load.config.vhosts.len(), 1);
|
||||
// Relative paths are relative to the configuration file.
|
||||
assert_eq!(load.tls.cert_files[0].0, dir.path().join("certs/app.pem"));
|
||||
assert_eq!(load.tls.cert_files[0].1, std::path::PathBuf::from("/etc/ssl/app.key"));
|
||||
assert_eq!(load.tls.cert_dirs, vec![dir.path().join("live")]);
|
||||
@@ -418,7 +405,6 @@ mod headless_tls_tests {
|
||||
vec!["api.example.com".to_string()]
|
||||
]
|
||||
);
|
||||
// The panel-format reader ignores the section; unknown keys in it are errors.
|
||||
assert!(external_config::headless_config(file.as_bytes(), &startup()).is_ok());
|
||||
assert!(options(r#"{"headless":{"unknown":1}}"#, HeadlessOptions::default()).is_err());
|
||||
assert!(options(
|
||||
@@ -452,7 +438,6 @@ mod headless_tls_tests {
|
||||
assert_eq!(acme.provider, "cloudflare");
|
||||
assert_eq!(acme.certificates.len(), 2);
|
||||
assert_eq!(load.tls.cert_files.len(), 1);
|
||||
// CLI e-mail alone without consent anywhere is rejected at load time.
|
||||
let cli_only = HeadlessOptions {
|
||||
acme: HeadlessAcmeSettings {
|
||||
domains: vec![HeadlessNames::Text("api.example.com".into())],
|
||||
@@ -499,7 +484,6 @@ mod headless_tls_tests {
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
let compiled = config::compile(load.config, 1, &policy(&cert_dir));
|
||||
assert!(compiled.is_ok(), "{:?}", compiled.err());
|
||||
// A file vhost with the same id is a conflict.
|
||||
let id = cli.routes[0].id();
|
||||
let file = format!(
|
||||
r#"{{"vhosts":[{{"id":"{id}","frontend":{{"hosts":["x.example.com"]}},"backends":[{{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}}]}}]}}"#
|
||||
@@ -533,7 +517,6 @@ mod headless_tls_tests {
|
||||
groups,
|
||||
vec![vec!["shop.example.com".to_string(), "www.shop.example.com".to_string()]]
|
||||
);
|
||||
// With DNS-01 wildcard vhost hosts are requested as well.
|
||||
let mut dns = acme(&[&["listed.example.com"]], "cloudflare");
|
||||
dns.auto = true;
|
||||
let groups = headless_auto_acme_groups(&config, &dns, &cert_dir);
|
||||
|
||||
@@ -54,9 +54,6 @@ async fn health_status(axum::extract::State(state): axum::extract::State<Arc<App
|
||||
response
|
||||
}
|
||||
|
||||
/// Read-only certificate inventory (like Envoy's admin `/certs`): every
|
||||
/// active certificate with its source, names and expiry, plus the state of the
|
||||
/// headless ACME requests. Only public certificate data is shown.
|
||||
async fn certificate_status(
|
||||
axum::extract::State(state): axum::extract::State<Arc<App>>,
|
||||
) -> Response {
|
||||
|
||||
@@ -132,7 +132,6 @@ mod cache_revision_tests {
|
||||
CacheInvalidation::None
|
||||
));
|
||||
|
||||
// Operational cache tuning keeps HOT/COLD objects.
|
||||
let mut tuning = base.clone();
|
||||
tuning.cache.max_entries += 1;
|
||||
tuning.cache.max_bytes *= 2;
|
||||
@@ -165,7 +164,6 @@ mod cache_revision_tests {
|
||||
CacheInvalidation::None
|
||||
));
|
||||
|
||||
// Representation and privacy settings still purge everything.
|
||||
for change in [
|
||||
(|c: &mut config::Config| c.cache.default_ttl_seconds += 60) as fn(&mut config::Config),
|
||||
|c| c.cache.max_ttl_seconds += 60,
|
||||
|
||||
@@ -18,8 +18,6 @@ impl App {
|
||||
.as_ref()
|
||||
.map(|(path, _)| path.clone());
|
||||
if let Some(listeners) = headless_listeners() {
|
||||
// Headless: the file (or, with only --route, an empty document)
|
||||
// plus the command-line and "headless" TLS sources.
|
||||
let load = tokio::task::spawn_blocking(move || {
|
||||
external_config::load_headless(file.as_deref(), listeners)
|
||||
})
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
// Request conditions of a location (routing rules beyond the path). All conditions of
|
||||
// a location must hold (AND); each condition matches when any of its values matches
|
||||
// (OR); `negate` inverts one condition. Locations that do not match are skipped and
|
||||
// selection continues with the next candidate, so "OR" between rules is written as
|
||||
// several locations.
|
||||
|
||||
/// Request attribute tested by a [`RouteCondition`].
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ConditionSource {
|
||||
@@ -13,11 +7,8 @@ pub enum ConditionSource {
|
||||
Cookie,
|
||||
Query,
|
||||
Method,
|
||||
/// Client address as determined by RustProxy (trusted forwarding / Cloudflare).
|
||||
Ip,
|
||||
/// Request host name without port (useful with wildcard vhosts).
|
||||
Host,
|
||||
/// ISO country code from the GeoIP database or Cloudflare.
|
||||
Country,
|
||||
}
|
||||
impl ConditionSource {
|
||||
@@ -36,7 +27,6 @@ pub enum ConditionOperator {
|
||||
Suffix,
|
||||
Contains,
|
||||
Regex,
|
||||
/// IP address or CIDR network (only for `ip`).
|
||||
Cidr,
|
||||
}
|
||||
|
||||
@@ -221,7 +211,6 @@ pub struct CompiledCondition {
|
||||
fold: bool,
|
||||
}
|
||||
|
||||
/// Request attributes available to location conditions.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RouteRequest<'a> {
|
||||
pub method: &'a http::Method,
|
||||
@@ -312,7 +301,6 @@ impl CompiledCondition {
|
||||
}
|
||||
}
|
||||
|
||||
/// All conditions of one location.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CompiledConditions(Vec<CompiledCondition>);
|
||||
impl CompiledConditions {
|
||||
@@ -339,7 +327,6 @@ impl CompiledConditions {
|
||||
pub fn matches(&self, request: &RouteRequest<'_>) -> bool {
|
||||
self.0.iter().all(|condition| condition.matches(request))
|
||||
}
|
||||
/// Result of every condition, for the panel tester.
|
||||
pub fn explain(&self, request: &RouteRequest<'_>) -> Vec<bool> {
|
||||
self.0.iter().map(|condition| condition.matches(request)).collect()
|
||||
}
|
||||
|
||||
@@ -462,9 +462,6 @@ impl Service {
|
||||
name: self.name.clone(),
|
||||
sendfile: self.sendfile,
|
||||
root,
|
||||
// Keep explicit index priorities unchanged. For the stock static
|
||||
// default, PHP-capable services also try index.php when the HTML
|
||||
// indexes are absent, matching common PHP application installs.
|
||||
index: {
|
||||
let mut index = self.index.clone();
|
||||
if self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm
|
||||
|
||||
@@ -278,10 +278,7 @@ pub struct Php {
|
||||
#[serde(default = "default_php_extensions")]
|
||||
pub extensions: Vec<String>,
|
||||
pub endpoint: String,
|
||||
/// Existing configurations default to PHP-FPM; fcgiwrap runs installed CGI scripts.
|
||||
pub handler: FastCgiHandler,
|
||||
/// Public URL prefix when a Vhost location rewrites a mount path.
|
||||
/// SCRIPT_FILENAME stays confined to document_root; SCRIPT_NAME gains this prefix.
|
||||
pub script_name_prefix: String,
|
||||
#[serde(default = "default_php_connect_timeout_ms")]
|
||||
pub connect_timeout_ms: u64,
|
||||
|
||||
@@ -73,8 +73,6 @@ pub struct CompiledService {
|
||||
}
|
||||
|
||||
impl CompiledService {
|
||||
// Read-only diagnostics for the authenticated administration UI. Warnings
|
||||
// come from the active compiled snapshot, not from another filesystem scan.
|
||||
pub fn htaccess_diagnostics(&self) -> Option<(usize, &[String])> {
|
||||
self.htaccess.as_ref().map(|compiled| (compiled.files_loaded, compiled.warnings.as_slice()))
|
||||
}
|
||||
|
||||
@@ -32,11 +32,8 @@ const FCGI_STDERR: u8 = 7;
|
||||
const FCGI_RESPONDER: u16 = 1;
|
||||
const FCGI_REQUEST_ID: u16 = 1;
|
||||
const FCGI_HEADER_LEN: usize = 8;
|
||||
/// Request records (BEGIN, PARAMS, STDIN) are coalesced into a few socket writes.
|
||||
const FASTCGI_WRITE_BUFFER_BYTES: usize = 16 * 1024;
|
||||
/// Response records are read through one buffer instead of 2-3 reads per record.
|
||||
const FASTCGI_READ_BUFFER_BYTES: usize = 32 * 1024;
|
||||
/// Already-received STDOUT records are merged into one body chunk up to this size.
|
||||
const FASTCGI_BODY_CHUNK_BYTES: usize = 64 * 1024;
|
||||
|
||||
pub(super) trait FastCgiIo: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
@@ -48,16 +45,12 @@ async fn connect_fastcgi(endpoint: &FastCgiEndpoint) -> io::Result<Box<dyn FastC
|
||||
FastCgiEndpoint::Unix(path) => Ok(Box::new(tokio::net::UnixStream::connect(path).await?)),
|
||||
FastCgiEndpoint::Tcp(address) => {
|
||||
let stream = tokio::net::TcpStream::connect(address).await?;
|
||||
// FastCGI is a request/response exchange of small records; Nagle's
|
||||
// algorithm would only delay the final record of a request.
|
||||
stream.set_nodelay(true)?;
|
||||
Ok(Box::new(stream))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Type of the next FastCGI record when it is already complete in the read
|
||||
/// buffer, so it can be consumed without waiting for the socket.
|
||||
fn buffered_fcgi_record(io: &BufReader<Box<dyn FastCgiIo>>) -> Option<u8> {
|
||||
let buffer = io.buffer();
|
||||
if buffer.len() < FCGI_HEADER_LEN {
|
||||
@@ -370,9 +363,6 @@ async fn drain_fastcgi_body(
|
||||
metrics: std::sync::Arc<crate::web_server::metrics::PhpMetrics>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
) {
|
||||
// Body bytes waiting to be sent. Records that have already arrived are
|
||||
// merged into one chunk; nothing is held back while waiting for the socket,
|
||||
// so flush() from the application still reaches the client immediately.
|
||||
let mut pending = if send_body { initial } else { Vec::new() };
|
||||
let mut stderr = Vec::new();
|
||||
loop {
|
||||
|
||||
@@ -111,8 +111,6 @@ async fn php_response_inner(
|
||||
write_fcgi_record(&mut writer, FCGI_PARAMS, &[]).await?;
|
||||
|
||||
let mut body = body;
|
||||
// Requests without a body go out in one write. With a body, deliver the
|
||||
// parameters first so the responder can start while the client uploads.
|
||||
if !http_body::Body::is_end_stream(&body) {
|
||||
writer.flush().await?;
|
||||
}
|
||||
@@ -151,7 +149,6 @@ async fn php_response_inner(
|
||||
}
|
||||
}
|
||||
|
||||
// The request is fully flushed; from here on the connection is only read.
|
||||
let mut io = BufReader::with_capacity(FASTCGI_READ_BUFFER_BYTES, writer.into_inner());
|
||||
let mut stdout = Vec::new();
|
||||
let mut stderr = Vec::new();
|
||||
|
||||
@@ -106,7 +106,6 @@ struct Scope {
|
||||
file_rules: Vec<FileAccessRule>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum AcceptPathInfoMode {
|
||||
On,
|
||||
@@ -114,8 +113,6 @@ enum AcceptPathInfoMode {
|
||||
Default,
|
||||
}
|
||||
|
||||
// Apache Files / FilesMatch rules apply to filenames below their directory.
|
||||
// Only bounded access-control directives are accepted inside these blocks.
|
||||
#[derive(Debug, Clone)]
|
||||
struct FileAccessRule {
|
||||
matcher: Regex,
|
||||
@@ -132,9 +129,6 @@ impl FileAccessRule {
|
||||
}
|
||||
}
|
||||
|
||||
// Apache 2.2 mod_access_compat's Order/Allow/Deny are access rules, not
|
||||
// harmless unsupported directives. Evaluate them instead of silently skipping
|
||||
// them and accidentally publishing protected files.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
enum LegacyOrder {
|
||||
#[default]
|
||||
|
||||
@@ -43,9 +43,6 @@ fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
|
||||
Ok(SimpleRedirect { matcher, replacement, status })
|
||||
}
|
||||
|
||||
// Only a safe, deterministic subset of Apache access rules is allowed in
|
||||
// <Files> and <FilesMatch>. Unknown directives inside a security scope must
|
||||
// fail closed, including when the general "ignore unsupported" option is off.
|
||||
fn file_rule_start(line: &str) -> Result<FileAccessRule> {
|
||||
let inner = line.trim().strip_prefix('<').and_then(|s| s.strip_suffix('>'))
|
||||
.context("unterminated Files or FilesMatch tag")?;
|
||||
@@ -56,7 +53,6 @@ fn file_rule_start(line: &str) -> Result<FileAccessRule> {
|
||||
ensure!(values.len() == 1, "FilesMatch needs one quoted regex");
|
||||
values[0].clone()
|
||||
} else {
|
||||
// Apache also accepts <Files ~ "regex"> as an alias of FilesMatch.
|
||||
if values.len() == 2 && values[0] == "~" {
|
||||
values[1].clone()
|
||||
} else {
|
||||
@@ -395,8 +391,6 @@ fn matching_scopes<'a>(compiled: &'a Compiled, path: &str) -> Vec<&'a Scope> {
|
||||
pub fn denied(compiled: Option<&Compiled>, path: &str, client_ip: IpAddr) -> bool {
|
||||
let Some(compiled) = compiled else { return false; };
|
||||
let scopes = matching_scopes(compiled, path);
|
||||
// A matching <Files>/<FilesMatch> denial is additive. A narrower file
|
||||
// grant must not cancel a directory denial or another matched file rule.
|
||||
let basename = path_components(path).ok().and_then(|parts| parts.last().cloned());
|
||||
if let Some(name) = basename {
|
||||
for scope in &scopes {
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user