This commit is contained in:
Mateusz Gruszczyński committed 2026-11-14 21:52:48 +01:00
1 parent f48843e934
commit e2c8099d9c
64 files changed
+5354 -673

No files matched your search

+223
View File
@@ -0,0 +1,223 @@
const GENERAL_ALERTS_TTL: Duration = Duration::from_secs(30);
type GeneralAlertsCache = std::sync::Mutex<Option<(std::time::Instant, u64, Vec<Value>)>>;
fn general_alert(
kind: &'static str,
severity: &'static str,
subject: impl Into<String>,
value: Option<String>,
threshold: Option<String>,
message: Option<String>,
) -> Value {
let subject = subject.into();
json!({
"key": format!("{kind}|{subject}"),
"kind": kind,
"severity": severity,
"subject": subject,
"value": value,
"threshold": threshold,
"message": message,
})
}
fn certificate_alerts(state: &App, config: &crate::config::Config, out: &mut Vec<Value>) {
let settings = &config.alerts;
let warning_days = i64::from(settings.certificate_warning_days);
let error_days = i64::from(settings.certificate_error_days);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|value| value.as_secs() as i64)
.unwrap_or_default();
let renewals = state.acme.renewal_view();
for certificate in &config.tls.certificates {
let not_after = state
.policy
.cert_dir
.as_deref()
.and_then(|directory| {
crate::tls::certificate_metadata(directory, &certificate.cert_file).ok()
})
.and_then(|metadata| metadata.not_after_unix)
.or_else(|| {
renewals
.get(&certificate.id)
.and_then(|item| item.not_after)
});
if let Some(not_after) = not_after.filter(|_| settings.certificate_expiry) {
let days = (not_after - now).div_euclid(86_400);
if not_after <= now {
out.push(general_alert(
"certificate_expired",
"error",
&certificate.id,
None,
None,
None,
));
} else if days < warning_days {
out.push(general_alert(
"certificate_expiring",
if days < error_days {
"error"
} else {
"warning"
},
&certificate.id,
Some(days.to_string()),
Some(warning_days.to_string()),
None,
));
}
}
if let Some(renewal) = renewals
.get(&certificate.id)
.filter(|_| settings.certificate_renewal)
{
if renewal.failures > 0 {
out.push(general_alert(
"certificate_renewal_failed",
"error",
&certificate.id,
Some(renewal.failures.to_string()),
None,
(!renewal.message.is_empty()).then(|| renewal.message.clone()),
));
}
}
}
if settings.acme_runtime
&& config
.tls
.certificates
.iter()
.any(|item| item.issuer.is_some())
{
let runtime = state.acme.runtime_view();
if runtime.status != "ready" {
out.push(general_alert(
"acme_runtime",
"warning",
"acme",
Some(runtime.status.to_owned()),
None,
Some(runtime.message.to_owned()),
));
}
}
}
fn resource_alerts(state: &App, settings: &crate::alerts::Settings, out: &mut Vec<Value>) {
if !settings.file_descriptors {
return;
}
let system = state.diagnostics.view();
if let (Some(open), Some(max)) = (system.open_fds, system.max_fds) {
if max > 0 {
let percent = (open as f64 / max as f64 * 100.0).round() as u64;
if percent >= u64::from(settings.file_descriptors_warning_percent) {
out.push(general_alert(
"file_descriptors_high",
if percent >= u64::from(settings.file_descriptors_error_percent) {
"error"
} else {
"warning"
},
"process",
Some(format!("{open}/{max}")),
Some(format!("{}%", settings.file_descriptors_warning_percent)),
None,
));
}
}
}
}
fn policy_alerts(state: &App, config: &crate::config::Config, out: &mut Vec<Value>) {
let settings = &config.alerts;
let country_rules = config.global_security.country_access.mode
!= crate::rate_limit::CountryMode::Off
|| config.vhosts.iter().any(|vhost| {
vhost.rate_limit.country_access.mode != crate::rate_limit::CountryMode::Off
});
if settings.geoip && country_rules && !state.geoip.load().view().loaded {
out.push(general_alert(
"geoip_missing",
"warning",
"geoip",
None,
None,
None,
));
}
let prometheus = &state.active_prometheus;
if settings.prometheus
&& prometheus.enabled
&& !prometheus.listen.ip().is_loopback()
&& state.prometheus_token_hash.load().is_none()
&& prometheus.allowed_cidrs.is_empty()
{
out.push(general_alert(
"prometheus_exposed",
"warning",
prometheus.listen.to_string(),
None,
None,
None,
));
}
let update = state.software_update.snapshot();
if settings.update && update.update_available {
out.push(general_alert(
"update_available",
"info",
"rustproxy",
update.latest_version.clone(),
Some(update.current_version.clone()),
None,
));
}
}
fn compute_general_alerts(state: &App) -> Vec<Value> {
let snapshot = state.config.load_full();
let config = &snapshot.envelope.config;
let mut out = Vec::new();
if !config.alerts.enabled {
return out;
}
certificate_alerts(state, config, &mut out);
resource_alerts(state, &config.alerts, &mut out);
policy_alerts(state, config, &mut out);
out.truncate(64);
out
}
fn general_alerts(state: &App) -> Vec<Value> {
static CACHE: std::sync::OnceLock<GeneralAlertsCache> = std::sync::OnceLock::new();
let cache = CACHE.get_or_init(|| std::sync::Mutex::new(None));
let mut guard = cache.lock().unwrap_or_else(|error| error.into_inner());
let revision = state.config.load().envelope.revision;
if let Some((at, cached_revision, alerts)) = guard.as_ref() {
if at.elapsed() < GENERAL_ALERTS_TTL && *cached_revision == revision {
return alerts.clone();
}
}
let alerts = compute_general_alerts(state);
*guard = Some((std::time::Instant::now(), revision, alerts.clone()));
alerts
}
async fn alerts_status(State(state): State<Arc<App>>) -> Json<Value> {
let alerts = tokio::task::spawn_blocking({
let state = state.clone();
move || general_alerts(&state)
})
.await
.unwrap_or_default();
let docker = {
let snapshot = state.config.load_full();
crate::docker::alerts(&snapshot.envelope.config, &state.docker.latest())
};
Json(json!({ "alerts": alerts, "docker": docker }))
}
+1
View File
@@ -4,6 +4,7 @@ fn general_api_token_allowed(method: &Method, path: &str, permission: &str) -> b
path,
"/api/status"
| "/api/system-info"
| "/api/alerts"
| "/api/backends"
| "/api/docker"
| "/api/certificates"
+28 -4
View File
@@ -72,10 +72,10 @@ async fn cache_rules_test(
|error: anyhow::Error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
let snapshot = state.config.load_full();
let config = &snapshot.envelope.config;
let vhosts = cache_rule_vhosts(&state);
let vhost = match input.vhost_id.as_deref().filter(|id| !id.is_empty()) {
Some(id) => Some(
config
.vhosts
vhosts
.iter()
.find(|vhost| vhost.id == id)
.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown vhost".into()))?,
@@ -212,8 +212,7 @@ async fn cache_rules_test(
"reason": store_reason,
});
let deliver = rules.evaluate_deliver(&request, status, &response_headers, false);
deliver_value =
json!({"matched": deliver.matched, "set": deliver.set, "remove": deliver.remove});
deliver_value = json!({"matched": deliver.matched, "set": deliver.set, "remove": deliver.remove, "defaults": deliver.defaults});
}
Ok(Json(json!({
"host": host,
@@ -246,6 +245,31 @@ async fn cache_rules_import_vcl(
Ok(Json(json!(result)))
}
fn cache_rule_vhosts(state: &Arc<App>) -> Vec<crate::vhost::Vhost> {
let snapshot = state.config.load_full();
let config = &snapshot.envelope.config;
if config.docker_agents.agents.is_empty() {
return config.vhosts.clone();
}
crate::docker::effective_config(config.clone(), &state.docker.latest())
.map(|effective| effective.vhosts)
.unwrap_or_else(|_| config.vhosts.clone())
}
async fn cache_rules_targets(State(state): State<Arc<App>>) -> Json<Value> {
let targets: Vec<Value> = cache_rule_vhosts(&state)
.iter()
.map(|vhost| {
json!({
"id": &vhost.id,
"hosts": vhost.frontend.hosts.iter().take(4).collect::<Vec<_>>(),
"docker": vhost.id.starts_with("docker-"),
})
})
.collect();
Json(json!({ "targets": targets }))
}
async fn cache_rules_stats() -> Json<Value> {
Json(json!({"hits": crate::cache::rule_hit_counts()}))
}
+7
View File
@@ -23,6 +23,7 @@ enum ConfigSection {
Response,
Logging,
GlobalSecurity,
Alerts,
}
impl ConfigSection {
@@ -51,6 +52,7 @@ impl ConfigSection {
"response" => Some(Self::Response),
"logging" => Some(Self::Logging),
"global-security" => Some(Self::GlobalSecurity),
"alerts" => Some(Self::Alerts),
_ => None,
}
}
@@ -87,6 +89,7 @@ impl ConfigSection {
"error_log": &config.error_log,
}),
Self::GlobalSecurity => json!(&config.global_security),
Self::Alerts => json!(&config.alerts),
}
}
@@ -201,6 +204,10 @@ impl ConfigSection {
}
config.global_security = part;
}
Self::Alerts => {
config.alerts =
serde_json::from_value(value).map_err(|error| invalid_section(name, error))?
}
}
Ok(())
}
+1
View File
@@ -13,6 +13,7 @@ include!("file_logs.rs");
include!("file_log_search.rs");
include!("operations.rs");
include!("cache_rules.rs");
include!("alerts.rs");
include!("certificate_api.rs");
include!("certificates.rs");
include!("tail.rs");
+341 -4
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.37.1",
"version": "0.37.2",
"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": [
@@ -1244,6 +1244,63 @@
"$ref": "#/components/schemas/UserAgentBlocking"
}
]
},
"alerts": {
"type": "object",
"description": "Since 0.37.2. General alert settings (Settings → Alerts): enabled, notifications, certificate_expiry, certificate_warning_days (1..90, default 14), certificate_error_days (below warning, default 3), certificate_renewal, acme_runtime, file_descriptors, file_descriptors_warning_percent (default 80), file_descriptors_error_percent (default 95), geoip, prometheus, update. Omitted when all values are defaults.",
"additionalProperties": false,
"properties": {
"enabled": {
"type": "boolean"
},
"notifications": {
"type": "boolean"
},
"certificate_expiry": {
"type": "boolean"
},
"certificate_renewal": {
"type": "boolean"
},
"acme_runtime": {
"type": "boolean"
},
"file_descriptors": {
"type": "boolean"
},
"geoip": {
"type": "boolean"
},
"prometheus": {
"type": "boolean"
},
"update": {
"type": "boolean"
},
"certificate_warning_days": {
"type": "integer",
"minimum": 1,
"maximum": 90,
"default": 14
},
"certificate_error_days": {
"type": "integer",
"minimum": 0,
"default": 3
},
"file_descriptors_warning_percent": {
"type": "integer",
"minimum": 50,
"maximum": 99,
"default": 80
},
"file_descriptors_error_percent": {
"type": "integer",
"minimum": 50,
"maximum": 100,
"default": 95
}
}
}
},
"additionalProperties": false,
@@ -3281,6 +3338,25 @@
"default": false,
"description": "Enable the normal RustProxy cache policy for this generated Docker vhost."
},
"cache_default_ttl_seconds": {
"type": "integer",
"minimum": 0,
"nullable": true,
"description": "Since 0.37.2. Default cache TTL for this Docker vhost; null uses the global cache default."
},
"cache_rules": {
"type": "array",
"maxItems": 128,
"items": {
"$ref": "#/components/schemas/CacheRule"
},
"description": "Since 0.37.2. Cache rules for this Docker vhost (same format as vhost cache.rules); they run before global rules."
},
"cache_ignore_global_rules": {
"type": "boolean",
"default": false,
"description": "Since 0.37.2. Do not apply global cache rules to this Docker vhost."
},
"health_check": {
"$ref": "#/components/schemas/DockerHealthCheck"
},
@@ -3352,6 +3428,11 @@
},
"description": "Up to 8 additional reusable ACL profiles. Explicit IP denies and country blocks beat all allows; otherwise explicit allows combine as OR; unmatched defaults require unanimous allow. Legacy acl_profile_id is still honored. Inline and global policies remain cumulative."
},
"inherit_acl_profiles": {
"type": "boolean",
"default": true,
"description": "Since 0.37.2. When no ACL profiles are selected for the service, the agent default ACL profiles apply. false publishes the service without the agent default profiles (public Docker vhost); inline and global policies still apply."
},
"allow_certificate_mismatch": {
"type": "boolean",
"default": false,
@@ -4345,6 +4426,36 @@
},
"description": "Optional per-card heights in Overview row units (1-32; a compact stat card spans 2 rows). Cards without an entry size to their content; a height smaller than the content needs is raised automatically. Keys must be registered Overview widget IDs."
},
"dashboard_widget_positions": {
"type": "object",
"nullable": true,
"description": "Since 0.37.2. Fixed Overview card positions saved with *Arrange manually*: grid column count and, per card ID, [column, row] (0-based; rows in Overview row units). Applied only when Fit to screen is off and the grid has the same column count; omitted for the flowing layout.",
"additionalProperties": false,
"properties": {
"columns": {
"type": "integer",
"minimum": 1,
"maximum": 24
},
"items": {
"type": "object",
"additionalProperties": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "integer",
"minimum": 0,
"maximum": 2048
}
}
}
},
"required": [
"columns",
"items"
]
},
"dashboard_auto_fit": {
"type": "boolean",
"default": true,
@@ -8663,7 +8774,7 @@
"maxItems": 16,
"items": {
"type": "object",
"description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, remove_header{name} (deliver).",
"description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, default_header{name,value} (only when the response lacks the header, since 0.37.2), remove_header{name} (deliver; deliver rules apply to every response of the vhost, also when caching is off).",
"additionalProperties": true
}
},
@@ -11834,7 +11945,8 @@
"host-policies",
"global-security",
"web-services",
"php-fpm-profiles"
"php-fpm-profiles",
"alerts"
]
},
"description": "Configuration section to replace."
@@ -11951,6 +12063,9 @@
],
"global-security": [
"global_security"
],
"alerts": [
"alerts"
]
}
},
@@ -11991,7 +12106,8 @@
"host-policies",
"global-security",
"web-services",
"php-fpm-profiles"
"php-fpm-profiles",
"alerts"
]
},
"description": "Exactly one supported configuration section."
@@ -12119,10 +12235,139 @@
],
"global-security": [
"global_security"
],
"alerts": [
"alerts"
]
}
}
},
"/api/alerts": {
"get": {
"summary": "Active general and Docker alerts",
"tags": [
"Cache"
],
"operationId": "get_api_alerts",
"responses": {
"200": {
"description": "Active alerts",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"alerts": {
"type": "array",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"kind": {
"type": "string",
"enum": [
"certificate_expired",
"certificate_expiring",
"certificate_renewal_failed",
"acme_runtime",
"file_descriptors_high",
"geoip_missing",
"prometheus_exposed",
"update_available"
]
},
"severity": {
"type": "string",
"enum": [
"error",
"warning",
"info"
]
},
"subject": {
"type": "string"
},
"value": {
"type": "string",
"nullable": true
},
"threshold": {
"type": "string",
"nullable": true
},
"message": {
"type": "string",
"nullable": true
}
}
}
},
"docker": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
},
"401": {
"description": "Authentication required or revoked",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Host, origin or CSRF validation failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"429": {
"description": "Bounded worker/session/rate limit",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"503": {
"description": "Control-plane storage/worker unavailable",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
},
"security": [
{
"AdminSession": []
},
{
"GeneralApiBearer": []
}
],
"description": "Since 0.37.2. Alerts computed from the current state only (no history): certificate expired/expiring within 14 days/renewal failed, ACME environment not ready while ACME certificates exist, file descriptors at 80% of the limit or more, country rules without a GeoIP database, Prometheus exporter reachable without token or address restriction, and an available update (severity info). General alerts are recomputed at most every 30 seconds and are also included as `alerts` in /api/status. `docker` repeats the Docker agent alerts."
}
},
"/api/docker": {
"get": {
"summary": "Read cached Docker agent observations",
@@ -15652,6 +15897,98 @@
]
}
},
"/api/cache/rules/targets": {
"get": {
"summary": "Vhosts that cache rules can target",
"tags": [
"Cache"
],
"operationId": "get_api_cache_rules_targets",
"responses": {
"200": {
"description": "Rule targets",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"targets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"hosts": {
"type": "array",
"items": {
"type": "string"
}
},
"docker": {
"type": "boolean"
}
}
}
}
}
}
}
}
},
"401": {
"description": "Authentication required or revoked",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Host, origin or CSRF validation failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"429": {
"description": "Bounded worker/session/rate limit",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"503": {
"description": "Control-plane storage/worker unavailable",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
},
"security": [
{
"AdminSession": []
},
{
"GeneralApiBearer": []
}
],
"description": "Since 0.37.2. Lists configured vhosts and the Docker vhosts generated from agent assignments and container labels (id, up to four hosts, docker flag), for the global rule vhost picker and the rule tester."
}
},
"/api/cache/rules/test": {
"post": {
"summary": "Simulate cache rules for a request",
+37
View File
@@ -46,6 +46,11 @@ fn reconcile_dashboard_widgets(prefs: &mut AdminPreferences) {
.any(|widget| widget.id == *id && valid_dashboard_span(&widget.display_type, *span))
});
}
if let Some(positions) = prefs.dashboard_widget_positions.as_mut() {
positions
.items
.retain(|id, _| DASHBOARD_WIDGETS.iter().any(|widget| widget.id == *id));
}
if let Some(heights) = prefs.dashboard_widget_heights.as_mut() {
heights.retain(|id, rows| {
valid_dashboard_rows(*rows) && DASHBOARD_WIDGETS.iter().any(|widget| widget.id == *id)
@@ -61,6 +66,25 @@ fn reconcile_dashboard_widgets(prefs: &mut AdminPreferences) {
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct DashboardWidgetPositions {
columns: u8,
items: std::collections::BTreeMap<String, [u16; 2]>,
}
impl DashboardWidgetPositions {
fn valid(&self) -> bool {
(1..=24).contains(&self.columns)
&& self.items.len() <= DASHBOARD_WIDGETS.len()
&& self.items.iter().all(|(id, [column, row])| {
*column < u16::from(self.columns)
&& *row <= 2048
&& DASHBOARD_WIDGETS.iter().any(|widget| widget.id == *id)
})
}
}
fn default_admin_dashboard_auto_fit() -> bool {
true
}
@@ -156,6 +180,8 @@ struct AdminPreferences {
sidebar_collapsed: bool,
#[serde(default)]
dashboard_widget_heights: Option<std::collections::BTreeMap<String, u8>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
dashboard_widget_positions: Option<DashboardWidgetPositions>,
#[serde(default = "default_file_log_columns")]
file_log_columns: Vec<String>,
#[serde(default = "default_file_log_sort")]
@@ -217,6 +243,7 @@ impl Default for AdminPreferences {
dashboard_hidden_widgets: default_hidden_dashboard_widgets(),
dashboard_widget_sizes: None,
dashboard_widget_heights: None,
dashboard_widget_positions: None,
dashboard_auto_fit: true,
sidebar_collapsed: false,
file_log_columns: default_file_log_columns(),
@@ -434,6 +461,16 @@ fn validate_admin_preferences(preferences: &AdminPreferences) -> Result<(), ApiE
"invalid Docker dashboard card agent preference".into(),
));
}
if preferences
.dashboard_widget_positions
.as_ref()
.is_some_and(|positions| !positions.valid())
{
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
"invalid dashboard card position preference".into(),
));
}
if !valid_dashboard_heights(&preferences.dashboard_widget_heights) {
return Err(ApiError(
StatusCode::UNPROCESSABLE_ENTITY,
+4
View File
@@ -74,6 +74,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/app/dashboard-inline-layout.js"),
include_str!("web/app/stream-dashboard.js"),
include_str!("web/app/docker-dashboard.js"),
include_str!("web/app/alerts.js"),
include_str!("web/app/backend-dashboard.js"),
include_str!("web/app/overview-extra-metrics.js"),
include_str!("web/app/overview-wide-metrics.js"),
@@ -102,6 +103,7 @@ fn admin_app_javascript() -> &'static str {
include_str!("web/acme.js"),
include_str!("web/settings.js"),
include_str!("web/system-info.js"),
include_str!("web/tls-configurator.js"),
include_str!("web/certificate-api.js"),
include_str!("web/api-tokens.js"),
include_str!("web/prometheus-token.js"),
@@ -175,6 +177,7 @@ pub fn router(state: Arc<App>) -> Router {
.route("/api/status", get(status))
.route("/api/system-info", get(system_info))
.route("/api/backends", get(backend_status))
.route("/api/alerts", get(alerts_status))
.route("/api/docker", get(docker_status))
.route("/api/docker/refresh", post(docker_refresh))
.route("/api/docker/test", post(docker_test))
@@ -252,6 +255,7 @@ pub fn router(state: Arc<App>) -> Router {
)
.route("/api/cache/bans", get(cache_bans))
.route("/api/cache/rules/stats", get(cache_rules_stats))
.route("/api/cache/rules/targets", get(cache_rules_targets))
.route(
"/api/cache/rules/test",
post(cache_rules_test).layer(DefaultBodyLimit::max(256 * 1024)),
+1
View File
@@ -197,6 +197,7 @@ fn status_payload(state: &App) -> Value {
&snapshot.envelope.config,
&state.docker.latest()
));
payload["alerts"] = json!(general_alerts(state));
payload["backends"] = json!(snapshot
.envelope
.config
+1
View File
@@ -64,6 +64,7 @@ fn live_status_payload(state: &App) -> Value {
"vhost_cache_totals": state.cache.scope_totals(),
"streams": {"metrics": stream_metrics},
"docker": crate::docker::dashboard_summary(&snapshot.envelope.config, &state.docker.latest()),
"alerts": general_alerts(state),
"logging": {"sinks": state.logs.stats(), "error_file": crate::logging::error_log_stats()}
})
}
+2
View File
@@ -705,6 +705,7 @@ mod tests {
"response",
"logging",
"global-security",
"alerts",
];
let mut original = Config::default();
original.global_security.compile().unwrap();
@@ -757,6 +758,7 @@ mod tests {
"response",
"logging",
"global-security",
"alerts",
] {
let response = router
.clone()
+42 -1
View File
@@ -78,6 +78,8 @@ window.rustProxyAclPicker = (() => {
options.addEventListener("change", event => { if (event.target.matches('input[type="checkbox"]')) sync(); });
search.addEventListener("input", syncSearch);
search.addEventListener("keydown", event => { if (event.key === "Escape") { search.value = ""; syncSearch(); details.open = false; summary.focus(); } });
root.select = ids => { for (const [id, box] of checks) box.checked = ids.includes(id); sync(); };
root.setDisabled = disabled => { root.classList.toggle("is-disabled", disabled); details.open = details.open && !disabled; summary.tabIndex = disabled ? -1 : 0; summary.setAttribute("aria-disabled", String(disabled)); };
syncSearch(); sync(); return root;
}
return { create, read: chosenIds, count: root => chosenIds(root).length };
@@ -103,7 +105,7 @@ window.rustProxyChoicePicker = (() => {
const row = el("label", undefined, "acl-picker-option"), check = el("input"); check.type = "checkbox"; check.value = item.id; check.checked = !!checked;
const content = el("span", undefined, "acl-picker-option-content"), headingRow = el("span", undefined, "acl-picker-option-heading");
headingRow.append(el("strong", item.title || item.id));
if (item.title && item.title !== item.id) headingRow.append(el("code", item.id, "acl-picker-id"));
if (item.title && item.title !== item.id && !item.title.startsWith(`${item.id} `)) headingRow.append(el("code", item.id, "acl-picker-id"));
if (item.badge) headingRow.append(el("span", item.badge, `acl-picker-policy ${item.badgeClass || "is-none"}`));
content.append(headingRow); if (item.detail) content.append(el("small", item.detail, "acl-picker-rule-preview"));
row.append(check, content); row.dataset.search = `${item.id} ${item.title || ""} ${item.search || ""} ${item.detail || ""}`.toLocaleLowerCase();
@@ -240,3 +242,42 @@ window.rustProxyCountryPicker = (() => {
}
return { attach, codes: CODES, nameOf };
})();
window.rustProxyMethodPicker = (() => {
const METHODS = [
["GET", "methodGet"], ["HEAD", "methodHead"], ["POST", "methodPost"], ["PUT", "methodPut"], ["PATCH", "methodPatch"], ["DELETE", "methodDelete"],
["OPTIONS", "methodOptions"], ["CONNECT", "methodConnect"], ["TRACE", "methodTrace"], ["TRACK", "methodTrack"], ["PURGE", "methodPurge"], ["BAN", "methodBan"],
["PROPFIND", "methodWebdav"], ["PROPPATCH", "methodWebdav"], ["MKCOL", "methodWebdav"], ["COPY", "methodWebdav"], ["MOVE", "methodWebdav"], ["LOCK", "methodWebdav"], ["UNLOCK", "methodWebdav"],
["SEARCH", "methodWebdav"], ["REPORT", "methodWebdav"], ["MKCALENDAR", "methodWebdav"],
];
const TOKEN = /^[A-Z0-9!#$%&'*+.^_`|~-]{1,32}$/;
const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
function attach(textarea) {
if (!textarea || textarea.dataset.methodPicker) return null;
textarea.dataset.methodPicker = "1"; textarea.hidden = true;
const wrapper = textarea.parentElement;
if (wrapper?.tagName === "LABEL") { const box = el("div", undefined, wrapper.className); box.append(...wrapper.childNodes); wrapper.replaceWith(box); }
const host = el("div", undefined, "method-picker-host"); textarea.after(host);
let picker = null, writing = false;
const build = () => {
picker = window.rustProxyChoicePicker.create({
className: "method-picker", selected: parse(textarea.value), limit: 64, unknownDetail: "methodCustom",
items: METHODS.map(([id, key]) => ({ id, title: id, detail: t(key) })),
labels: { choose: "methodPickerChoose", selected: "methodPickerSelected", none: "methodPickerNone", search: "methodPickerSearch", addHint: "methodPickerAddHint", empty: "methodPickerEmpty" },
custom: raw => {
const id = String(raw || "").trim().toUpperCase(); if (!id) return null;
if (!TOKEN.test(id)) throw new Error(t("methodPickerInvalid").replace("{value}", raw));
return { id, title: id, detail: t("methodCustom") };
},
});
picker.addEventListener("choicechange", event => { if (writing) return; const value = (event.detail || []).join("\n"); if (value === textarea.value) return; textarea.value = value; textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.dispatchEvent(new Event("change", { bubbles: true })); });
host.replaceChildren(picker);
picker.setDisabled(textarea.disabled);
};
const refresh = () => { writing = true; try { build(); } finally { writing = false; } };
refresh();
new MutationObserver(() => picker?.setDisabled(textarea.disabled)).observe(textarea, { attributes: true, attributeFilter: ["disabled"] });
return { refresh, host };
}
return { attach, methods: METHODS.map(([id]) => id) };
})();
+60
View File
@@ -0,0 +1,60 @@
window.rustProxyAlerts = (() => {
const KEYS = {
certificate_expired: "alertCertificateExpired",
certificate_expiring: "alertCertificateExpiring",
certificate_renewal_failed: "alertCertificateRenewalFailed",
acme_runtime: "alertAcmeRuntime",
file_descriptors_high: "alertFileDescriptorsHigh",
geoip_missing: "alertGeoipMissing",
prometheus_exposed: "alertPrometheusExposed",
update_available: "alertUpdateAvailable",
};
const LINKS = {
certificate_expired: "/tls", certificate_expiring: "/tls", certificate_renewal_failed: "/tls",
acme_runtime: "/settings?tab=system-info", file_descriptors_high: "/settings?tab=system-info", geoip_missing: "/settings?tab=geoip",
prometheus_exposed: "/settings?tab=prometheus", update_available: "/settings?tab=alerts",
};
function text(alert) {
const key = KEYS[alert.kind];
if (!key) return `${alert.kind}: ${alert.subject || ""}`;
return t(key).replace("{subject}", alert.subject || "-").replace("{value}", alert.value ?? "-").replace("{threshold}", alert.threshold ?? "-").replace("{message}", alert.message || "-");
}
const list = status => Array.isArray(status?.alerts) ? status.alerts : null;
function check(status) {
const alerts = list(status);
if (!alerts) return null;
const important = alerts.filter(alert => alert.severity !== "info");
const extra = details(status);
if (!important.length) return { level: "ok", label: t("appHealthAlerts"), detail: t("appHealthAlertsNone"), extra };
return { level: important.some(alert => alert.severity === "error") ? "error" : "warning", label: t("appHealthAlerts"), detail: t("alertsTitle").replace("{count}", important.length), extra };
}
let seen = null;
function notify(status) {
const alerts = list(status);
if (!alerts) return;
if (envelope?.config?.alerts?.notifications === false) { seen = new Set(alerts.map(alert => alert.key)); return; }
const keys = new Set(alerts.map(alert => alert.key));
if (seen === null) {
seen = keys;
const important = alerts.filter(alert => alert.severity !== "info");
if (important.length) toast(t("alertsTitle").replace("{count}", important.length), important.some(alert => alert.severity === "error"));
return;
}
for (const alert of alerts) if (!seen.has(alert.key) && alert.severity !== "info") toast(text(alert), alert.severity === "error");
seen = keys;
}
function details(status) {
const alerts = list(status) || [];
if (!alerts.length) return null;
const box = el("ul", undefined, "app-alert-list");
for (const alert of alerts) {
const item = el("li", undefined, `is-${alert.severity}`);
item.append(el("span", alert.severity === "error" ? "●" : alert.severity === "info" ? "i" : "▲", "app-alert-icon"), el("span", text(alert)));
const link = LINKS[alert.kind];
if (link) { const anchor = el("a", t("alertOpen")); anchor.href = link; item.append(anchor); }
box.append(item);
}
return box;
}
return { text, check, notify, details, reset() { seen = null; } };
})();
+12 -3
View File
@@ -216,6 +216,7 @@ function appHealthChecks(status) {
}
const dockerCheck = window.rustProxyDockerDashboard?.healthCheck?.(status); if (dockerCheck) checks.push(dockerCheck);
const alertsCheck = window.rustProxyAlerts?.check?.(status); if (alertsCheck) checks.push(alertsCheck);
const sink = status.logging?.sinks || {}, errorFile = status.logging?.error_file || {};
const loggingDropped = (Number(sink.queue_dropped) || 0) + (Number(errorFile.queue_dropped) || 0);
const loggingErrors = (Number(sink.errors) || 0) + (Number(errorFile.errors) || 0);
@@ -250,7 +251,7 @@ function renderAppHealth(status = latestStatus) {
const list = $("app-health-checks");
if (list) list.replaceChildren(...checks.map(check => {
const row = el("div", undefined, `app-health-check is-${check.level}`), dot = el("i"), copy = el("div");
dot.setAttribute("aria-hidden", "true"); copy.append(el("strong", check.label), el("p", check.detail, "fine")); row.append(dot, copy); return row;
dot.setAttribute("aria-hidden", "true"); copy.append(el("strong", check.label), el("p", check.detail, "fine")); if (check.extra) copy.append(check.extra); row.append(dot, copy); return row;
}));
}
function enhanceEnabledControl(input, hintKey = "entityEnableHint") {
@@ -313,7 +314,15 @@ window.rustProxyOverviewSamples.onChange(() => {
const nativeScrollAnchoring = typeof CSS !== "undefined" && CSS.supports?.("overflow-anchor", "auto");
function preserveScrollAnchor(render) {
if (nativeScrollAnchoring || window.scrollY <= 0) return render();
if (window.scrollY <= 0) return render();
if (nativeScrollAnchoring) {
const scroller = document.scrollingElement || document.documentElement, before = window.scrollY, height = scroller.scrollHeight;
scroller.style.minHeight = `${height}px`;
let result;
try { result = render(); } finally { requestAnimationFrame(() => { scroller.style.minHeight = ""; }); }
if (window.scrollY < before - 1 && scroller.scrollHeight - window.innerHeight >= before - 1) window.scrollTo(window.scrollX, before);
return result;
}
const probe = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2);
const anchor = probe?.closest?.("article, tr, .mini-live-chart, .network-interface-row") || probe;
const before = anchor?.isConnected ? anchor.getBoundingClientRect().top : null;
@@ -371,7 +380,7 @@ function renderStatusNow(s, systemSample = false) {
$("metric-ws-proto-h1").textContent = (Number(m.websocket_h1_active) || 0).toLocaleString(locale());
$("metric-ws-proto-h2").textContent = (Number(m.websocket_h2_active) || 0).toLocaleString(locale());
$("metric-ws-proto-h3").textContent = (Number(m.websocket_h3_active) || 0).toLocaleString(locale());
renderFooter(s); renderDiagnostics(s, true, systemSample); window.rustProxyVhosts?.renderStatus(s); window.rustProxyDocker?.renderStatus(s); window.rustProxyStreams?.renderStatus(s); window.rustProxyStreamDashboard?.render(s); window.rustProxyDockerDashboard?.render(s); window.rustProxyDockerDashboard?.notify?.(s); window.rustProxyBackendDashboard?.render(s); window.rustProxyExtraOverview?.render(s); window.rustProxyWideOverview?.render(s); window.rustProxyWebOverview?.render(s); window.rustProxyWebServer?.renderLive?.(s);
renderFooter(s); renderDiagnostics(s, true, systemSample); window.rustProxyVhosts?.renderStatus(s); window.rustProxyDocker?.renderStatus(s); window.rustProxyStreams?.renderStatus(s); window.rustProxyStreamDashboard?.render(s); window.rustProxyDockerDashboard?.render(s); window.rustProxyDockerDashboard?.notify?.(s); window.rustProxyAlerts?.notify?.(s); window.rustProxyBackendDashboard?.render(s); window.rustProxyExtraOverview?.render(s); window.rustProxyWideOverview?.render(s); window.rustProxyWebOverview?.render(s); window.rustProxyWebServer?.renderLive?.(s);
}
function renderFooter(s) {
const apiLatency = lastApiLatencyMs == null ? "API -" : `API ${lastApiLatencyMs.toFixed(lastApiLatencyMs < 10 ? 1 : 0)} ms`;
+95 -11
View File
@@ -11,6 +11,8 @@ window.rustProxyInlineLayout = (() => {
const modalButton = $("overview-layout-open");
const compactButton = $("overview-inline-compact");
const autoFitToggle = $("overview-inline-autofit");
const manualToggle = $("overview-inline-manual");
let manual = false;
let draft = null;
let original = null;
let opening = false;
@@ -31,7 +33,16 @@ window.rustProxyInlineLayout = (() => {
|| [...draft.hidden].some(id => !original.hidden.has(id)) || [...original.hidden].some(id => !draft.hidden.has(id))
|| JSON.stringify(draft.sizes) !== JSON.stringify(original.sizes)
|| JSON.stringify(normalizeDashboardWidgetHeights(draft.heights)) !== JSON.stringify(normalizeDashboardWidgetHeights(original.heights))
|| draft.autoFit !== original.autoFit);
|| draft.autoFit !== original.autoFit
|| JSON.stringify(cleanPositions(draft.positions)) !== JSON.stringify(cleanPositions(original.positions)));
const rows = () => window.rustProxyOverviewRows;
function cleanPositions(value) { return value ? normalizeDashboardWidgetPositions({ columns: value.columns, items: value.items }) : null; }
function capturePositions() {
if (!draft || !manual) return;
const captured = rows()?.currentPositions?.();
if (captured) { draft.positions = { columns: captured.columns, items: captured.items }; rows()?.setPositions?.(draft.positions); }
}
function settlePositions() { requestAnimationFrame(() => requestAnimationFrame(() => { rows()?.flush?.(); capturePositions(); })); }
function renderHidden() {
if (!hiddenList || !draft) return;
@@ -58,7 +69,9 @@ window.rustProxyInlineLayout = (() => {
function hide(id) {
if (!draft || !visibleIds().includes(id)) return;
draft.hidden.add(id);
if (draft.positions?.items) delete draft.positions.items[id];
paint();
if (manual) settlePositions();
if (hiddenShelf) { hiddenShelf.open = true; hiddenShelf.querySelector("summary")?.focus(); }
}
function paint() {
@@ -125,6 +138,7 @@ window.rustProxyInlineLayout = (() => {
if (next === dashboardDefaultWidth(id)) delete draft.sizes[id];
else draft.sizes[id] = next;
paint();
if (manual) settlePositions();
nodeFor(id)?.querySelector(delta < 0 ? ".overview-inline-narrow" : ".overview-inline-widen")?.focus();
}
function resizeHeight(id, delta) {
@@ -137,6 +151,7 @@ window.rustProxyInlineLayout = (() => {
if (next <= rows.min) delete draft.heights[id];
else draft.heights[id] = Math.min(DASHBOARD_MAX_ROWS, next);
paint();
if (manual) settlePositions();
nodeFor(id)?.querySelector(delta < 0 ? ".overview-inline-lower" : ".overview-inline-taller")?.focus();
}
function nudge(id, delta) {
@@ -195,6 +210,10 @@ window.rustProxyInlineLayout = (() => {
if (compactButton) compactButton.title = t("overviewLayoutInlineCompactHint");
const autoFitLabel = $("overview-inline-autofit-label");
if (autoFitLabel) autoFitLabel.title = t("overviewLayoutAutoFitHint");
const manualLabel = $("overview-inline-manual-label");
if (manualLabel) manualLabel.title = t("overviewLayoutManualHint");
if (manualToggle) manualToggle.checked = manual;
syncManual();
if (hiddenShelf) { hiddenShelf.hidden = false; hiddenShelf.open = false; }
if (modalButton) modalButton.disabled = true;
for (const node of nodes()) toolbar(node);
@@ -203,7 +222,7 @@ window.rustProxyInlineLayout = (() => {
function finish(preserveSaved = false) {
clearDrag();
for (const node of nodes()) node.querySelector(".overview-inline-toolbar")?.remove();
grid.classList.remove("is-unlocked");
grid.classList.remove("is-unlocked", "is-manual-layout");
unlock.setAttribute("aria-pressed", "false");
unlock.dataset.i18n = "overviewLayoutUnlock";
unlock.textContent = t("overviewLayoutUnlock");
@@ -215,6 +234,7 @@ window.rustProxyInlineLayout = (() => {
if (modalButton) modalButton.disabled = false;
if (!preserveSaved && original) {
window.rustProxyOverviewRows?.setAutoFit?.(original.autoFit);
window.rustProxyOverviewRows?.setPositions?.(original.positions);
applyDashboardLayout(original.order, [...original.hidden], original.sizes, original.heights);
}
draft = original = null;
@@ -233,7 +253,10 @@ window.rustProxyInlineLayout = (() => {
const heights = normalizeDashboardWidgetHeights(saved.dashboard_widget_heights);
const autoFit = saved.dashboard_auto_fit !== false;
original = { order: [...order], hidden: new Set(hidden), sizes: sizes === null ? null : { ...sizes }, heights: heights ? { ...heights } : null, autoFit };
draft = { order: [...order], hidden: new Set(hidden), sizes: sizes === null ? null : { ...sizes }, heights: heights ? { ...heights } : null, autoFit };
const positions = normalizeDashboardWidgetPositions(saved.dashboard_widget_positions);
original.positions = positions ? structuredClone(positions) : null;
draft = { order: [...order], hidden: new Set(hidden), sizes: sizes === null ? null : { ...sizes }, heights: heights ? { ...heights } : null, autoFit, positions: positions ? structuredClone(positions) : null };
manual = !!positions;
if (autoFitToggle) autoFitToggle.checked = autoFit;
showEditing();
} catch (error) { if (error?.status !== 401) toast(error.message, true); }
@@ -250,6 +273,7 @@ window.rustProxyInlineLayout = (() => {
dashboard_widget_sizes: draft.sizes === null ? null : { ...draft.sizes },
dashboard_widget_heights: normalizeDashboardWidgetHeights(draft.heights),
dashboard_auto_fit: draft.autoFit !== false,
dashboard_widget_positions: manual ? cleanPositions(draft.positions) : null,
});
finish(true);
toast(t("overviewLayoutEditorSaved"));
@@ -294,8 +318,25 @@ window.rustProxyInlineLayout = (() => {
if (last && y > last.getBoundingClientRect().bottom) return { node: last, after: true };
return null;
}
function clearMarker(drag) {
drag?.marker?.node.classList.remove("is-drop-before", "is-drop-after");
if (drag) drag.marker = null;
}
function updatePlaceholder(x, y) {
const drag = pointerDrag;
if (manual) {
const cell = rows()?.cellAt?.(x - drag.offsetX, y - drag.offsetY);
if (!cell) return;
const span = Math.min(cell.columns, Number(drag.node.dataset.dashboardFit || drag.node.dataset.dashboardSpan) || dashboardWidgetWidth(drag.node.dataset.dashboardWidget, draft.sizes) || 1);
const column = Math.max(0, Math.min(cell.columns - span, cell.column));
drag.cell = { column, row: cell.row };
const box = rows()?.cellBox?.(column, cell.row, span, Number(drag.node.dataset.dashboardRows) || 1);
if (!box) return;
if (!drag.ghost) { drag.ghost = el("div", undefined, "overview-drop-ghost"); document.body.append(drag.ghost); }
const zoom = drag.zoom || 1;
Object.assign(drag.ghost.style, { left: `${box.left / zoom}px`, top: `${box.top / zoom}px`, width: `${box.width / zoom}px`, height: `${Math.max(box.height, 24) / zoom}px` });
return;
}
if (performance.now() < drag.cooldownUntil) return;
const target = placeholderTarget(x, y);
if (!target) return;
@@ -322,10 +363,10 @@ window.rustProxyInlineLayout = (() => {
}
drag.frame = requestAnimationFrame(autoScroll);
}
const bodyZoom = () => parseFloat(getComputedStyle(document.body).zoom) || 1;
function liftBlock() {
const drag = pointerDrag;
enterFreeLayout();
paint();
if (!manual) { enterFreeLayout(); paint(); }
const rect = drag.node.getBoundingClientRect();
const placeholder = el("div", undefined, "overview-drop-placeholder");
placeholder.dataset.dashboardSpan = drag.node.dataset.dashboardSpan || "2";
@@ -340,20 +381,24 @@ window.rustProxyInlineLayout = (() => {
drag.height = rect.height;
drag.active = true;
drag.cooldownUntil = 0;
grid.insertBefore(placeholder, drag.node);
grid.classList.add("is-overview-sorting");
drag.startRect = { left: rect.left, top: rect.top };
if (manual) grid.classList.add("is-manual-dragging");
else { grid.insertBefore(placeholder, drag.node); grid.classList.add("is-overview-sorting"); }
drag.node.classList.add("is-overview-lifted");
drag.zoom = bodyZoom();
Object.assign(drag.node.style, {
position: "fixed", left: "0px", top: "0px", width: `${rect.width}px`, height: `${rect.height}px`,
position: "fixed", left: "0px", top: "0px", width: `${rect.width / drag.zoom}px`, height: `${rect.height / drag.zoom}px`,
zIndex: "60", pointerEvents: "none", margin: "0",
});
moveLifted();
hint.style.minHeight = `${hint.getBoundingClientRect().height / (parseFloat(getComputedStyle(document.body).zoom) || 1)}px`;
hint.textContent = t("overviewLayoutInlineDragging");
drag.frame = requestAnimationFrame(autoScroll);
}
function moveLifted() {
const drag = pointerDrag;
drag.node.style.transform = `translate(${drag.x - drag.offsetX}px, ${drag.y - drag.offsetY}px) rotate(.6deg) scale(1.015)`;
const zoom = drag.zoom || 1, x = (drag.x - drag.offsetX) / zoom, y = (drag.y - drag.offsetY) / zoom;
drag.node.style.transform = manual ? `translate(${x}px, ${y}px)` : `translate(${x}px, ${y}px) rotate(.6deg) scale(1.015)`;
}
function settle(commit) {
const drag = pointerDrag;
@@ -367,8 +412,28 @@ window.rustProxyInlineLayout = (() => {
cancelAnimationFrame(drag.frame);
for (const key of ["position", "left", "top", "width", "height", "zIndex", "pointerEvents", "margin", "transform"]) drag.node.style[key] = "";
drag.node.classList.remove("is-overview-lifted");
grid.classList.remove("is-overview-sorting");
if (commit) drag.placeholder.replaceWith(drag.node);
grid.classList.remove("is-overview-sorting", "is-manual-dragging");
requestAnimationFrame(() => { hint.style.minHeight = ""; });
clearMarker(drag); drag.ghost?.remove();
if (manual) {
if (commit && drag.cell && draft.positions) {
draft.positions = { columns: draft.positions.columns, items: { ...draft.positions.items, [drag.node.dataset.dashboardWidget]: [drag.cell.column, drag.cell.row] }, first: drag.node.dataset.dashboardWidget };
rows()?.setPositions?.(draft.positions);
settlePositions();
}
hint.textContent = t("overviewLayoutInlineHint");
paint();
drag.node.querySelector(".overview-inline-grip")?.focus({ preventScroll: true });
drag.node.animate?.([{ boxShadow: "0 0 0 3px var(--accent)" }, { boxShadow: "0 0 0 0 transparent" }], { duration: 450 });
return;
}
if (commit && manual && drag.cell && draft.positions) {
drag.placeholder.replaceWith(drag.node);
draft.positions = { columns: draft.positions.columns, items: { ...draft.positions.items, [drag.node.dataset.dashboardWidget]: [drag.cell.column, drag.cell.row] }, first: drag.node.dataset.dashboardWidget };
rows()?.setPositions?.(draft.positions);
settlePositions();
}
else if (commit) drag.placeholder.replaceWith(drag.node);
else { drag.placeholder.remove(); grid.insertBefore(drag.node, drag.origin?.parentNode === grid ? drag.origin : null); }
hint.textContent = t("overviewLayoutInlineHint");
if (commit) {
@@ -432,6 +497,24 @@ window.rustProxyInlineLayout = (() => {
});
}
compactButton?.addEventListener("click", compact);
function syncManual() {
grid?.classList.toggle("is-manual-layout", manual);
if (autoFitToggle) autoFitToggle.disabled = manual;
if (compactButton) compactButton.disabled = manual;
if (!draft) return;
if (manual) {
draft.autoFit = false; if (autoFitToggle) autoFitToggle.checked = false;
rows()?.setAutoFit?.(false);
if (!draft.positions) { enterFreeLayout(); paint(); rows()?.flush?.(); const captured = rows()?.currentPositions?.(); draft.positions = captured ? { columns: captured.columns, items: captured.items } : null; }
rows()?.setPositions?.(draft.positions);
} else {
draft.positions = null;
rows()?.setPositions?.(null);
rows()?.setAutoFit?.(draft.autoFit !== false);
}
paint();
}
manualToggle?.addEventListener("change", () => { manual = manualToggle.checked; syncManual(); });
autoFitToggle?.addEventListener("change", () => {
if (!draft) return;
draft.autoFit = autoFitToggle.checked;
@@ -448,6 +531,7 @@ window.rustProxyInlineLayout = (() => {
sizes: draft.sizes === null ? null : { ...draft.sizes },
heights: draft.heights ? { ...draft.heights } : null,
autoFit: draft.autoFit !== false,
positions: manual && draft.positions ? structuredClone(draft.positions) : null,
} : null,
cancel,
};
+1 -1
View File
@@ -79,7 +79,7 @@ const UI_PANEL_ICONS = Object.freeze({
const UI_SETTINGS_TAB_ICONS = Object.freeze({
appearance: "palette", listeners: "plug", connections: "globe", "docker-agents": "box",
policies: "shield", cache: "database", transform: "wand", forwarding: "route", pages: "file",
logging: "list", geoip: "mapPin", prometheus: "activity", administration: "users",
logging: "list", geoip: "mapPin", prometheus: "activity", alerts: "alert", administration: "users",
"system-info": "cpu", "certificate-api": "key", "tls-policy": "lock", "manual-config": "code", security: "shield",
});
const UI_VHOST_TAB_ICONS = Object.freeze({
+75 -2
View File
@@ -4,7 +4,7 @@ window.rustProxyOverviewRows = (() => {
const MIN_CARD_WIDTH = { value: 150, value_chart: 210, chart: 300, panel: 340, table: 640 };
const noop = { schedule() { }, flush() { }, setHeights() { }, setAutoFit() { }, reveal() { }, dataReady() { }, rowsFor() { return null; }, fitFor() { return null; } };
if (!grid) return noop;
let heights = null, frame = 0, lastRun = 0, lastWidth = 0, autoFit = true;
let heights = null, frame = 0, lastRun = 0, lastWidth = 0, autoFit = true, positions = null, lastGeometry = null;
const state = new Map();
const shrinkVotes = new Map();
const cards = () => [...grid.children].filter(node => node.dataset.dashboardWidget);
@@ -53,7 +53,7 @@ window.rustProxyOverviewRows = (() => {
}
function apply() {
frame = 0;
if (!grid.getClientRects().length || grid.classList.contains("is-overview-sorting")) return;
if (!grid.getClientRects().length || grid.classList.contains("is-overview-sorting") || grid.classList.contains("is-manual-dragging")) return;
if (!enabled()) { if (grid.classList.contains("has-row-units")) clear(); return; }
lastRun = performance.now();
lastWidth = grid.clientWidth;
@@ -96,7 +96,9 @@ window.rustProxyOverviewRows = (() => {
grid.classList.add("has-row-units");
const geometry = gridGeometry(unit + gap, zoom);
if (!geometry) return;
lastGeometry = geometry;
if (autoFit) { packCards(items, geometry, isStat); return; }
if (positions && positions.columns === geometry.starts.length) { pinCards(items, geometry); return; }
equalizeStatRows(items.filter(isStat), geometry);
alignBottom(items, geometry);
}
@@ -224,6 +226,73 @@ window.rustProxyOverviewRows = (() => {
}
grid.classList.add("has-auto-placement");
}
function pinCards(items, geometry) {
const columns = geometry.starts.length, occupancy = [];
const free = (r, c, w, h) => {
for (let y = r; y < r + h; y++) for (let x = c; x < c + w; x++) if (occupancy[y]?.[x]) return false;
return true;
};
const mark = (r, c, w, h) => {
for (let y = r; y < r + h; y++) { const row = occupancy[y] || (occupancy[y] = new Uint8Array(columns)); for (let x = c; x < c + w; x++) row[x] = 1; }
};
const model = items.map((node, index) => {
const flow = place(node, geometry), w = Math.min(columns, spanOf(flow)), cell = positions.items[node.dataset.dashboardWidget];
return { node, w, h: rowsOf(node), index, cell, first: node.dataset.dashboardWidget === positions.first };
});
const pinned = model.filter(card => card.cell).sort((a, b) => (b.first - a.first) || a.cell[1] - b.cell[1] || a.cell[0] - b.cell[0] || a.index - b.index);
for (const card of pinned) {
card.c = Math.max(0, Math.min(columns - card.w, card.cell[0]));
card.r = card.cell[1];
while (!free(card.r, card.c, card.w, card.h)) card.r++;
mark(card.r, card.c, card.w, card.h);
}
for (const card of model.filter(card => !card.cell)) {
let placed = false;
for (let r = 0; !placed; r++) for (let c = 0; c + card.w <= columns && !placed; c++) if (free(r, c, card.w, card.h)) { card.r = r; card.c = c; placed = true; }
mark(card.r, card.c, card.w, card.h);
}
for (const card of model) {
card.node.style.setProperty("--overview-col", String(card.c + 1));
card.node.style.setProperty("--overview-cols", String(card.w));
card.node.style.setProperty("--overview-row", String(card.r + 1));
}
grid.classList.add("has-auto-placement");
}
function currentPositions() {
const geometry = lastGeometry || gridGeometry(1, zoomOf());
if (!geometry) return null;
const items = {};
for (const node of cards().filter(item => !item.hidden && item.getClientRects().length)) {
const col = Number(node.style.getPropertyValue("--overview-col")), row = Number(node.style.getPropertyValue("--overview-row"));
if (grid.classList.contains("has-auto-placement") && col && row) { items[node.dataset.dashboardWidget] = [col - 1, row - 1]; continue; }
const flow = place(node, geometry);
items[node.dataset.dashboardWidget] = [flow.first, flow.row];
}
return { columns: geometry.starts.length, items };
}
function cellAt(clientX, clientY) {
const geometry = lastGeometry;
if (!geometry) return null;
const box = grid.getBoundingClientRect();
const x = (clientX - box.left) / geometry.zoom - geometry.left, y = (clientY - box.top) / geometry.zoom - geometry.top;
const column = geometry.starts.reduce((best, start, index) => Math.abs(start - x) < Math.abs(geometry.starts[best] - x) ? index : best, 0);
return { column, row: Math.max(0, Math.round(y / geometry.step)), columns: geometry.starts.length, step: geometry.step };
}
function cellBox(column, row, span, rows) {
const geometry = lastGeometry;
if (!geometry) return null;
const box = grid.getBoundingClientRect(), columns = geometry.starts.length;
const first = Math.max(0, Math.min(columns - 1, column)), last = Math.max(first, Math.min(columns - 1, first + span - 1));
const left = box.left + (geometry.left + geometry.starts[first]) * geometry.zoom;
const right = box.left + (geometry.left + geometry.starts[last] + geometry.tracks[last]) * geometry.zoom;
const top = box.top + (geometry.top + row * geometry.step) * geometry.zoom;
return { left, top, width: right - left, height: Math.max(1, rows * geometry.step - (geometry.step - (parseFloat(getComputedStyle(grid).getPropertyValue("--overview-row-unit")) || geometry.step))) * geometry.zoom };
}
function setPositions(value) {
positions = value && typeof value === "object" && value.items ? value : null;
grid.classList.toggle("has-pinned-layout", !!positions);
schedule(true);
}
function setRows(node, rows) {
if (node.dataset.dashboardRows === String(rows)) return;
node.style.setProperty("--overview-rows", String(rows));
@@ -328,6 +397,10 @@ window.rustProxyOverviewRows = (() => {
schedule,
flush,
setHeights,
setPositions,
currentPositions,
cellAt,
cellBox,
setAutoFit,
reveal,
dataReady,
+17 -3
View File
@@ -14,7 +14,7 @@ const ADMIN_DEFAULT_HIDDEN_WIDGETS = Object.freeze([...new Set([
const ADMIN_APPEARANCE_DEFAULTS = Object.freeze({
theme: "dark", language: "auto", ui_scale: 100, time_format: "24h", chart_style: "default",
chart_axes: false, interface_icons: false, logo_animation: false, stable_dialog_position: true,
button_style: "normal", corner_style: "default", table_density: "normal", dashboard_density: ADMIN_DASHBOARD_DEFAULTS.dashboard_density, dashboard_widgets: [...ADMIN_DASHBOARD_WIDGETS], dashboard_hidden_widgets: [...ADMIN_DEFAULT_HIDDEN_WIDGETS], dashboard_widget_sizes: null, dashboard_widget_heights: null, dashboard_auto_fit: true, sidebar_collapsed: false,
button_style: "normal", corner_style: "default", table_density: "normal", dashboard_density: ADMIN_DASHBOARD_DEFAULTS.dashboard_density, dashboard_widgets: [...ADMIN_DASHBOARD_WIDGETS], dashboard_hidden_widgets: [...ADMIN_DEFAULT_HIDDEN_WIDGETS], dashboard_widget_sizes: null, dashboard_widget_heights: null, dashboard_widget_positions: null, dashboard_auto_fit: true, sidebar_collapsed: false,
});
const CHART_STYLE_KEYS = Object.freeze({ default: "chartStyleDefault", soft: "chartStyleSoft", technical: "chartStyleTechnical", high_contrast: "chartStyleHighContrast", neon: "chartStyleNeon", monochrome: "chartStyleMonochrome", warm: "chartStyleWarm", cool: "chartStyleCool", sunset: "chartStyleSunset", aurora: "chartStyleAurora", ocean: "chartStyleOcean", forest: "chartStyleForest", pastel: "chartStylePastel", terminal: "chartStyleTerminal", blueprint: "chartStyleBlueprint", colorblind: "chartStyleColorblind" });
let adminPreferences = null, adminPreferencesLoading = null, adminPreferencesWrite = Promise.resolve(), adminPreferencesUnavailable = false;
@@ -70,6 +70,18 @@ function normalizeDashboardWidgetSizes(value) {
return result;
}
const DASHBOARD_MAX_ROWS = 32;
function normalizeDashboardWidgetPositions(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const columns = Number(value.columns);
if (!Number.isInteger(columns) || columns < 1 || columns > 24 || !value.items || typeof value.items !== "object") return null;
const items = {};
for (const [id, cell] of Object.entries(value.items)) {
if (!ADMIN_DASHBOARD_BY_ID.has(id) || !Array.isArray(cell) || cell.length !== 2) continue;
const [column, row] = cell.map(Number);
if (Number.isInteger(column) && Number.isInteger(row) && column >= 0 && column < columns && row >= 0 && row <= 2048) items[id] = [column, row];
}
return Object.keys(items).length ? { columns, items } : null;
}
function normalizeDashboardWidgetHeights(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const result = {};
@@ -310,6 +322,8 @@ function applyAdminPreferences(value, cache = true) {
const savedSizes = normalizeDashboardWidgetSizes(value.dashboard_widget_sizes);
const savedHeights = normalizeDashboardWidgetHeights(value.dashboard_widget_heights);
const savedAutoFit = value.dashboard_auto_fit !== false;
const savedPositions = normalizeDashboardWidgetPositions(value.dashboard_widget_positions);
window.rustProxyOverviewRows?.setPositions?.(editing ? editing.positions : savedPositions);
window.rustProxyOverviewRows?.setAutoFit?.(editing ? editing.autoFit !== false : savedAutoFit);
if (editing) applyDashboardLayout(editing.order, editing.hidden, editing.sizes, editing.heights);
else applyDashboardLayout(savedOrder, savedHidden, savedSizes, savedHeights);
@@ -318,7 +332,7 @@ function applyAdminPreferences(value, cache = true) {
refresh: normalizeRefreshPreferences(value.refresh),
theme: applyAdminTheme(value.theme, cache), language: applyAdminLanguage(value.language, cache, false), ui_scale: applyAdminUiScale(value.ui_scale, cache),
time_format: applyAdminTimeFormat(value.time_format), chart_style: applyAdminChartStyle(value.chart_style), chart_axes: applyAdminChartAxes(value.chart_axes), interface_icons: applyAdminInterfaceIcons(value.interface_icons), logo_animation: applyAdminLogoAnimation(value.logo_animation), stable_dialog_position: applyAdminStableDialogPosition(value.stable_dialog_position), button_style: applyAdminButtonStyle(value.button_style), corner_style: applyAdminCornerStyle(value.corner_style, cache), table_density: applyAdminTableDensity(value.table_density),
dashboard_density: applyAdminDashboardDensity(value.dashboard_density), dashboard_widgets: savedOrder, dashboard_hidden_widgets: savedHidden, dashboard_widget_sizes: savedSizes, dashboard_widget_heights: savedHeights, dashboard_auto_fit: savedAutoFit,
dashboard_density: applyAdminDashboardDensity(value.dashboard_density), dashboard_widgets: savedOrder, dashboard_hidden_widgets: savedHidden, dashboard_widget_sizes: savedSizes, dashboard_widget_heights: savedHeights, dashboard_widget_positions: savedPositions, dashboard_auto_fit: savedAutoFit,
};
adminPreferences = normalized;
window.rustProxyRefresh?.update(normalized.refresh);
@@ -370,7 +384,7 @@ function updateAdminPreferences(patch) {
next.refresh = normalizeRefreshPreferences(next.refresh);
next.theme = normalizeAdminTheme(next.theme); next.language = normalizeAdminLanguage(next.language); next.ui_scale = normalizeAdminUiScale(next.ui_scale);
next.time_format = normalizeAdminTimeFormat(next.time_format); next.chart_style = normalizeAdminChartStyle(next.chart_style); next.chart_axes = next.chart_axes === true; next.interface_icons = next.interface_icons === true; next.logo_animation = next.logo_animation === true; next.stable_dialog_position = next.stable_dialog_position !== false; next.button_style = normalizeAdminButtonStyle(next.button_style); next.corner_style = normalizeAdminCornerStyle(next.corner_style); next.table_density = normalizeAdminDensity(next.table_density);
next.dashboard_density = normalizeAdminDensity(next.dashboard_density, "compact"); next.dashboard_widgets = normalizeDashboardWidgets(next.dashboard_widgets); next.dashboard_hidden_widgets = normalizeHiddenDashboardWidgets(next.dashboard_hidden_widgets); next.dashboard_widget_sizes = normalizeDashboardWidgetSizes(next.dashboard_widget_sizes); next.dashboard_widget_heights = normalizeDashboardWidgetHeights(next.dashboard_widget_heights); next.dashboard_auto_fit = next.dashboard_auto_fit !== false; next.sidebar_collapsed = next.sidebar_collapsed === true;
next.dashboard_density = normalizeAdminDensity(next.dashboard_density, "compact"); next.dashboard_widgets = normalizeDashboardWidgets(next.dashboard_widgets); next.dashboard_hidden_widgets = normalizeHiddenDashboardWidgets(next.dashboard_hidden_widgets); next.dashboard_widget_sizes = normalizeDashboardWidgetSizes(next.dashboard_widget_sizes); next.dashboard_widget_heights = normalizeDashboardWidgetHeights(next.dashboard_widget_heights); next.dashboard_widget_positions = normalizeDashboardWidgetPositions(next.dashboard_widget_positions); next.dashboard_auto_fit = next.dashboard_auto_fit !== false; next.sidebar_collapsed = next.sidebar_collapsed === true;
const saved = await api("/api/preferences", { method: "PUT", body: JSON.stringify(next) });
if (!authenticated || epoch !== authEpoch) return adminPreferences;
return applyAdminPreferences(saved);
+4 -1
View File
@@ -97,6 +97,7 @@ function renderSettings() {
$("global-ip-rules").value = rulesText(acl);
$("global-method-mode").value = methods.mode || "off";
$("global-method-list").value = (methods.methods || []).join("\n");
globalMethodPicker()?.refresh();
$("global-content-type-enabled").checked = content.enabled === true;
$("global-content-type-list").value = (content.blocked || []).join("\n");
$("global-rate-enabled").checked = rate.enabled === true;
@@ -142,9 +143,11 @@ function syncGlobalSecurityControls() {
}
}
globalCountryPicker();
globalMethodPicker();
syncGlobalPolicySummary();
}
let globalCountryPickerInstance = null;
let globalCountryPickerInstance = null, globalMethodPickerInstance = null;
function globalMethodPicker() { if (!globalMethodPickerInstance) globalMethodPickerInstance = window.rustProxyMethodPicker?.attach($("global-method-list")) || null; return globalMethodPickerInstance; }
function globalCountryPicker() { if (!globalCountryPickerInstance) globalCountryPickerInstance = window.rustProxyCountryPicker?.attach($("global-country-list")) || null; return globalCountryPickerInstance; }
function syncGlobalPolicySummary() {
const nav = $("global-policy-summary"); if (!nav) return;
+32 -6
View File
@@ -20,7 +20,7 @@ window.rustProxyCacheRules = (() => {
const ACTIONS = {
request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
deliver: ["set_header", "remove_header"],
deliver: ["set_header", "default_header", "remove_header"],
};
const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
@@ -92,6 +92,7 @@ window.rustProxyCacheRules = (() => {
case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
case "remove_header": return `unset resp.http.${a.name};`;
case "default_header": return `if (!resp.http.${a.name}) { set resp.http.${a.name} = "${esc(a.value ?? "")}"; }`;
default: return `# ${a.type}`;
}
});
@@ -121,7 +122,8 @@ window.rustProxyCacheRules = (() => {
const actions = rule.actions.map(a => {
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
if (a.type === "set_header" || a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
if (a.type === "set_header" || a.type === "default_header") return `${actionLabel(a.type)}: ${a.name || "-"}${a.value ? ` = ${a.value}` : ""}`;
if (a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
return actionLabel(a.type);
});
return actions.join(" · ");
@@ -142,6 +144,9 @@ window.rustProxyCacheRules = (() => {
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
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" }] }],
};
function applicableGlobals(vhostId) {
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
@@ -172,6 +177,19 @@ window.rustProxyCacheRules = (() => {
if (skippedBy.length) notes.push(t("cacheRulesIgnoredIn").replace("{vhosts}", skippedBy.join(", ")));
return notes;
}
let targets = null, targetsLoading = null;
function loadTargets() {
if (targets || targetsLoading || typeof authenticated === "undefined" || !authenticated) return targetsLoading;
targetsLoading = api("/api/cache/rules/targets")
.then(data => { targets = Array.isArray(data.targets) ? data.targets : []; document.dispatchEvent(new Event("rustproxy-cache-targets")); })
.catch(() => { })
.finally(() => { targetsLoading = null; });
return targetsLoading;
}
function targetList() {
return targets || (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, hosts: vhost.frontend?.hosts || [], docker: false }));
}
const targetTitle = target => target.docker ? `${target.hosts?.[0] || target.id} (Docker)` : target.id;
let hits = {};
async function loadHits() {
if (!authenticated) return;
@@ -203,7 +221,7 @@ window.rustProxyCacheRules = (() => {
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
toolbar.append(templates, importButton, exportButton, addButton);
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; ignoreBox.id = "vh-cache-ignore-global-rules";
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; if (options.ignoreId !== "") ignoreBox.id = options.ignoreId || "vh-cache-ignore-global-rules";
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
const notices = el("div", undefined, "cache-rules-notices");
const list = el("div", undefined, "cache-rules-list");
@@ -224,6 +242,8 @@ window.rustProxyCacheRules = (() => {
for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
function taken() { return new Set(rules.map(rule => rule.id)); }
void loadTargets();
document.addEventListener("rustproxy-cache-targets", () => { if (root.isConnected && scope === "global" && open.size) render(); });
function renderNotices() {
notices.replaceChildren();
if (scope !== "vhost") return;
@@ -285,7 +305,7 @@ window.rustProxyCacheRules = (() => {
grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
body.append(grid);
if (scope === "global") {
const vhostItems = (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, title: vhost.name || vhost.id, detail: (vhost.frontend?.hosts || []).slice(0, 3).join(", ") }));
const vhostItems = targetList().map(target => ({ id: target.id, title: targetTitle(target), detail: target.docker ? target.id : (target.hosts || []).slice(0, 3).join(", "), search: (target.hosts || []).join(" "), badge: target.docker ? "Docker" : "", badgeClass: "is-allow" }));
const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
picker.addEventListener("change", changed);
@@ -358,6 +378,7 @@ window.rustProxyCacheRules = (() => {
case "hash_cookie": params.append(nameInput("lang")); break;
case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
case "default_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("Cache-Control"), value); break; }
case "remove_header": params.append(nameInput("X-Powered-By")); break;
default: params.append(el("small", t(`cacheRuleActionHelp${action.type.split("_").map(p => p[0].toUpperCase() + p.slice(1)).join("")}`), "fine"));
}
@@ -370,7 +391,12 @@ window.rustProxyCacheRules = (() => {
const grid = el("div", undefined, "cache-rules-tester-grid");
const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...(envelope?.config?.vhosts || []).map(vhost => [vhost.id, vhost.name || vhost.id])], vhostId, t("cacheRulesTesterVhost"));
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])], vhostId, t("cacheRulesTesterVhost"));
document.addEventListener("rustproxy-cache-targets", () => {
const current = vhostSelect.value;
vhostSelect.replaceChildren(...[["", t("cacheRulesTesterNoVhost")], ...targetList().map(target => [target.id, targetTitle(target)])].map(([value, text]) => { const option = el("option", text); option.value = value; return option; }));
vhostSelect.value = [...vhostSelect.options].some(option => option.value === current) ? current : "";
});
const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
const clientIp = textInput("", "203.0.113.10", "mono");
const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
@@ -443,7 +469,7 @@ window.rustProxyCacheRules = (() => {
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
}
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "default_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
}
return rules.map(rule => clean(rule, scope === "global"));
}
+4
View File
@@ -139,6 +139,8 @@ curl --fail --show-error --request POST \\
$("certificate-api-revoke-all").disabled = !credentials.length;
$("certificate-api-new").disabled = credentials.length >= max || ($("certificate-api-form").hidden === false && !certificateApiEditingKey);
const form = $("certificate-api-form"), editingForm = !form.hidden && certificateApiEditingKey;
const scrolled = [...form.querySelectorAll("*")].filter(node => node.scrollTop > 0).map(node => [node, node.scrollTop]);
const focused = form.contains(document.activeElement) ? document.activeElement : null;
if (editingForm) $("certificate-api-card").insertBefore(form, target);
target.replaceChildren();
for (const credential of credentials) {
@@ -197,6 +199,8 @@ curl --fail --show-error --request POST \\
target.append(container);
if (editingForm && certificateApiEditingKey === credential.key_id) container.append(form);
}
for (const [node, top] of scrolled) node.scrollTop = top;
if (focused && document.activeElement !== focused) focused.focus({ preventScroll: true });
certificateApiExample();
}
async function loadCertificateApi(force = false) {
File diff suppressed because it is too large. Load diff
+120 -19
View File
@@ -1,4 +1,3 @@
.host-chip-editor.field-invalid,
.listener-choices.field-invalid {
border-color: var(--red) !important;
@@ -1724,6 +1723,22 @@ html.app-loading,
min-width: 0;
}
.acl-picker .acl-picker-options>label.acl-picker-option {
display: flex;
align-items: flex-start;
gap: 9px;
margin: 0;
padding: 6px 9px;
}
.acl-picker .acl-picker-options {
gap: 3px;
}
.acl-picker .acl-picker-option-content {
gap: 2px;
}
.acl-picker-option:has(input:checked) {
border-color: var(--pill-live-line);
background: var(--nav-selected-bg);
@@ -1731,10 +1746,11 @@ html.app-loading,
.acl-picker-option input[type=checkbox] {
flex: 0 0 auto;
width: 16px !important;
height: 16px !important;
min-height: 16px !important;
margin: 2px 0 0;
width: var(--ui-check-size) !important;
height: var(--ui-check-size) !important;
min-width: var(--ui-check-size) !important;
min-height: var(--ui-check-size) !important;
margin: calc((18px - var(--ui-check-size)) / 2) 0 0;
}
.acl-picker-option input:disabled {
@@ -1760,8 +1776,13 @@ html.app-loading,
align-items: center;
}
.acl-picker-option-heading {
min-height: 18px;
}
.acl-picker-option-heading strong {
font-size: 12px;
line-height: 18px;
color: var(--text);
overflow-wrap: anywhere;
}
@@ -1954,6 +1975,7 @@ html.app-loading,
margin: 0 !important;
min-width: 0;
}
.fine+:is(.switch-grid, .settings-tabs, .table-scroll, .soft-card, .appearance-settings-grid, .runtime-information-grid, details),
.form-actions+.fine,
.table-scroll+:is(.empty, .fine),
@@ -2025,18 +2047,97 @@ h2+.fine {
}
}
@media (min-width: 761px) { .redirect-card .vhost-card-head { align-items: center; } }
.redirect-flow { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1.4fr); gap: 12px; align-items: center; margin-top: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0); background: var(--bg); }
.redirect-flow-from, .redirect-flow-to { display: flex; flex-wrap: wrap; gap: 6px; min-width: 0; align-items: center; }
.redirect-flow-to { flex-direction: column; align-items: flex-start; gap: 3px; }
.redirect-flow-arrow { color: var(--muted); font-size: 16px; line-height: 1; }
.redirect-host-chip { max-width: 100%; padding: 2px 6px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0); font: 11px/1.45 var(--mono); color: var(--text); overflow-wrap: anywhere; }
.redirect-target { font: 12px/1.45 var(--mono); font-weight: 600; color: var(--green); overflow-wrap: anywhere; min-width: 0; }
.redirect-target-more { font-size: 11px; color: var(--muted); }
.redirect-meta { display: flex; flex-wrap: wrap; gap: 4px 18px; margin-top: 10px; font-size: 11px; color: var(--muted); }
.redirect-meta-item { display: inline-flex; gap: 6px; min-width: 0; }
.redirect-meta-item b { color: var(--text); font-weight: 600; overflow-wrap: anywhere; }
@media (max-width: 760px) {
.redirect-flow { grid-template-columns: minmax(0, 1fr); gap: 6px; }
.redirect-flow-arrow { transform: rotate(90deg); justify-self: start; }
@media (min-width: 761px) {
.redirect-card .vhost-card-head {
align-items: center;
}
}
.redirect-flow {
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1.4fr);
gap: 12px;
align-items: center;
margin-top: 12px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 0);
background: var(--bg);
}
.redirect-flow-from,
.redirect-flow-to {
display: flex;
flex-wrap: wrap;
gap: 6px;
min-width: 0;
align-items: center;
}
.redirect-flow-to {
flex-direction: column;
align-items: flex-start;
gap: 3px;
}
.redirect-flow-arrow {
color: var(--muted);
font-size: 16px;
line-height: 1;
}
.redirect-host-chip {
max-width: 100%;
padding: 2px 6px;
border: 1px solid var(--line);
border-radius: var(--rp-radius-control, 0);
font: 11px/1.45 var(--mono);
color: var(--text);
overflow-wrap: anywhere;
}
.redirect-target {
font: 12px/1.45 var(--mono);
font-weight: 600;
color: var(--green);
overflow-wrap: anywhere;
min-width: 0;
}
.redirect-target-more {
font-size: 11px;
color: var(--muted);
}
.redirect-meta {
display: flex;
flex-wrap: wrap;
gap: 4px 18px;
margin-top: 10px;
font-size: 11px;
color: var(--muted);
}
.redirect-meta-item {
display: inline-flex;
gap: 6px;
min-width: 0;
}
.redirect-meta-item b {
color: var(--text);
font-weight: 600;
overflow-wrap: anywhere;
}
@media (max-width: 760px) {
.redirect-flow {
grid-template-columns: minmax(0, 1fr);
gap: 6px;
}
.redirect-flow-arrow {
transform: rotate(90deg);
justify-self: start;
}
}
File diff suppressed because it is too large. Load diff
+280 -53
View File
@@ -1,4 +1,3 @@
@media (min-width:1201px) {
#panel-overview .stats-grid {
grid-template-columns: repeat(6, minmax(0, 1fr));
@@ -117,6 +116,7 @@
}
@media (max-width:900px) {
.logging-builder-layout,
.logging-format-actions,
.acl-policy-custom-controls,
@@ -405,6 +405,7 @@
}
@media (max-width:700px) {
#panel-tls .certificate-operation-heading,
#panel-tls .certificate-subheading,
#panel-tls .certificate-workspace-heading,
@@ -762,6 +763,7 @@
}
@media (max-width:640px) {
.acl-rule,
.basic-user {
grid-template-columns: 1fr 1fr;
@@ -847,7 +849,7 @@
}
.breadcrumb b,
.nav span {
.nav span {
display: none;
}
@@ -1065,6 +1067,7 @@
}
@media (max-width:760px) {
.redirect-card .vhost-detail-strip,
.redirect-rule .vh-grid,
.listener-choices,
@@ -1554,6 +1557,7 @@
}
@media (prefers-reduced-motion:reduce) {
.docker-publish-field .docker-publish,
.docker-publish-field .docker-publish::before,
#panel-overview .overview-meter-fill,
@@ -1736,63 +1740,286 @@
}
.docker-service-editor:not(.docker-service-metrics)>summary,
.docker-health-editor>summary, .docker-acl-editor>summary, .docker-protocol-editor>summary, .docker-timeout-editor>summary, .docker-passive-health-editor>summary {
.docker-health-editor>summary,
.docker-acl-editor>summary,
.docker-cache-editor>summary,
.docker-protocol-editor>summary,
.docker-timeout-editor>summary,
.docker-passive-health-editor>summary {
list-style: none;
}
.docker-service-editor>summary::-webkit-details-marker, .docker-health-editor>summary::-webkit-details-marker, .docker-acl-editor>summary::-webkit-details-marker,
.docker-protocol-editor>summary::-webkit-details-marker, .docker-timeout-editor>summary::-webkit-details-marker, .docker-passive-health-editor>summary::-webkit-details-marker { display: none; }
.docker-service-editor>summary::before, .docker-health-editor>summary::before, .docker-acl-editor>summary::before,
.docker-protocol-editor>summary::before, .docker-timeout-editor>summary::before, .docker-passive-health-editor>summary::before {
content: "›"; display: inline-block; width: 14px; flex: 0 0 14px; color: var(--muted); font-size: 14px; line-height: 1; transition: transform .15s ease;
.docker-service-editor>summary::-webkit-details-marker,
.docker-health-editor>summary::-webkit-details-marker,
.docker-acl-editor>summary::-webkit-details-marker,
.docker-cache-editor>summary::-webkit-details-marker,
.docker-protocol-editor>summary::-webkit-details-marker,
.docker-timeout-editor>summary::-webkit-details-marker,
.docker-passive-health-editor>summary::-webkit-details-marker {
display: none;
}
.docker-service-editor[open]>summary::before, .docker-health-editor[open]>summary::before, .docker-acl-editor[open]>summary::before,
.docker-protocol-editor[open]>summary::before, .docker-timeout-editor[open]>summary::before, .docker-passive-health-editor[open]>summary::before { transform: rotate(90deg); color: var(--text); }
.docker-service-editor>summary>span { flex: 0 0 auto; }
.docker-service-editor>summary .docker-config-hint { flex: 1; min-width: 0; }
.docker-service-editor:not(.docker-service-metrics)>summary:hover>span { color: var(--green); }
.docker-service-editor[open]:not(.docker-service-metrics) { border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 6px); background: var(--panel2); padding: 10px 12px 12px; }
.docker-service-editor>summary::before,
.docker-health-editor>summary::before,
.docker-acl-editor>summary::before,
.docker-cache-editor>summary::before,
.docker-protocol-editor>summary::before,
.docker-timeout-editor>summary::before,
.docker-passive-health-editor>summary::before {
content: "›";
display: inline-block;
width: 14px;
flex: 0 0 14px;
color: var(--muted);
font-size: 14px;
line-height: 1;
transition: transform .15s ease;
}
.docker-service-editor[open]>summary::before,
.docker-health-editor[open]>summary::before,
.docker-acl-editor[open]>summary::before,
.docker-cache-editor[open]>summary::before,
.docker-protocol-editor[open]>summary::before,
.docker-timeout-editor[open]>summary::before,
.docker-passive-health-editor[open]>summary::before {
transform: rotate(90deg);
color: var(--text);
}
.docker-service-editor>summary>span {
flex: 0 0 auto;
}
.docker-service-editor>summary .docker-config-hint {
flex: 1;
min-width: 0;
}
.docker-service-editor:not(.docker-service-metrics)>summary:hover>span {
color: var(--green);
}
.docker-service-editor[open]:not(.docker-service-metrics) {
border: 1px solid var(--line);
border-radius: var(--rp-radius-surface, 6px);
background: var(--panel2);
padding: 10px 12px 12px;
}
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-health-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-acl-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-cache-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-protocol-editor,
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-timeout-editor { margin-top: 10px; }
.docker-service-editor>summary:focus-visible, .docker-acl-editor>summary:focus-visible, .docker-protocol-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; border-radius: var(--rp-radius-control, 0px); }
.vh-tabs { gap: 2px; padding: 4px 0 0; border-bottom: 1px solid var(--line); margin-bottom: 12px; }
.vh-tabs button { font-size: 12px; padding: 8px 12px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--muted); margin-bottom: -1px; }
.vh-tabs button:hover { color: var(--text); background: var(--panel2); }
.vh-tabs button.active { color: var(--text); background: transparent; border-bottom-color: var(--green); font-weight: 600; }
.vh-tabs button:focus-visible { outline: 2px solid var(--green); outline-offset: -2px; }
.vh-form>.card-heading { gap: 10px; align-items: center; }
.vh-form .form-actions { display: flex; gap: 8px; align-items: center; }
.vh-form .form-actions .primary { order: 0; }
.vh-form .form-actions .quiet { order: 1; }
.vh-setting-section>h3 { letter-spacing: .01em; }
.vh-tabs { flex-wrap: wrap; overflow: visible; row-gap: 0; }
@media (max-width:700px) { .vh-tabs button { font-size: 11px; padding: 7px 8px; } }
.auto-id-hint, .auto-cert-hint { display: block; margin-top: 3px; color: var(--muted); font-size: 11px; line-height: 1.35; }
.auto-id-reset { justify-self: start; margin-top: 3px; padding: 2px 8px; font-size: 11px; }
.auto-id-hint[hidden], .auto-cert-hint[hidden], .auto-id-reset[hidden] { display: none; }
.auto-id-field>span:first-child { color: var(--muted); }
.auto-id-field.is-compact>input { display: none; }
.auto-id-row { display: flex; align-items: center; gap: 8px; min-height: 32px; padding: 0 2px; }
.auto-id-value { font-family: var(--mono, monospace); font-size: 13px; color: var(--text); overflow-wrap: anywhere; }
.auto-id-value.is-pending { color: var(--muted); font-style: italic; font-family: inherit; font-size: 12px; }
.auto-id-badge { display: inline-flex; align-items: center; padding: 2px 6px; border: 1px solid var(--pill-line); border-radius: var(--rp-radius-control, 0); color: var(--accent); font: 9px var(--mono); letter-spacing: 1px; text-transform: uppercase; }
.auto-id-change { padding: 2px 8px; font-size: 11px; margin-left: auto; }
.auto-id-row[hidden], .auto-id-change[hidden], .auto-id-badge[hidden] { display: none; }
.auto-id-field input { font-family: var(--mono, monospace); font-size: 12px; }
.docker-service-editor>summary, .docker-health-editor>summary, .docker-acl-editor>summary,
.docker-protocol-editor>summary, .docker-timeout-editor>summary, .docker-passive-health-editor>summary {
justify-content: flex-start; text-align: left;
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-timeout-editor {
margin-top: 10px;
}
.docker-service-editor>summary>span, .docker-health-editor>summary>span, .docker-acl-editor>summary>span,
.docker-protocol-editor>summary>span, .docker-timeout-editor>summary>span, .docker-passive-health-editor>summary>span { text-align: left; }
.docker-service-editor>summary .docker-config-hint, .docker-health-editor>summary>small, .docker-acl-editor>summary>small,
.docker-protocol-editor>summary>small, .docker-timeout-editor>summary>small, .docker-passive-health-editor>summary>small {
flex: 1 1 auto; min-width: 0; text-align: left;
.docker-service-editor>summary:focus-visible,
.docker-acl-editor>summary:focus-visible,
.docker-cache-editor>summary:focus-visible,
.docker-protocol-editor>summary:focus-visible,
.docker-timeout-editor>summary:focus-visible,
.docker-health-editor>summary:focus-visible {
outline: 2px solid var(--green);
outline-offset: 2px;
border-radius: var(--rp-radius-control, 0px);
}
.vh-tabs {
gap: 2px;
padding: 4px 0 0;
border-bottom: 1px solid var(--line);
margin-bottom: 12px;
}
.vh-tabs button {
font-size: 12px;
padding: 8px 12px;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: transparent;
color: var(--muted);
margin-bottom: -1px;
}
.vh-tabs button:hover {
color: var(--text);
background: var(--panel2);
}
.vh-tabs button.active {
color: var(--text);
background: transparent;
border-bottom-color: var(--green);
font-weight: 600;
}
.vh-tabs button:focus-visible {
outline: 2px solid var(--green);
outline-offset: -2px;
}
.vh-form>.card-heading {
gap: 10px;
align-items: center;
}
.vh-form .form-actions {
display: flex;
gap: 8px;
align-items: center;
}
.vh-form .form-actions .primary {
order: 0;
}
.vh-form .form-actions .quiet {
order: 1;
}
.vh-setting-section>h3 {
letter-spacing: .01em;
}
.vh-tabs {
flex-wrap: wrap;
overflow: visible;
row-gap: 0;
}
@media (max-width:700px) {
.vh-tabs button {
font-size: 11px;
padding: 7px 8px;
}
}
.auto-id-hint,
.auto-cert-hint {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
}
.auto-id-reset {
justify-self: start;
margin-top: 3px;
padding: 2px 8px;
font-size: 11px;
}
.auto-id-hint[hidden],
.auto-cert-hint[hidden],
.auto-id-reset[hidden] {
display: none;
}
.auto-id-field>span:first-child {
color: var(--muted);
}
.auto-id-field.is-compact>input {
display: none;
}
.auto-id-row {
display: flex;
align-items: center;
gap: 8px;
min-height: 32px;
padding: 0 2px;
}
.auto-id-value {
font-family: var(--mono, monospace);
font-size: 13px;
color: var(--text);
overflow-wrap: anywhere;
}
.auto-id-value.is-pending {
color: var(--muted);
font-style: italic;
font-family: inherit;
font-size: 12px;
}
.auto-id-badge {
display: inline-flex;
align-items: center;
padding: 2px 6px;
border: 1px solid var(--pill-line);
border-radius: var(--rp-radius-control, 0);
color: var(--accent);
font: 9px var(--mono);
letter-spacing: 1px;
text-transform: uppercase;
}
.auto-id-change {
padding: 2px 8px;
font-size: 11px;
margin-left: auto;
}
.auto-id-row[hidden],
.auto-id-change[hidden],
.auto-id-badge[hidden] {
display: none;
}
.auto-id-field input {
font-family: var(--mono, monospace);
font-size: 12px;
}
.docker-service-editor>summary,
.docker-health-editor>summary,
.docker-acl-editor>summary,
.docker-cache-editor>summary,
.docker-protocol-editor>summary,
.docker-timeout-editor>summary,
.docker-passive-health-editor>summary {
justify-content: flex-start;
text-align: left;
}
.docker-service-editor>summary>span,
.docker-health-editor>summary>span,
.docker-acl-editor>summary>span,
.docker-cache-editor>summary>span,
.docker-protocol-editor>summary>span,
.docker-timeout-editor>summary>span,
.docker-passive-health-editor>summary>span {
text-align: left;
}
.docker-service-editor>summary .docker-config-hint,
.docker-health-editor>summary>small,
.docker-acl-editor>summary>small,
.docker-cache-editor>summary>small,
.docker-protocol-editor>summary>small,
.docker-timeout-editor>summary>small,
.docker-passive-health-editor>summary>small {
flex: 1 1 auto;
min-width: 0;
text-align: left;
}
@media (min-width:721px) {
.docker-service-editor>summary>span, .docker-health-editor>summary>span, .docker-acl-editor>summary>span,
.docker-protocol-editor>summary>span, .docker-timeout-editor>summary>span, .docker-passive-health-editor>summary>span { flex: 0 0 190px; }
}
.docker-service-editor>summary>span,
.docker-health-editor>summary>span,
.docker-acl-editor>summary>span,
.docker-cache-editor>summary>span,
.docker-protocol-editor>summary>span,
.docker-timeout-editor>summary>span,
.docker-passive-health-editor>summary>span {
flex: 0 0 190px;
}
}
+107 -20
View File
@@ -146,7 +146,6 @@
const ip = String(binding.bind_ip || "");
if (ip && ip !== "0.0.0.0" && ip !== "::" && !ip.startsWith("127.") && ip !== "::1") add(ip, `${ip} (${t("dockerBindingIp")})`);
}
if (agent?.default_target_ip) add(agent.default_target_ip, `${agent.default_target_ip} (${t("dockerAgentDefaultIp")})`);
if (assignment?.target_ip) add(assignment.target_ip, assignment.target_ip);
return [...byIp.entries()];
}
@@ -195,12 +194,22 @@
if (payload?.v !== 1 || token.length < 24 || token.length > 512) throw new Error(t("dockerProvisionInvalid"));
return { ...base, token };
}
function certificateNameKind(name) {
const clean = cleanDomain(name);
if (clean.startsWith("*.")) return "dockerCertNameWildcard";
if (clean.startsWith("www.")) return "dockerCertNameWww";
const agentDomainSet = new Set((cfg().agents || []).flatMap(agentDomains));
return agentDomainSet.has(clean) || clean.split(".").length === 2 ? "dockerCertNameApex" : "dockerCertNameSubdomain";
}
const describeCertificateName = name => `${name} (${t(certificateNameKind(name))})`;
function domainOptionsFor(selected) {
const known = new Map(), add = (domain, detail) => { domain = cleanDomain(domain).replace(/^\*\./, ""); if (domain && domain.includes(".") && validDnsName(domain) && !known.has(domain)) known.set(domain, detail); };
for (const agent of cfg().agents || []) for (const domain of agentDomains(agent)) add(domain, `${t("dockerAgent")}: ${agent.name || agent.id}`);
for (const cert of envelope?.config?.tls?.certificates || []) for (const name of certificateNames(cert)) if (name.startsWith("*.")) add(name, `${t("vhCertificate")}: ${cert.id}`);
const known = new Map(), add = (domain, detail) => { domain = cleanDomain(domain).replace(/^\*\./, ""); if (!domain || !domain.includes(".") || !validDnsName(domain)) return; const list = known.get(domain) || []; if (detail && !list.includes(detail)) list.push(detail); known.set(domain, list); };
const agentsByDomain = new Map();
for (const agent of cfg().agents || []) for (const domain of agentDomains(agent)) agentsByDomain.set(domain, [...(agentsByDomain.get(domain) || []), agent.name || agent.id]);
for (const [domain, agents] of agentsByDomain) add(domain, `${t(agents.length > 1 ? "dockerAgentsShared" : "dockerAgent")}: ${agents.join(", ")}`);
for (const cert of envelope?.config?.tls?.certificates || []) for (const name of certificateNames(cert)) if (name.startsWith("*.")) add(name, `${t("vhCertificate")}: ${cert.id} (${t("dockerCertNameWildcard")})`);
for (const domain of selected) add(domain, "");
return [...known.entries()].map(([id, detail]) => ({ id, title: id, detail }));
return [...known.entries()].map(([id, details]) => ({ id, title: id, detail: details.join(" · ") }));
}
function domainPicker(selected) {
return window.rustProxyChoicePicker.create({
@@ -210,7 +219,7 @@
});
}
function certificatePicker(selected) {
const items = (envelope?.config?.tls?.certificates || []).map(cert => { const names = certificateNames(cert); return { id: cert.id, title: cert.id, detail: names.slice(0, 4).join(", ") + (names.length > 4 ? ` +${names.length - 4}` : ""), search: names.join(" "), badge: cert.issuer ? "ACME" : "", badgeClass: "is-allow" }; });
const items = (envelope?.config?.tls?.certificates || []).map(cert => { const names = certificateNames(cert); return { id: cert.id, title: cert.id, detail: names.slice(0, 4).map(describeCertificateName).join(", ") + (names.length > 4 ? ` +${names.length - 4}` : ""), search: names.join(" "), badge: cert.issuer ? "ACME" : "", badgeClass: "is-allow" }; });
return window.rustProxyChoicePicker.create({ className: "docker-agent-certificates", selected, items, limit: MAX_CERTIFICATES, unknownDetail: "dockerCertificateUnknown", labels: { choose: "dockerCertificatesChoose", selected: "dockerCertificatesSelected", none: "dockerCertificatesNone", empty: "dockerCertificatesEmpty" } });
}
function addressGroup(address, primary) {
@@ -309,7 +318,7 @@
if (!state) { holder.hidden = true; return; }
holder.hidden = false;
const head = el("div", undefined, "docker-agent-diagnostics-head"), inventory = state.inventory;
head.append(el("span", t("dockerAgentDiagnostics"), "small-label"), el("span", state.ok ? t("dockerConnected") : t("dockerError"), `pill ${state.ok ? "live" : "warn"}`.trim()), el("span", `${t("dockerLastChecked")}: ${checkedAgo(state.checked_at_unix_ms)}`, "fine"));
head.append(el("span", t("dockerAgentDiagnostics"), "small-label"), el("span", `${t("dockerLastChecked")}: ${checkedAgo(state.checked_at_unix_ms)}`, "fine"));
if (inventory) head.append(el("span", `${t("dockerHost")}: ${inventory.hostname} · ${t("dockerAgentVersion")}: ${inventory.agent_version} · ${t("dockerServices")}: ${(inventory.services || []).length}`, "fine"));
holder.append(head);
if (!state.ok && state.error) holder.append(el("p", state.error, "fine docker-agent-diagnostics-error"));
@@ -631,16 +640,62 @@
};
}
function aclEditor(assignment, agent) {
const details = el("details", undefined, "docker-acl-editor"), summary = el("summary"); summary.append(el("span", t("dockerAccessControl")), el("small", t("dockerAclSummary"), "fine")); details.append(summary);
const grid = el("div", undefined, "field-grid docker-acl-grid"), profile = profileChoices(selectedProfileIds(assignment), "docker-acl-profile");
const inheritedProfiles = selectedProfileIds(agent);
const profileControl = profileField("dockerAclProfile", profile, inheritedProfiles.length ? `${t("dockerAclProfileInherit")}: ${inheritedProfiles.map(id => (envelope?.config?.acl_profiles || []).find(item => item.id === id)?.name || id).join(", ")}` : t("dockerAclProfileNone"));
profileControl.append(profileWarning(profile, inheritedProfiles.length));
const inline = input("", "checkbox", "docker-acl-inline"); inline.checked = !!assignment?.acl; const inlineLabel = checkboxField("dockerAclInline", inline);
const details = el("details", undefined, "docker-acl-editor"), summary = el("summary"), state = el("small", "", "fine"); summary.append(el("span", t("dockerAccessControl")), state); details.append(summary);
const profiles = envelope?.config?.acl_profiles || [], nameOf = id => profiles.find(item => item.id === id)?.name || id;
const inheritedProfiles = selectedProfileIds(agent), explicit = selectedProfileIds(assignment), inherit = assignment?.inherit_acl_profiles !== false;
const grid = el("div", undefined, "field-grid docker-acl-grid"), profile = profileChoices(explicit.length ? explicit : inherit ? inheritedProfiles : [], "docker-acl-profile");
details._inheritedProfiles = inheritedProfiles;
const help = el("small", "", "fine"), profileControl = el("div", undefined, "docker-field docker-profile-field");
profileControl.append(el("span", t("dockerAclProfile")), profile, help, profileWarning(profile, 0));
const publicAccess = input("", "checkbox", "docker-acl-public"); publicAccess.checked = !explicit.length && !inherit && !assignment?.acl;
const publicLabel = checkboxField("dockerAclPublic", publicAccess); publicLabel.append(el("small", t("dockerAclPublicHelp"), "fine"));
const inline = input("", "checkbox", "docker-acl-inline"); inline.checked = !!assignment?.acl; const inlineLabel = checkboxField("dockerAclInline", inline); inlineLabel.classList.add("docker-acl-inline-row");
const defaultAction = el("select", undefined, "docker-acl-default"); for (const value of ["deny", "allow"]) { const option = el("option", t(value)); option.value = value; defaultAction.append(option); } defaultAction.value = assignment?.acl?.default || "deny";
const rules = document.createElement("textarea"); rules.className = "docker-acl-rules"; rules.rows = 4; rules.maxLength = 32768; rules.spellcheck = false; rules.value = rulesText(assignment?.acl); rules.placeholder = "allow 10.0.0.0/8\ndeny 0.0.0.0/0";
const sync = () => { defaultAction.disabled = !inline.checked; rules.disabled = !inline.checked; }; inline.addEventListener("change", sync); sync();
grid.append(profileControl, inlineLabel, labeled("dockerAclDefault", defaultAction), labeled("dockerAclRules", rules, t("dockerAclHelp"))); details.append(grid); return details;
const sameSet = (a, b) => a.length === b.length && a.every(id => b.includes(id));
const sync = () => {
const open = !publicAccess.checked, picked = window.rustProxyAclPicker.read(profile);
profile.setDisabled?.(!open); profile.classList.toggle("is-disabled", !open); inline.disabled = !open; if (!open) inline.checked = false;
defaultAction.disabled = !open || !inline.checked; rules.disabled = !open || !inline.checked;
const inheritedText = inheritedProfiles.map(nameOf).join(", ");
help.textContent = !inheritedProfiles.length ? t("dockerAclProfileNone")
: sameSet(picked, inheritedProfiles) ? t("dockerAclInheritedActive").replace("{profiles}", inheritedText)
: t("dockerAclInheritedOverridden").replace("{profiles}", inheritedText);
state.textContent = publicAccess.checked ? t("dockerAclStatePublic")
: picked.length ? `${t("dockerAclStateProfiles")}: ${picked.map(nameOf).join(", ")}${inline.checked ? ` + ${t("dockerAclStateInline")}` : ""}`
: inline.checked ? t("dockerAclStateInline") : t("dockerAclStateNone");
};
publicAccess.addEventListener("change", () => { if (publicAccess.checked) profile.select?.([]); else if (!window.rustProxyAclPicker.read(profile).length) profile.select?.(inheritedProfiles); sync(); });
inline.addEventListener("change", sync); profile.addEventListener("change", sync); sync();
grid.append(publicLabel, profileControl, inlineLabel, labeled("dockerAclDefault", defaultAction), labeled("dockerAclRules", rules, t("dockerAclHelp"))); details.append(grid); return details;
}
function collectAcl(row) {
const editor = row.querySelector(".docker-acl-editor"), inherited = editor?._inheritedProfiles || [];
const picked = readProfileChoices(row, ".docker-acl-profile"), isPublic = row.querySelector(".docker-acl-public")?.checked === true;
if (isPublic) return { acl_profile_ids: [], inherit_acl_profiles: false };
if (inherited.length && picked.length === inherited.length && picked.every(id => inherited.includes(id))) return { acl_profile_ids: [], inherit_acl_profiles: true };
if (!picked.length) return { acl_profile_ids: [], inherit_acl_profiles: !inherited.length };
return { acl_profile_ids: picked, inherit_acl_profiles: true };
}
function cacheEditor(assignment, agent, key, enabled) {
const details = el("details", undefined, "docker-cache-editor"), summary = el("summary"); summary.append(el("span", t("dockerCacheSettings")), el("small", t("dockerCacheSettingsHelp"), "fine")); details.append(summary);
const grid = el("div", undefined, "field-grid docker-cache-grid");
const ttl = input(assignment?.cache_default_ttl_seconds ?? "", "number", "docker-cache-ttl"); ttl.min = 0; ttl.max = 31536000; ttl.placeholder = String(envelope?.config?.cache?.default_ttl_seconds ?? "");
grid.append(labeled("dockerCacheTtl", ttl, t("dockerCacheTtlHelp")));
const vhostId = poolRoutes.find(item => item.agent_id === agent.id && item.service_key === key)?.pool_id || "";
const rules = window.rustProxyCacheRules?.create?.({ scope: "vhost", vhostId, rules: assignment?.cache_rules || [], ignoreGlobal: assignment?.cache_ignore_global_rules === true, ignoreId: "" });
if (rules?.node) { rules.node.classList.add("docker-cache-rules"); details._rules = rules; }
details.append(grid); if (rules?.node) details.append(rules.node);
const sync = () => { details.hidden = !enabled.checked; }; enabled.addEventListener("change", sync); sync();
return details;
}
function collectCache(row) {
const details = row.querySelector(".docker-cache-editor"), ttl = row.querySelector(".docker-cache-ttl")?.value.trim();
return {
cache_default_ttl_seconds: ttl === "" || ttl === undefined ? null : Number(ttl),
cache_rules: details?._rules?.read?.() || [],
cache_ignore_global_rules: details?._rules?.ignoreGlobal?.() === true,
};
}
function timeoutEditor(assignment) {
const value = { ...defaultProxyTimeouts(), ...(assignment?.proxy_timeouts || {}) }, details = el("details", undefined, "docker-timeout-editor"), summary = el("summary"); summary.append(el("span", t("dockerProxyTimeouts")), el("small", t("dockerProxyTimeoutsHelp"), "fine")); details.append(summary);
@@ -655,9 +710,9 @@
service_key: row.dataset.key, hostname: row.querySelector(".docker-hostname").value.trim().toLowerCase().replace(/\.$/, ""), domain: row.querySelector(".docker-master-domain")?.value || null, aliases: row._readAliases?.() || [], target_ip: row.querySelector(".docker-target-ip").value || null,
enabled: true, scheme: row.querySelector(".docker-scheme").value, preserve_host: row.querySelector(".docker-preserve-host").checked, force_ssl: row.querySelector(".docker-force-ssl").checked, websockets: row.querySelector(".docker-websockets").checked, http2_enabled: row.querySelector(".docker-http2-enabled").checked, http3_enabled: row.querySelector(".docker-http3-enabled").checked, cache_enabled: row.querySelector(".docker-cache-enabled").checked, transform_enabled: row.querySelector(".docker-transform-enabled").checked, compression_enabled: row.querySelector(".docker-compression-enabled").checked,
compression_zstd: null, compression_br: null, compression_gzip: null, compression_deflate: null,
acl_profile_id: null, acl_profile_ids: readProfileChoices(row, ".docker-acl-profile"),
acl_profile_id: null, ...collectAcl(row), ...collectCache(row),
allow_certificate_mismatch: row.querySelector(".docker-cert-mismatch")?.checked === true,
acl: inline ? { default: row.querySelector(".docker-acl-default").value, rules: parseRules(row.querySelector(".docker-acl-rules").value) } : null,
acl: inline && row.querySelector(".docker-acl-public")?.checked !== true ? { default: row.querySelector(".docker-acl-default").value, rules: parseRules(row.querySelector(".docker-acl-rules").value) } : null,
proxy_timeouts: { connect_timeout_seconds: Number(row.querySelector(".docker-proxy-connect").value), response_header_timeout_seconds: Number(row.querySelector(".docker-proxy-header").value), read_timeout_seconds: Number(row.querySelector(".docker-proxy-read").value), send_timeout_seconds: Number(row.querySelector(".docker-proxy-send").value) },
health_check: collectHealth(row), passive_health: collectPassiveHealth(row)
};
@@ -804,7 +859,7 @@
protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled));
protocolBox.append(protocolSummary, protocolOptions);
route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp();
editor.append(route, protocolBox, aclEditor(assignment, agent), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
editor.append(route, protocolBox, aclEditor(assignment, agent), cacheEditor(assignment, agent, key, cacheEnabled), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment));
const actions = el("div", undefined, "docker-service-actions"), apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions); row.append(editor);
if (agent.enabled !== false && assignment && assignment.enabled !== false) row.append(statisticsSection(agent, key));
function updateHint() { syncCertificateHint(); const targetLabel = target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), aliasCount = aliases.count(); editorHint.textContent = `${expandedHost(host.value.trim() || technical, domainSelect.value) || host.value.trim() || technical} → ${scheme.value.toUpperCase()} · ${targetLabel} · H1${h2Enabled.checked ? "/H2" : ""}${h3Enabled.checked ? "/H3" : ""}${aliasCount ? ` · +${aliasCount} ${t("dockerAliasesShort")}` : ""}`; } updateHint();
@@ -854,14 +909,45 @@
box.append(agentDetails);
const rows = el("div", undefined, "docker-service-list"), assignments = new Map((agent.assignments || []).map(item => [item.service_key, item]));
for (const route of poolRoutes) if (route.agent_id === agent.id && route.source === "labels" && route.assignment && !assignments.has(route.service_key)) assignments.set(route.service_key, { ...route.assignment, from_labels: true });
for (const service of inv.services || []) rows.append(assignmentRow(agent, inv, service, assignments.get(service.key), false)); for (const item of agent.assignments || []) if (!(inv.services || []).some(service => service.key === item.service_key)) rows.append(assignmentRow(agent, inv, null, item, true)); if (!rows.children.length) rows.append(el("p", t("dockerNoPublishedPorts"), "empty")); box.append(rows); target.append(box);
for (const service of inv.services || []) rows.append(assignmentRow(agent, inv, service, assignments.get(service.key), false)); for (const item of agent.assignments || []) if (!(inv.services || []).some(service => service.key === item.service_key)) rows.append(assignmentRow(agent, inv, null, item, true)); if (!rows.children.length) rows.append(el("p", t("dockerNoPublishedPorts"), "empty")); groupServiceRows(agent, rows); box.append(rows); target.append(box);
}
applyViewFilters();
renderDockerMetrics();
}
function serviceGroup(key) {
const compose = /^compose:([^/]+)\//.exec(key || ""); if (compose) return { id: `compose:${compose[1]}`, name: compose[1], type: "compose" };
const container = /^container:(.+):\d+\/[a-z]+$/.exec(key || ""); if (container) return { id: `container:${container[1]}`, name: container[1], type: "container" };
return null;
}
const GROUP_STATE_KEY = "rustproxy.docker.collapsedGroups";
function collapsedGroups() { try { return new Set(JSON.parse(localStorage.getItem(GROUP_STATE_KEY) || "[]")); } catch { return new Set(); } }
function saveCollapsedGroups(set) { try { localStorage.setItem(GROUP_STATE_KEY, JSON.stringify([...set].slice(-256))); } catch { } }
function groupServiceRows(agent, holder) {
const rows = [...holder.querySelectorAll(":scope > .docker-service-row")], buckets = new Map();
for (const row of rows) { const group = serviceGroup(row.dataset.key); if (!group) continue; if (!buckets.has(group.id)) buckets.set(group.id, { group, rows: [] }); buckets.get(group.id).rows.push(row); }
const collapsed = collapsedGroups();
for (const { group, rows: members } of buckets.values()) {
if (members.length < 2) continue;
const stateKey = `${agent.id}|${group.id}`, box = el("details", undefined, "docker-service-group"), summary = el("summary"), body = el("div", undefined, "docker-service-group-rows");
box.open = !collapsed.has(stateKey); box.dataset.groupKey = stateKey;
const published = members.filter(row => row.dockerSort?.published === 0).length;
const hosts = members.filter(row => row.dockerSort?.published === 0).map(row => { try { return new URL(row.querySelector(".docker-open-app")?.href || "").host; } catch { return row.querySelector(".docker-hostname")?.value?.trim(); } }).filter(Boolean);
summary.append(el("span", group.type === "compose" ? "Compose" : t("dockerGroupContainer"), "pill"), el("strong", group.name), el("span", t("dockerGroupCount").replace("{count}", members.length).replace("{published}", published), "fine"));
if (hosts.length) summary.append(el("span", hosts.slice(0, 4).join(", ") + (hosts.length > 4 ? " …" : ""), "fine docker-service-group-hosts"));
box.append(summary, body); members[0].before(box); body.append(...members);
box.dockerSort = members[0].dockerSort;
box.addEventListener("toggle", () => { const set = collapsedGroups(); if (box.open) set.delete(stateKey); else set.add(stateKey); saveCollapsedGroups(set); });
}
}
function sortRowsIn(holder) {
const rows = [...holder.querySelectorAll(":scope > .docker-service-row")];
rows.sort((left, right) => { const a = left.dockerSort?.[listPrefs.sort] ?? "", b = right.dockerSort?.[listPrefs.sort] ?? ""; const result = typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b), locale(), { numeric: true, sensitivity: "base" }); return listPrefs.descending ? -result : result; });
for (const row of rows) holder.append(row);
}
function sortServiceRows(card) {
const holder = card.querySelector(".docker-service-list"); if (!holder) return;
const rows = [...holder.querySelectorAll(":scope > .docker-service-row")];
for (const group of holder.querySelectorAll(":scope > .docker-service-group")) { const body = group.querySelector(".docker-service-group-rows"); sortRowsIn(body); group.dockerSort = body.querySelector(".docker-service-row")?.dockerSort; }
const rows = [...holder.querySelectorAll(":scope > .docker-service-row, :scope > .docker-service-group")];
rows.sort((left, right) => { const a = left.dockerSort?.[listPrefs.sort] ?? "", b = right.dockerSort?.[listPrefs.sort] ?? ""; const result = typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b), locale(), { numeric: true, sensitivity: "base" }); return listPrefs.descending ? -result : result; });
for (const row of rows) holder.append(row);
}
@@ -879,6 +965,7 @@
row.hidden = (!showHidden && viewHidden) || !matches;
if (!row.hidden) visible += 1;
}
for (const group of card.querySelectorAll(".docker-service-group")) group.hidden = ![...group.querySelectorAll(".docker-service-row")].some(row => !row.hidden);
card.hidden = rows.length ? visible === 0 : (!!query && !(card.dataset.searchText || "").includes(query));
}
const hideDisabled = $("docker-hide-disabled");
+76 -3
View File
@@ -155,6 +155,11 @@
<input id="overview-inline-autofit" type="checkbox" checked>
<span data-i18n="overviewLayoutAutoFit">Fit to screen</span>
</label>
<label class="overview-inline-autofit" id="overview-inline-manual-label"
title="Blocks stay in place while dragging; the drop position is only marked">
<input id="overview-inline-manual" type="checkbox">
<span data-i18n="overviewLayoutManual">Arrange manually</span>
</label>
<button class="quiet" id="overview-inline-cancel" type="button"
data-i18n="overviewLayoutInlineCancel">Cancel changes</button>
</div>
@@ -2054,6 +2059,9 @@
tabindex="-1" type="button"></button><button aria-controls="settings-page-prometheus"
aria-selected="false" data-i18n="prometheusTitle" data-settings-tab="prometheus"
id="settings-tab-prometheus" role="tab" tabindex="-1" type="button"></button><button
aria-controls="settings-page-alerts" aria-selected="false" data-i18n="alertSettingsTitle"
data-settings-tab="alerts" id="settings-tab-alerts" role="tab" tabindex="-1"
type="button"></button><button
aria-controls="settings-page-administration" aria-selected="false"
data-i18n="administration" data-settings-tab="administration"
id="settings-tab-administration" role="tab" tabindex="-1" type="button"></button><button
@@ -2546,10 +2554,9 @@
<option value="allow" data-i18n="locationMethodAllow">Allow listed
only</option>
</select></label>
<label><span data-i18n="globalMethodList">Methods (comma, space or newline
separated)</span><textarea id="global-method-list" rows="2"
<div class="settings-chip-field"><span data-i18n="globalMethodList">HTTP methods</span><textarea id="global-method-list" rows="2"
maxlength="1024" spellcheck="false"
placeholder="TRACE, TRACK"></textarea></label>
placeholder="TRACE, TRACK"></textarea></div>
</div>
</section>
<section class="global-policy-section">
@@ -3421,6 +3428,72 @@
<pre class="metrics-preview" hidden="" id="prom-preview-output"></pre>
</form>
</div>
<div aria-labelledby="settings-tab-alerts" class="settings-page"
data-settings-page="alerts" hidden="" id="settings-page-alerts" role="tabpanel">
<form class="card edit-form" id="alerts-form">
<div class="card-heading">
<h2 data-i18n="alertSettingsTitle">Alerts</h2><span class="pill live"
data-i18n="hotApply">LIVE APPLY</span>
</div>
<p class="fine" data-i18n="alertSettingsHelp">Alerts computed from the current state.</p>
<p class="docs-links"><a class="docs-link" data-i18n="alertSettingsDocs"
href="/docs#doc=docs%2FMONITORING.md&amp;section=alerts" rel="noopener noreferrer"
target="_blank">Documentation</a></p>
<section class="settings-section">
<h3 class="subheading" data-i18n="alertSettingsGeneral">General</h3>
<div class="switch-grid">
<label class="check"><input id="alerts-enabled" type="checkbox" /><span
data-i18n="alertSettingsEnabled">Alerts enabled</span></label>
<label class="check"><input id="alerts-notifications" type="checkbox" /><span
data-i18n="alertSettingsNotifications">Show notifications for new alerts</span></label>
</div>
<p class="fine" id="alerts-active" role="status"></p>
</section>
<section class="settings-section alerts-settings-group">
<h3 class="subheading" data-i18n="alertSettingsCertificates">Certificates</h3>
<label class="check"><input id="alerts-certificate-expiry" type="checkbox" /><span
data-i18n="alertSettingsCertificateExpiry">Expired or expiring certificates</span></label>
<div class="field-grid">
<label><span data-i18n="alertSettingsWarningDays">Warning (days before expiry)</span><input
id="alerts-certificate-warning" max="90" min="1" type="number" /></label>
<label><span data-i18n="alertSettingsErrorDays">Error (days before expiry)</span><input
id="alerts-certificate-error" max="89" min="0" type="number" /></label>
</div>
<div class="switch-grid">
<label class="check"><input id="alerts-certificate-renewal" type="checkbox" /><span
data-i18n="alertSettingsRenewal">Failed ACME renewals</span></label>
<label class="check"><input id="alerts-acme-runtime" type="checkbox" /><span
data-i18n="alertSettingsAcmeRuntime">ACME environment not ready</span></label>
</div>
</section>
<section class="settings-section alerts-settings-group">
<h3 class="subheading" data-i18n="alertSettingsResources">Resources</h3>
<label class="check"><input id="alerts-file-descriptors" type="checkbox" /><span
data-i18n="alertSettingsFileDescriptors">File descriptors of RustProxy</span></label>
<div class="field-grid">
<label><span data-i18n="alertSettingsWarningPercent">Warning (% of limit)</span><input
id="alerts-fd-warning" max="99" min="50" type="number" /></label>
<label><span data-i18n="alertSettingsErrorPercent">Error (% of limit)</span><input
id="alerts-fd-error" max="100" min="51" type="number" /></label>
</div>
</section>
<section class="settings-section alerts-settings-group">
<h3 class="subheading" data-i18n="alertSettingsConfiguration">Configuration and updates</h3>
<div class="switch-grid">
<label class="check"><input id="alerts-geoip" type="checkbox" /><span
data-i18n="alertSettingsGeoip">Country rules without a GeoIP database</span></label>
<label class="check"><input id="alerts-prometheus" type="checkbox" /><span
data-i18n="alertSettingsPrometheus">Prometheus exporter open without token</span></label>
<label class="check"><input id="alerts-update" type="checkbox" /><span
data-i18n="alertSettingsUpdate">New RustProxy version (information)</span></label>
</div>
<p class="fine"><span data-i18n="alertSettingsDockerHint">Docker alerts are configured in</span>
<a href="/settings?tab=docker-agents" data-i18n="alertSettingsDockerLink">Settings → Docker agents</a>.</p>
</section>
<div class="form-actions"><button class="primary" data-i18n="apply"
type="submit">Validate, save and apply</button></div>
</form>
</div>
<div aria-labelledby="settings-tab-administration" class="settings-page"
data-settings-page="administration" hidden="" id="settings-page-administration"
role="tabpanel">
+34
View File
@@ -209,6 +209,8 @@
$("tls-policy-key-exchange").textContent = kxGroups.length ? `${t("tlsPqcKeyExchangeGroups")}: ${kxGroups.join(", ")}` : "";
$("tls-policy-effective").textContent = effective.length ? `${t("tlsEffectiveCiphers")}: ${effective.join(", ")}` : "";
$("tls-policy-available").textContent = available.length ? `${t("tlsAvailableCiphers")}: ${available.join(", ")}` : "";
window.rustProxyTlsConfigurator?.refresh();
renderAlertSettings();
window.rustProxyCertificateApi?.render();
if (authenticated && active === "certificate-api") void window.rustProxyCertificateApi?.load?.();
}
@@ -246,6 +248,38 @@
const locked = !!latestStatus?.administration?.listen_locked;
next.administration = { listen: locked ? null : $("admin-listen").value.trim(), tls: $("admin-tls").checked, certificate_id: $("admin-tls").checked ? ($("admin-certificate").value || null) : null, allowed_hosts: additionalAdminHosts($("admin-hosts").value.split(/[\n,]+/), $("admin-public-origin").value.trim()), public_origin: $("admin-public-origin").value.trim() || null, session_days: Number($("admin-session-days").value), panel_compression: Object.fromEntries(["zstd", "br", "gzip"].map(codec => [codec, $(`admin-compression-${codec}`).checked])) };
}, "administration");
const ALERT_DEFAULTS = { enabled: true, notifications: true, certificate_expiry: true, certificate_warning_days: 14, certificate_error_days: 3, certificate_renewal: true, acme_runtime: true, file_descriptors: true, file_descriptors_warning_percent: 80, file_descriptors_error_percent: 95, geoip: true, prometheus: true, update: true };
const ALERT_CHECKS = { "alerts-enabled": "enabled", "alerts-notifications": "notifications", "alerts-certificate-expiry": "certificate_expiry", "alerts-certificate-renewal": "certificate_renewal", "alerts-acme-runtime": "acme_runtime", "alerts-file-descriptors": "file_descriptors", "alerts-geoip": "geoip", "alerts-prometheus": "prometheus", "alerts-update": "update" };
const ALERT_NUMBERS = { "alerts-certificate-warning": "certificate_warning_days", "alerts-certificate-error": "certificate_error_days", "alerts-fd-warning": "file_descriptors_warning_percent", "alerts-fd-error": "file_descriptors_error_percent" };
function syncAlertSettings() {
const on = $("alerts-enabled").checked;
for (const id of [...Object.keys(ALERT_CHECKS), ...Object.keys(ALERT_NUMBERS)]) if (id !== "alerts-enabled") $(id).disabled = !on;
$("alerts-certificate-warning").disabled = !on || !$("alerts-certificate-expiry").checked;
$("alerts-certificate-error").disabled = !on || !$("alerts-certificate-expiry").checked;
$("alerts-fd-warning").disabled = !on || !$("alerts-file-descriptors").checked;
$("alerts-fd-error").disabled = !on || !$("alerts-file-descriptors").checked;
for (const group of document.querySelectorAll("#alerts-form .alerts-settings-group")) group.classList.toggle("is-off", !on);
}
function renderAlertSettings() {
if (!$("alerts-form")) return;
const value = { ...ALERT_DEFAULTS, ...(envelope?.config?.alerts || {}) };
if (!settingsDirty.has("alerts-form")) {
for (const [id, key] of Object.entries(ALERT_CHECKS)) $(id).checked = value[key] !== false;
for (const [id, key] of Object.entries(ALERT_NUMBERS)) $(id).value = value[key];
}
syncAlertSettings();
const active = Array.isArray(latestStatus?.alerts) ? latestStatus.alerts : null;
$("alerts-active").textContent = active === null ? "" : active.length ? t("alertsTitle").replace("{count}", active.length) + ": " + active.map(alert => window.rustProxyAlerts?.text?.(alert) || alert.kind).join(" · ") : t("appHealthAlertsNone");
}
$("alerts-form").addEventListener("change", syncAlertSettings);
bindSettingsForm("alerts-form", next => {
const value = {};
for (const [id, key] of Object.entries(ALERT_CHECKS)) value[key] = $(id).checked;
for (const [id, key] of Object.entries(ALERT_NUMBERS)) { const number = Number($(id).value); if (!Number.isInteger(number)) throw fieldError($(id), t("alertSettingsNumberInvalid")); value[key] = number; }
if (value.certificate_error_days >= value.certificate_warning_days) throw fieldError($("alerts-certificate-error"), t("alertSettingsCertificateOrder"));
if (value.file_descriptors_error_percent <= value.file_descriptors_warning_percent) throw fieldError($("alerts-fd-error"), t("alertSettingsPercentOrder"));
next.alerts = value;
}, "alerts");
bindSettingsForm("tls-policy-form", next => {
if (!$("tls-policy-12").checked && !$("tls-policy-13").checked) throw fieldError($("tls-policy-12"), t("tlsPolicyVersionRequired"));
if ($("tls-policy-pqc").checked && !$("tls-policy-13").checked) throw fieldError($("tls-policy-13"), t("tlsPqcTls13Required"));
+167
View File
@@ -0,0 +1,167 @@
window.rustProxyTlsConfigurator = (() => {
"use strict";
const FALLBACK = [
"TLS13_AES_256_GCM_SHA384", "TLS13_AES_128_GCM_SHA256", "TLS13_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
];
const CLIENTS = [
{ id: "modern", tls13: true, tls12: () => true },
{ id: "safari_new", tls13: true, tls12: () => true },
{ id: "safari_old", tls13: false, tls12: suite => suite.gcm },
{ id: "android_7", tls13: false, tls12: () => true },
{ id: "android_44", tls13: false, tls12: suite => suite.gcm },
{ id: "java_11", tls13: true, tls12: () => true },
{ id: "java_8", tls13: false, tls12: suite => suite.gcm },
{ id: "openssl_111", tls13: true, tls12: () => true },
{ id: "openssl_102", tls13: false, tls12: suite => suite.gcm },
{ id: "ie11_win10", tls13: false, tls12: suite => suite.gcm },
{ id: "ie11_win7", tls13: false, tls12: suite => suite.gcm && suite.auth === "ECDSA", ecdsa: true },
{ id: "legacy", impossible: true },
];
const PRESETS = {
modern: { tls12: false, tls13: true, suites: [] },
recommended: { tls12: true, tls13: true, suites: [] },
strong: { tls12: true, tls13: true, suites: names => names.filter(name => /AES_256|CHACHA20/.test(name)) },
};
function meta(name) {
const tls13 = name.startsWith("TLS13_");
const auth = tls13 ? "*" : name.includes("_ECDSA_") ? "ECDSA" : name.includes("_RSA_") ? "RSA" : "*";
const cipher = name.includes("CHACHA20") ? "ChaCha20-Poly1305" : name.includes("AES_256_GCM") ? "AES-256-GCM" : name.includes("AES_128_GCM") ? "AES-128-GCM" : name;
const bits = cipher === "AES-128-GCM" ? 128 : 256;
return { name, tls13, auth, cipher, bits, gcm: cipher.includes("GCM"), hash: (name.match(/SHA(\d+)$/) || [])[1] ? `SHA-${name.match(/SHA(\d+)$/)[1]}` : "" };
}
function attach() {
const textarea = $("tls-policy-ciphers"), box12 = $("tls-policy-12"), box13 = $("tls-policy-13"), pqc = $("tls-policy-pqc");
if (!textarea || textarea.dataset.tlsConfigurator) return null;
textarea.dataset.tlsConfigurator = "1";
for (const id of ["tls-policy-effective", "tls-policy-available"]) { const node = $(id); if (node) node.hidden = true; }
const holder = textarea.closest("label"); if (holder) holder.hidden = true; else textarea.hidden = true;
const root = el("div", undefined, "tls-configurator");
(holder || textarea).after(root);
const presets = el("div", undefined, "tls-config-presets");
const presetButtons = Object.keys(PRESETS).map(id => { const button = el("button", t(`tlsPreset${id[0].toUpperCase()}${id.slice(1)}`), "outline"); button.type = "button"; button.dataset.preset = id; button.title = t(`tlsPreset${id[0].toUpperCase()}${id.slice(1)}Help`); return button; });
const custom = el("span", t("tlsPresetCustom"), "pill tls-config-custom");
presets.append(el("span", t("tlsPresets"), "small-label"), ...presetButtons, custom);
const layout = el("div", undefined, "tls-config-layout");
const tableWrap = el("div", undefined, "tls-config-suites"), side = el("div", undefined, "tls-config-side");
layout.append(tableWrap, side);
root.append(presets, layout, el("p", t("tlsConfiguratorHelp"), "fine"));
const available = () => { const list = latestStatus?.tls?.cipher_suites; return Array.isArray(list) && list.length ? list : FALLBACK; };
const selected = () => String(textarea.value || "").split(/[\n,]+/).map(value => value.trim()).filter(Boolean);
const effective = () => { const names = available(), chosen = selected(); return (chosen.length ? chosen : names).filter(name => names.includes(name)); };
const write = suites => {
const names = available(), all = names.every(name => suites.includes(name));
const value = all ? "" : names.filter(name => suites.includes(name)).join("\n");
if (value === textarea.value) return;
textarea.value = value;
textarea.dispatchEvent(new Event("input", { bubbles: true }));
};
function suiteTable() {
const names = available(), active = new Set(effective());
const table = el("table", undefined, "tls-config-table");
const head = el("thead"), headRow = el("tr");
for (const key of ["", "tlsSuite", "tlsSuiteAuth", "tlsSuiteCipher", "tlsSuiteBits", "tlsSuiteRating"]) headRow.append(el("th", key ? t(key) : ""));
head.append(headRow); table.append(head);
const body = el("tbody");
for (const [label, version, enabled] of [["TLS 1.3", true, box13.checked], ["TLS 1.2", false, box12.checked]]) {
const group = el("tr", undefined, "tls-config-group"), cell = el("td"); cell.colSpan = 6;
cell.append(el("strong", label), el("span", enabled ? t("tlsVersionOn") : t("tlsVersionOff"), `pill ${enabled ? "live" : ""}`.trim()));
group.append(cell); body.append(group);
for (const name of names.filter(item => meta(item).tls13 === version)) {
const info = meta(name), row = el("tr"), check = el("input"); check.type = "checkbox"; check.checked = active.has(name); check.disabled = !enabled; check.dataset.suite = name;
check.setAttribute("aria-label", name);
const first = el("td"); first.append(check);
const nameCell = el("td"); nameCell.append(el("code", name));
const rating = info.bits === 256 ? ["tlsRatingStrong", "live"] : ["tlsRatingRecommended", ""];
const ratingCell = el("td"); ratingCell.append(el("span", t(rating[0]), `pill ${rating[1]}`.trim()));
row.classList.toggle("is-off", !enabled || !check.checked);
row.append(first, nameCell, el("td", info.auth === "*" ? t("tlsSuiteAnyCert") : info.auth), el("td", info.cipher), el("td", String(info.bits)), ratingCell);
body.append(row);
}
}
table.append(body);
table.addEventListener("change", event => {
if (!event.target.matches("input[data-suite]")) return;
const chosen = [...table.querySelectorAll("input[data-suite]:checked")].map(input => input.dataset.suite);
const off = [...table.querySelectorAll("input[data-suite]:disabled")].filter(input => active.has(input.dataset.suite)).map(input => input.dataset.suite);
write([...new Set([...chosen, ...off])]);
render();
});
return table;
}
function grade(suites) {
const hsts = envelope?.config?.global_security?.security_headers?.hsts?.enabled === true;
const tls13 = box13.checked && suites.some(name => meta(name).tls13), tls12 = box12.checked && suites.some(name => !meta(name).tls13);
const weakest = Math.min(...suites.filter(name => (meta(name).tls13 ? box13.checked : box12.checked)).map(name => meta(name).bits), 256);
const score = { protocol: tls13 ? (tls12 ? 95 : 100) : 90, exchange: pqc.checked ? 100 : 90, cipher: weakest >= 256 ? 100 : 90 };
const letter = !tls13 && !tls12 ? "-" : tls13 && hsts ? "A+" : "A";
return { letter, score, hsts, tls13, tls12 };
}
function clientState(client, suites) {
if (client.impossible) return "impossible";
const metas = suites.map(meta);
if (client.tls13 && box13.checked && metas.some(item => item.tls13)) return "ok";
if (box12.checked && metas.some(item => !item.tls13 && client.tls12(item))) return client.ecdsa ? "ecdsa" : "ok";
return "fail";
}
function summary() {
const suites = effective(), result = grade(suites);
const card = el("div", undefined, "tls-config-grade");
card.append(el("strong", result.letter, `tls-config-letter ${result.letter === "-" ? "is-bad" : ""}`.trim()));
const bars = el("div", undefined, "tls-config-bars");
for (const [key, value] of [["tlsScoreProtocol", result.score.protocol], ["tlsScoreKeyExchange", result.score.exchange], ["tlsScoreCipher", result.score.cipher]]) {
const bar = el("div", undefined, "tls-config-bar"); const meter = el("i", undefined, "pr-meter"), fill = el("b"); fill.style.width = `${value}%`; meter.append(fill);
bar.append(el("span", t(key)), meter, el("b", String(value))); bars.append(bar);
}
card.append(bars);
const checks = el("ul", undefined, "tls-config-checks");
const item = (ok, key) => { const li = el("li", t(key), ok ? "is-ok" : "is-warn"); li.prepend(el("span", ok ? "✓" : "!", "tls-config-mark")); checks.append(li); };
item(true, "tlsCheckForwardSecrecy"); item(true, "tlsCheckAead"); item(true, "tlsCheckNoLegacy");
item(result.tls13, result.tls13 ? "tlsCheckTls13" : "tlsCheckNoTls13");
item(pqc.checked, pqc.checked ? "tlsCheckPqc" : "tlsCheckNoPqc");
item(result.hsts, result.hsts ? "tlsCheckHsts" : "tlsCheckNoHsts");
const compat = el("div", undefined, "tls-config-compat");
compat.append(el("span", t("tlsCompatibility"), "small-label"));
const list = el("ul");
for (const client of CLIENTS) {
const state = clientState(client, suites), li = el("li", undefined, `is-${state}`);
li.append(el("span", { ok: "✓", ecdsa: "!", fail: "✕", impossible: "✕" }[state], "tls-config-mark"), el("span", t(`tlsClient_${client.id}`)));
if (state !== "ok") li.append(el("small", t(`tlsClientState_${state}`), "fine"));
list.append(li);
}
compat.append(list);
return [card, compat, checks, el("p", t("tlsGradeNote"), "fine")];
}
function syncPresetState() {
const chosen = selected(), names = available();
let match = "";
for (const [id, preset] of Object.entries(PRESETS)) {
const suites = typeof preset.suites === "function" ? preset.suites(names) : preset.suites;
const sameSuites = suites.length ? suites.length === chosen.length && suites.every(name => chosen.includes(name)) : !chosen.length;
if (sameSuites && preset.tls12 === box12.checked && preset.tls13 === box13.checked) match = id;
}
for (const button of presetButtons) { const on = button.dataset.preset === match; button.classList.toggle("primary", on); button.classList.toggle("outline", !on); button.setAttribute("aria-pressed", String(on)); }
custom.hidden = !!match;
}
function render() {
tableWrap.replaceChildren(suiteTable());
side.replaceChildren(...summary());
syncPresetState();
}
for (const button of presetButtons) button.addEventListener("click", () => {
const preset = PRESETS[button.dataset.preset], names = available();
box12.checked = preset.tls12; box13.checked = preset.tls13;
if (!preset.tls13) pqc.checked = false;
const suites = typeof preset.suites === "function" ? preset.suites(names) : preset.suites;
textarea.value = suites.length ? suites.join("\n") : "";
textarea.dispatchEvent(new Event("input", { bubbles: true }));
render();
});
for (const box of [box12, box13, pqc]) box.addEventListener("change", render);
render();
return { refresh: render };
}
let instance = null;
return { refresh() { if (!instance) instance = attach(); else instance.refresh(); }, meta };
})();
+1 -1
View File
@@ -415,7 +415,7 @@ function locationsEditor(parent, values) {
locationProfile.value = value.acl_profile_id || "";
const locationMethods = subsection(accessBody, "vhTrafficMethodsSection");
field(locationMethods, "location-method-mode", "locationMethodMode", value.method_policy?.mode || "off", "select", { values: [["off", "vhOff"], ["allow", "locationMethodAllow"], ["block", "locationMethodBlock"]] });
field(locationMethods, "location-method-list", "locationMethodList", (value.method_policy?.methods || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 });
window.rustProxyMethodPicker?.attach(field(locationMethods, "location-method-list", "locationMethodList", (value.method_policy?.methods || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 }));
note(locationMethods, "locationMethodHelp");
const locationCountries = subsection(accessBody, "vhTrafficCountrySection");
field(locationCountries, "location-country-mode", "locationCountryMode", value.country_access?.mode || "off", "select", { values: [["off", "vhOff"], ["block", "vhCountryBlock"], ["allow", "vhCountryAllow"]] });
+1 -1
View File
@@ -291,7 +291,7 @@ function load(value = defaults(), migrationIds = [], show = true) {
const methodFields = subsection(g, "vhTrafficMethodsSection");
field(methodFields, "method-mode", "vhMethodMode", methodPolicy.mode || "off", "select", { values: [["off", "vhOff"], ["allow", "locationMethodAllow"], ["block", "locationMethodBlock"]] });
field(methodFields, "method-list", "vhMethodList", (methodPolicy.methods || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 });
window.rustProxyMethodPicker?.attach(field(methodFields, "method-list", "vhMethodList", (methodPolicy.methods || []).join("\n"), "textarea", { rows: 3, maxLength: 1024 }));
note(methodFields, "vhMethodHelp");
const mimePolicy = value.content_type_policy || {};
+63
View File
@@ -0,0 +1,63 @@
use anyhow::{ensure, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Settings {
pub enabled: bool,
pub notifications: bool,
pub certificate_expiry: bool,
pub certificate_warning_days: u32,
pub certificate_error_days: u32,
pub certificate_renewal: bool,
pub acme_runtime: bool,
pub file_descriptors: bool,
pub file_descriptors_warning_percent: u8,
pub file_descriptors_error_percent: u8,
pub geoip: bool,
pub prometheus: bool,
pub update: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
enabled: true,
notifications: true,
certificate_expiry: true,
certificate_warning_days: 14,
certificate_error_days: 3,
certificate_renewal: true,
acme_runtime: true,
file_descriptors: true,
file_descriptors_warning_percent: 80,
file_descriptors_error_percent: 95,
geoip: true,
prometheus: true,
update: true,
}
}
}
impl Settings {
pub fn is_default(&self) -> bool {
self == &Self::default()
}
pub fn validate(&self) -> Result<()> {
ensure!(
(1..=90).contains(&self.certificate_warning_days),
"certificate warning must be 1..=90 days"
);
ensure!(
self.certificate_error_days < self.certificate_warning_days,
"certificate error days must be lower than the warning days"
);
ensure!(
(50..=99).contains(&self.file_descriptors_warning_percent)
&& (50..=100).contains(&self.file_descriptors_error_percent)
&& self.file_descriptors_warning_percent < self.file_descriptors_error_percent,
"file descriptor thresholds must be 50..=100 percent and warning below error"
);
Ok(())
}
}
+25 -2
View File
@@ -154,6 +154,10 @@ pub enum RuleAction {
RemoveHeader {
name: String,
},
DefaultHeader {
name: String,
value: String,
},
}
impl RuleAction {
@@ -169,7 +173,9 @@ impl RuleAction {
| Self::NoStore
| Self::IgnoreCacheControl
| Self::StripSetCookie => RuleStage::Response,
Self::SetHeader { .. } | Self::RemoveHeader { .. } => RuleStage::Deliver,
Self::SetHeader { .. } | Self::RemoveHeader { .. } | Self::DefaultHeader { .. } => {
RuleStage::Deliver
}
}
}
fn aspect(&self) -> Option<&'static str> {
@@ -537,7 +543,7 @@ fn validate_action(action: &RuleAction) -> Result<()> {
"TTL and grace are limited to one year"
)
}
RuleAction::SetHeader { name, value } => {
RuleAction::SetHeader { name, value } | RuleAction::DefaultHeader { name, value } => {
let header = rule_header_name(name)?;
ensure!(
!PROTECTED_RULE_HEADERS.contains(&header.as_str()),
@@ -681,6 +687,9 @@ impl CompiledRules {
pub fn is_empty(&self) -> bool {
self.request.is_empty() && self.response.is_empty() && self.deliver.is_empty()
}
pub fn has_deliver_rules(&self) -> bool {
!self.deliver.is_empty()
}
pub fn has_late_rules(&self) -> bool {
!self.response.is_empty() || !self.deliver.is_empty()
}
@@ -896,6 +905,7 @@ pub struct ResponseRuleOutcome {
#[derive(Debug, Clone, Default, Serialize)]
pub struct DeliverRuleOutcome {
pub set: Vec<(String, String)>,
pub defaults: Vec<(String, String)>,
pub remove: Vec<String>,
pub matched: Vec<RuleMatchInfo>,
}
@@ -1065,6 +1075,9 @@ impl CompiledRules {
RuleAction::RemoveHeader { name } => {
outcome.remove.push(name.to_ascii_lowercase())
}
RuleAction::DefaultHeader { name, value } => outcome
.defaults
.push((name.to_ascii_lowercase(), value.clone())),
_ => {}
}
}
@@ -1146,6 +1159,16 @@ impl DeliverRuleOutcome {
headers.insert(header, value);
}
}
for (name, value) in &self.defaults {
if let (Ok(header), Ok(value)) = (
http::HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
if !headers.contains_key(&header) {
headers.insert(header, value);
}
}
}
}
}
+16
View File
@@ -195,6 +195,22 @@ mod cache_rules_tests {
assert!(headers.get("server").is_none());
}
#[test]
fn default_header_only_fills_missing_headers() {
let rules = vec![rule(
serde_json::json!({"id": "defaults", "stage": "deliver", "actions": [{"type": "default_header", "name": "Cache-Control", "value": "public, max-age=60"}, {"type": "default_header", "name": "X-Content-Type-Options", "value": "nosniff"}]}),
)];
let compiled = CompiledRules::compile("", &[], &rules, false).unwrap();
assert!(compiled.has_deliver_rules());
let mut headers = HeaderMap::new();
headers.insert("cache-control", HeaderValue::from_static("no-store"));
let outcome =
compiled.evaluate_deliver(&request("/", None, &[]), StatusCode::OK, &headers, false);
outcome.apply(&mut headers);
assert_eq!(headers.get("cache-control").unwrap(), "no-store");
assert_eq!(headers.get("x-content-type-options").unwrap(), "nosniff");
}
#[test]
fn rule_variant_changes_the_cache_key_only_when_present() {
let cache = Cache::new(1);
+1
View File
@@ -28,6 +28,7 @@ pub fn compile_with_active(
config.listeners.validate(&desired_policy)?;
config.http2.validate()?;
config.docker_agents.validate(&config.listeners)?;
config.alerts.validate()?;
let certificate_ids: HashSet<_> = config
.tls
.certificates
+2
View File
@@ -40,6 +40,8 @@ pub struct Config {
pub http2: crate::settings::Http2Connections,
#[serde(default)]
pub docker_agents: crate::docker::Settings,
#[serde(default, skip_serializing_if = "crate::alerts::Settings::is_default")]
pub alerts: crate::alerts::Settings,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub streams: Vec<crate::stream::Host>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
+15
View File
@@ -37,6 +37,9 @@ const MAX_BINDINGS: usize = 32;
const MAX_DOMAINS: usize = 16;
const MAX_CERTIFICATES: usize = 32;
fn is_true(value: &bool) -> bool {
*value
}
fn yes() -> bool {
true
}
@@ -174,10 +177,18 @@ pub struct Assignment {
pub compression_zstd: Option<bool>,
pub compression_deflate: Option<bool>,
pub cache_enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_default_ttl_seconds: Option<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cache_rules: Vec<crate::cache::Rule>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cache_ignore_global_rules: bool,
pub transform_enabled: bool,
pub acl_profile_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub acl_profile_ids: Vec<String>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub inherit_acl_profiles: bool,
pub allow_certificate_mismatch: bool,
pub acl: Option<crate::acl::Acl>,
pub proxy_timeouts: crate::vhost::ProxyTimeouts,
@@ -205,9 +216,13 @@ impl Default for Assignment {
compression_zstd: None,
compression_deflate: None,
cache_enabled: false,
cache_default_ttl_seconds: None,
cache_rules: Vec::new(),
cache_ignore_global_rules: false,
transform_enabled: false,
acl_profile_id: None,
acl_profile_ids: Vec::new(),
inherit_acl_profiles: true,
allow_certificate_mismatch: false,
acl: None,
proxy_timeouts: crate::vhost::ProxyTimeouts::default(),
+10 -2
View File
@@ -356,10 +356,13 @@ fn build_vhost(
.unwrap_or_default();
let override_profiles =
assignment.acl_profile_id.is_some() || !assignment.acl_profile_ids.is_empty();
let no_profiles = Vec::new();
let (acl_profile_id, acl_profile_ids) = if override_profiles {
(&assignment.acl_profile_id, &assignment.acl_profile_ids)
} else {
} else if assignment.inherit_acl_profiles {
(&agent.acl_profile_id, &agent.acl_profile_ids)
} else {
(&None, &no_profiles)
};
let value = serde_json::json!({
"id": generated_id(&agent.id, &assignment.service_key),
@@ -371,7 +374,12 @@ fn build_vhost(
"http3_enabled": assignment.http3_enabled,
"backends": backends,
"compression": {"enabled": assignment.compression_enabled},
"cache": {"enabled": assignment.cache_enabled},
"cache": {
"enabled": assignment.cache_enabled,
"default_ttl_seconds": assignment.cache_default_ttl_seconds,
"rules": &assignment.cache_rules,
"ignore_global_rules": assignment.cache_ignore_global_rules
},
"transform": {"enabled": assignment.transform_enabled},
"acl_profile_id": acl_profile_id,
"acl_profile_ids": acl_profile_ids,
+37
View File
@@ -104,6 +104,43 @@ mod tests {
assert_eq!(other.acl_profile_id.as_deref(), Some("office"));
}
#[test]
fn public_docker_publication_skips_agent_default_acl_profiles() {
let mut desired = crate::config::demo_config("127.0.0.1:9000".parse().unwrap());
desired.vhosts.clear();
desired.docker_agents.agents.push(Agent {
id: "node1".into(),
name: "Node 1".into(),
endpoint: "http://10.0.0.2:9876".into(),
token: "012345678901234567890123".into(),
base_domain: "docker1.lab.local".into(),
listener_ids: vec!["http".into()],
acl_profile_id: Some("office".into()),
assignments: vec![
Assignment {
service_key: "container:app:8080/tcp".into(),
hostname: "app".into(),
inherit_acl_profiles: false,
..Default::default()
},
Assignment {
service_key: "container:second:8080/tcp".into(),
hostname: "second".into(),
..Default::default()
},
],
..Default::default()
});
let serialized =
serde_json::to_value(&desired.docker_agents.agents[0].assignments).unwrap();
assert_eq!(serialized[0]["inherit_acl_profiles"], false);
assert!(serialized[1].get("inherit_acl_profiles").is_none());
let result = effective_config(desired, &observation(service(), vec![])).unwrap();
let public = &result.vhosts[0];
assert!(public.acl_profile_id.is_none() && public.acl_profile_ids.is_empty());
assert_eq!(result.vhosts[1].acl_profile_id.as_deref(), Some("office"));
}
#[test]
fn generated_vhost_supports_base_domain_custom_domain_aliases_and_selected_ip() {
let mut desired = crate::config::demo_config("127.0.0.1:9000".parse().unwrap());
+1
View File
@@ -4,6 +4,7 @@
pub mod acl;
pub mod acme;
pub mod admin;
pub mod alerts;
#[path = "auth/mod.rs"]
pub mod auth;
pub mod backup;
+19
View File
@@ -127,6 +127,25 @@ let mut cache_rule_context: Option<Arc<crate::cache::RuleContext>> = None;
let mut cache_rule_query: Option<Option<String>> = None;
let mut cache_rule_variant = String::new();
let mut cache_rule_pass = false;
if !admin_control_plane && !cache_settings.active_for(route.cache) {
if let Some(rules) = cache_settings
.compiled_rules
.clone()
.filter(|rules| rules.has_deliver_rules())
{
let rule_request = crate::cache::RuleRequest {
host: host.clone(),
path: path.to_string(),
query: request.uri().query().map(str::to_owned),
method: request.method().clone(),
headers: request.headers().clone(),
client_ip: Some(context.client_ip),
};
if let Some(sink) = request.extensions().get::<crate::cache::RuleSink>() {
sink.set(Arc::new(crate::cache::RuleContext { rules, request: rule_request }));
}
}
}
if !admin_control_plane && cache_settings.active_for(route.cache) {
if let Some(rules) = cache_settings.compiled_rules.clone() {
let mut rule_request = crate::cache::RuleRequest {