v0.37.1
This commit is contained in:
1 parent
78dbb31487
commit
f48843e934
83 files changed
+7304
-1203
No files matched your search
@@ -0,0 +1,251 @@
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CacheRuleTestRequest {
|
||||
#[serde(default = "cache_rule_test_method")]
|
||||
method: String,
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
headers: Vec<(String, String)>,
|
||||
#[serde(default)]
|
||||
client_ip: Option<String>,
|
||||
}
|
||||
|
||||
fn cache_rule_test_method() -> String {
|
||||
"GET".into()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CacheRuleTestResponse {
|
||||
status: u16,
|
||||
#[serde(default)]
|
||||
headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CacheRuleTestInput {
|
||||
#[serde(default)]
|
||||
vhost_id: Option<String>,
|
||||
#[serde(default)]
|
||||
global_rules: Option<Vec<crate::cache::Rule>>,
|
||||
#[serde(default)]
|
||||
vhost_rules: Option<Vec<crate::cache::Rule>>,
|
||||
#[serde(default)]
|
||||
ignore_global_rules: Option<bool>,
|
||||
request: CacheRuleTestRequest,
|
||||
#[serde(default)]
|
||||
response: Option<CacheRuleTestResponse>,
|
||||
}
|
||||
|
||||
fn cache_rule_headers(pairs: &[(String, String)]) -> Result<http::HeaderMap, ApiError> {
|
||||
if pairs.len() > 64 {
|
||||
return Err(ApiError(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"at most 64 test headers".into(),
|
||||
));
|
||||
}
|
||||
let mut headers = http::HeaderMap::new();
|
||||
for (name, value) in pairs {
|
||||
let name = http::HeaderName::from_bytes(name.trim().as_bytes()).map_err(|_| {
|
||||
ApiError(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
format!("invalid header name {name:?}"),
|
||||
)
|
||||
})?;
|
||||
let value = http::HeaderValue::from_str(value.trim()).map_err(|_| {
|
||||
ApiError(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
format!("invalid value for header {name}"),
|
||||
)
|
||||
})?;
|
||||
headers.append(name, value);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
async fn cache_rules_test(
|
||||
State(state): State<Arc<App>>,
|
||||
Json(input): Json<CacheRuleTestInput>,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let invalid =
|
||||
|error: anyhow::Error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
||||
let snapshot = state.config.load_full();
|
||||
let config = &snapshot.envelope.config;
|
||||
let vhost = match input.vhost_id.as_deref().filter(|id| !id.is_empty()) {
|
||||
Some(id) => Some(
|
||||
config
|
||||
.vhosts
|
||||
.iter()
|
||||
.find(|vhost| vhost.id == id)
|
||||
.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown vhost".into()))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let mut global = config.cache.clone();
|
||||
if let Some(rules) = input.global_rules {
|
||||
global.rules = rules;
|
||||
}
|
||||
crate::cache::validate_rules(&global.rules, true).map_err(invalid)?;
|
||||
let mut overrides = vhost.map(|vhost| vhost.cache.clone()).unwrap_or_default();
|
||||
if let Some(rules) = input.vhost_rules {
|
||||
overrides.rules = rules;
|
||||
}
|
||||
if let Some(ignore) = input.ignore_global_rules {
|
||||
overrides.ignore_global_rules = ignore;
|
||||
}
|
||||
let vhost_id = vhost.map(|vhost| vhost.id.as_str()).unwrap_or("");
|
||||
let settings = overrides.resolve_for(&global, vhost_id).map_err(invalid)?;
|
||||
let rules = settings.compiled_rules.clone().unwrap_or_default();
|
||||
let raw = input.request.url.trim();
|
||||
if raw.is_empty() || raw.len() > 8192 {
|
||||
return Err(ApiError(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"enter a URL or path to test".into(),
|
||||
));
|
||||
}
|
||||
let uri: http::Uri = raw
|
||||
.parse()
|
||||
.map_err(|_| ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid test URL".into()))?;
|
||||
let mut headers = cache_rule_headers(&input.request.headers)?;
|
||||
let host = uri
|
||||
.host()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| {
|
||||
headers
|
||||
.get(http::header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|v| v.split(':').next().unwrap_or(v).to_owned())
|
||||
})
|
||||
.or_else(|| vhost.and_then(|vhost| vhost.frontend.hosts.first().cloned()))
|
||||
.unwrap_or_default();
|
||||
let method =
|
||||
http::Method::from_bytes(input.request.method.trim().to_ascii_uppercase().as_bytes())
|
||||
.map_err(|_| ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid method".into()))?;
|
||||
let client_ip =
|
||||
match input
|
||||
.request
|
||||
.client_ip
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
Some(value) => Some(value.parse().map_err(|_| {
|
||||
ApiError(StatusCode::UNPROCESSABLE_ENTITY, "invalid client IP".into())
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
let path = uri.path().to_owned();
|
||||
let mut request = crate::cache::RuleRequest {
|
||||
host: host.clone(),
|
||||
path: path.clone(),
|
||||
query: uri.query().map(str::to_owned),
|
||||
method: method.clone(),
|
||||
headers: headers.clone(),
|
||||
client_ip,
|
||||
};
|
||||
let request_outcome = rules.evaluate_request(&request, false);
|
||||
request_outcome.rewrite_cookies(&mut headers);
|
||||
let query = match request_outcome.rewrite_query(uri.query()) {
|
||||
Some(rewritten) => rewritten,
|
||||
None => uri.query().map(str::to_owned),
|
||||
};
|
||||
request.headers = headers.clone();
|
||||
request.query = query.clone();
|
||||
let target = match &query {
|
||||
Some(query) => format!("{path}?{query}"),
|
||||
None => path.clone(),
|
||||
};
|
||||
let request_policy = if request_outcome.pass.is_some() {
|
||||
Some("cache_rule")
|
||||
} else if !settings.enabled {
|
||||
Some("cache_disabled")
|
||||
} else {
|
||||
crate::cache::request_policy(&method, &headers, true, &path, query.is_some(), &settings)
|
||||
.bypass_reason()
|
||||
};
|
||||
let mut response_value = Value::Null;
|
||||
let mut deliver_value = Value::Null;
|
||||
if let Some(response) = input.response {
|
||||
let status = StatusCode::from_u16(response.status).map_err(|_| {
|
||||
ApiError(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"invalid response status".into(),
|
||||
)
|
||||
})?;
|
||||
let mut response_headers = cache_rule_headers(&response.headers)?;
|
||||
let outcome = rules.evaluate_response(&request, status, &response_headers, false);
|
||||
if outcome.overrides.strip_set_cookie {
|
||||
response_headers.remove(http::header::SET_COOKIE);
|
||||
}
|
||||
let plan = if request_policy.is_none() {
|
||||
crate::cache::plan_with(
|
||||
status,
|
||||
&response_headers,
|
||||
&settings,
|
||||
std::time::Duration::ZERO,
|
||||
&outcome.overrides,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let store_reason = if request_policy.is_some() {
|
||||
None
|
||||
} else if outcome.overrides.no_store {
|
||||
Some("cache_rule_no_store")
|
||||
} else if plan.is_none() {
|
||||
Some(crate::cache::response_reason(
|
||||
status,
|
||||
&response_headers,
|
||||
&settings,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
response_value = json!({
|
||||
"matched": outcome.matched,
|
||||
"overridden": outcome.overridden,
|
||||
"overrides": outcome.overrides,
|
||||
"stored": plan.is_some(),
|
||||
"ttl": plan.as_ref().map(|plan| plan.ttl()),
|
||||
"grace": plan.as_ref().map(|plan| plan.grace()),
|
||||
"reason": store_reason,
|
||||
});
|
||||
let deliver = rules.evaluate_deliver(&request, status, &response_headers, false);
|
||||
deliver_value =
|
||||
json!({"matched": deliver.matched, "set": deliver.set, "remove": deliver.remove});
|
||||
}
|
||||
Ok(Json(json!({
|
||||
"host": host,
|
||||
"request": {
|
||||
"matched": request_outcome.matched,
|
||||
"overridden": request_outcome.overridden,
|
||||
"pass": request_outcome.pass,
|
||||
"target": target,
|
||||
"cookie": headers.get(http::header::COOKIE).and_then(|v| v.to_str().ok()),
|
||||
"variant": request_outcome.hash,
|
||||
"cacheable": request_policy.is_none(),
|
||||
"reason": request_policy,
|
||||
},
|
||||
"response": response_value,
|
||||
"deliver": deliver_value,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CacheVclImportInput {
|
||||
vcl: String,
|
||||
}
|
||||
|
||||
async fn cache_rules_import_vcl(
|
||||
Json(input): Json<CacheVclImportInput>,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let result = crate::cache::import_vcl(&input.vcl)
|
||||
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()))?;
|
||||
Ok(Json(json!(result)))
|
||||
}
|
||||
|
||||
async fn cache_rules_stats() -> Json<Value> {
|
||||
Json(json!({"hits": crate::cache::rule_hit_counts()}))
|
||||
}
|
||||
@@ -37,4 +37,5 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
|
||||
reader_doc!("docs/API.md", "guides"),
|
||||
reader_doc!("docs/PERFORMANCE.md", "guides"),
|
||||
reader_doc!("docs/TROUBLESHOOTING.md", "guides"),
|
||||
reader_doc!("integrations/opnsense-acme/README.md", "guides"),
|
||||
];
|
||||
@@ -12,6 +12,7 @@ include!("api_tokens.rs");
|
||||
include!("file_logs.rs");
|
||||
include!("file_log_search.rs");
|
||||
include!("operations.rs");
|
||||
include!("cache_rules.rs");
|
||||
include!("certificate_api.rs");
|
||||
include!("certificates.rs");
|
||||
include!("tail.rs");
|
||||
|
||||
+545
-2
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "RustProxy Administration API",
|
||||
"version": "0.37.0",
|
||||
"version": "0.37.1",
|
||||
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
|
||||
},
|
||||
"servers": [
|
||||
@@ -755,6 +755,19 @@
|
||||
"nullable": true,
|
||||
"default": null,
|
||||
"description": "If true, only emit cache diagnostic headers for actual HIT responses, never MISS/BYPASS. null inherits global expose_only_hits. Via is controlled independently."
|
||||
},
|
||||
"rules": {
|
||||
"type": "array",
|
||||
"maxItems": 128,
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CacheRule"
|
||||
},
|
||||
"description": "Vhost cache rules; evaluated before global rules (no vhosts field)."
|
||||
},
|
||||
"ignore_global_rules": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Skip global cache rules for this vhost."
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
@@ -2412,6 +2425,14 @@
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Default true: ignore only client hard-reload no-cache, max-age=0 and Pragma: no-cache on fresh cache lookups. Preserve client no-store, only-if-cached (504 on MISS), min-fresh/max-stale, origin ETag revalidation and zero-TTL stale-if-error storage. A positive default_ttl_seconds explicitly allows public origin no-cache responses to be reused for that fallback TTL, even without validators; zero keeps validator-only revalidation. Surrogate-Control: no-store and all private/no-store/Set-Cookie/Vary restrictions remain active. Eligible positive-TTL entries without an explicit stale-while-revalidate directive get configurable grace (varnish_grace_seconds, default 60s; explicit =0 is honored). False restores strict browser reload. Switching modes invalidates cache; not full Varnish VCL emulation."
|
||||
},
|
||||
"rules": {
|
||||
"type": "array",
|
||||
"maxItems": 128,
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CacheRule"
|
||||
},
|
||||
"description": "Global cache rules (Cache → Rules)."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -3715,7 +3736,7 @@
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Discovery sources, for example interface, route, public_api or override."
|
||||
"description": "Discovery sources, for example interface, route, public_api, override or bridge (container bridge interfaces such as docker0, br-*, podman*, reported since agent 0.37.1)."
|
||||
},
|
||||
"interface": {
|
||||
"type": "string"
|
||||
@@ -8549,6 +8570,192 @@
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"CacheRule": {
|
||||
"type": "object",
|
||||
"description": "Cache rule (since 0.37.1). Request rules run before the cache lookup (vcl_recv/vcl_hash), response rules on a backend response (vcl_backend_response), deliver rules on every response sent to the client (vcl_deliver). Vhost rules run before global rules; for TTL, grace, pass and no_store the first matching rule wins.",
|
||||
"required": [
|
||||
"id",
|
||||
"actions"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"default": true
|
||||
},
|
||||
"stage": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"request",
|
||||
"response",
|
||||
"deliver"
|
||||
],
|
||||
"default": "request"
|
||||
},
|
||||
"match": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"all",
|
||||
"any"
|
||||
],
|
||||
"default": "all"
|
||||
},
|
||||
"conditions": {
|
||||
"type": "array",
|
||||
"maxItems": 16,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"field": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"host",
|
||||
"url",
|
||||
"path",
|
||||
"extension",
|
||||
"method",
|
||||
"query",
|
||||
"header",
|
||||
"cookie",
|
||||
"client_ip",
|
||||
"status",
|
||||
"content_type",
|
||||
"response_header"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"operator": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"equals",
|
||||
"prefix",
|
||||
"suffix",
|
||||
"contains",
|
||||
"glob",
|
||||
"regex",
|
||||
"exists",
|
||||
"cidr"
|
||||
]
|
||||
},
|
||||
"values": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"negate": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 16,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"description": "type: pass, strip_cookies{keep}, strip_query{params,keep_only}, hash_header{name}, hash_cookie{name} (request); ttl{seconds}, grace{seconds}, no_store, ignore_cache_control, strip_set_cookie (response); set_header{name,value}, remove_header{name} (deliver).",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"stop": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"vhosts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Global rules only: limit to these vhost ids (empty = all)."
|
||||
}
|
||||
}
|
||||
},
|
||||
"CacheRuleTestRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"request"
|
||||
],
|
||||
"properties": {
|
||||
"vhost_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"global_rules": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CacheRule"
|
||||
}
|
||||
},
|
||||
"vhost_rules": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CacheRule"
|
||||
}
|
||||
},
|
||||
"ignore_global_rules": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"request": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"method": {
|
||||
"type": "string"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"headers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"client_ip": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "integer"
|
||||
},
|
||||
"headers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"CacheVclImportRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"vcl"
|
||||
],
|
||||
"properties": {
|
||||
"vcl": {
|
||||
"type": "string",
|
||||
"maxLength": 262144
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -15374,6 +15581,342 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/cache/rules/stats": {
|
||||
"get": {
|
||||
"summary": "Cache rule match counters",
|
||||
"tags": [
|
||||
"Cache"
|
||||
],
|
||||
"operationId": "get_api_cache_rules_stats",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Match counters keyed by global:<id> or vhost:<vhost>:<id> since process start",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Authentication required or revoked",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Host, origin or CSRF validation failed",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Bounded worker/session/rate limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Control-plane storage/worker unavailable",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"AdminSession": []
|
||||
},
|
||||
{
|
||||
"GeneralApiBearer": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/cache/rules/test": {
|
||||
"post": {
|
||||
"summary": "Simulate cache rules for a request",
|
||||
"tags": [
|
||||
"Cache"
|
||||
],
|
||||
"operationId": "post_api_cache_rules_test",
|
||||
"description": "Evaluates saved or draft global/vhost cache rules for a test request (and optional backend response) without sending traffic or counting matches. Returns matched rules per stage, overridden rule actions, the rewritten URL, cookies, cache key variants, TTL/grace and the cache decision.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "Origin",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE."
|
||||
},
|
||||
{
|
||||
"name": "X-RustProxy-Request",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"1"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"AdminSession": []
|
||||
},
|
||||
{
|
||||
"GeneralApiBearer": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CacheRuleTestRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Simulation result",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Authentication required or revoked",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Host, origin or CSRF validation failed",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "Request exceeds the endpoint body limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Configuration/input validation failed",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Bounded worker/session/rate limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Control-plane storage/worker unavailable",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/cache/rules/import-vcl": {
|
||||
"post": {
|
||||
"summary": "Convert a VCL subset into cache rules",
|
||||
"tags": [
|
||||
"Cache"
|
||||
],
|
||||
"operationId": "post_api_cache_rules_import_vcl",
|
||||
"description": "Parses vcl_recv/vcl_hash, vcl_backend_response/vcl_fetch and vcl_deliver and converts supported statements into cache rules. Unsupported statements are returned as warnings; nothing is saved.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "Origin",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Exact http://HOST:ADMIN_PORT. Set automatically by same-origin browser POST/PUT/DELETE."
|
||||
},
|
||||
{
|
||||
"name": "X-RustProxy-Request",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"1"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"AdminSession": []
|
||||
},
|
||||
{
|
||||
"GeneralApiBearer": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CacheVclImportRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Imported rules and warnings",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Authentication required or revoked",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Host, origin or CSRF validation failed",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "Request exceeds the endpoint body limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Configuration/input validation failed",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Bounded worker/session/rate limit",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "Control-plane storage/worker unavailable",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": []
|
||||
|
||||
@@ -88,6 +88,7 @@ fn admin_app_javascript() -> &'static str {
|
||||
include_str!("web/drafts.js"),
|
||||
include_str!("web/integrations.js"),
|
||||
include_str!("web/acl-picker.js"),
|
||||
include_str!("web/cache-rules.js"),
|
||||
admin_vhosts_javascript(),
|
||||
include_str!("web/web-server-profiles.js"),
|
||||
include_str!("web/web-server.js"),
|
||||
@@ -100,6 +101,7 @@ fn admin_app_javascript() -> &'static str {
|
||||
include_str!("web/transform-panel.js"),
|
||||
include_str!("web/acme.js"),
|
||||
include_str!("web/settings.js"),
|
||||
include_str!("web/system-info.js"),
|
||||
include_str!("web/certificate-api.js"),
|
||||
include_str!("web/api-tokens.js"),
|
||||
include_str!("web/prometheus-token.js"),
|
||||
@@ -249,6 +251,15 @@ pub fn router(state: Arc<App>) -> Router {
|
||||
post(cache_invalidate).layer(DefaultBodyLimit::max(16 * 1024)),
|
||||
)
|
||||
.route("/api/cache/bans", get(cache_bans))
|
||||
.route("/api/cache/rules/stats", get(cache_rules_stats))
|
||||
.route(
|
||||
"/api/cache/rules/test",
|
||||
post(cache_rules_test).layer(DefaultBodyLimit::max(256 * 1024)),
|
||||
)
|
||||
.route(
|
||||
"/api/cache/rules/import-vcl",
|
||||
post(cache_rules_import_vcl).layer(DefaultBodyLimit::max(300 * 1024)),
|
||||
)
|
||||
.route("/api/cache/bans/{id}", delete(cache_ban_delete))
|
||||
.route("/api/tunnels", get(active_tunnels))
|
||||
.route(
|
||||
|
||||
@@ -135,7 +135,7 @@ window.rustProxyChoicePicker = (() => {
|
||||
remove.addEventListener("click", () => { const box = checks.get(id); box.checked = false; box.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
tag.append(text);
|
||||
if (index > 0 && options.markFirst && options.makeFirst) {
|
||||
const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`);
|
||||
const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.dataset.uiIconName = "none"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`);
|
||||
promote.addEventListener("click", () => { order.splice(order.indexOf(id), 1); order.unshift(id); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
tag.append(promote);
|
||||
}
|
||||
@@ -170,3 +170,73 @@ window.rustProxyChoicePicker = (() => {
|
||||
}
|
||||
return { create, read: root => root?.read?.() || [] };
|
||||
})();
|
||||
|
||||
window.rustProxyChipInput = (() => {
|
||||
const CIDR = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}(?:\/(?:3[0-2]|[12]?\d))?|[0-9a-fA-F:]*:[0-9a-fA-F:.]*(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?)$/;
|
||||
function create(options = {}) {
|
||||
const box = el("div", undefined, `host-chip-editor ${options.className || ""}`.trim()), input = document.createElement("input");
|
||||
input.type = "text"; input.maxLength = options.maxLength || 128; input.placeholder = options.placeholder || ""; input.spellcheck = false;
|
||||
if (options.label) input.setAttribute("aria-label", options.label);
|
||||
const values = [], limit = options.limit || 64;
|
||||
const changed = () => box.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
const normalize = raw => { const value = String(raw || "").trim(); if (!value) return null; if (options.validate) { const result = options.validate(value); if (result === false) throw fieldError(input, options.invalidMessage || t("invalidValue")); if (typeof result === "string") return result; } return value; };
|
||||
const sync = () => {
|
||||
box.querySelectorAll(".host-chip").forEach(node => node.remove());
|
||||
for (const value of values) {
|
||||
const chip = el("span", undefined, "host-chip"); chip.append(el("span", value));
|
||||
const remove = el("button", "×"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${value}`);
|
||||
remove.addEventListener("click", () => { values.splice(values.indexOf(value), 1); sync(); changed(); });
|
||||
chip.append(remove); box.insertBefore(chip, input);
|
||||
}
|
||||
};
|
||||
const add = (raw, notify = true) => { const value = normalize(raw); if (!value || values.includes(value)) return; if (values.length >= limit) throw fieldError(input, options.limitMessage || t("aclPickerLimit")); values.push(value); sync(); if (notify) changed(); };
|
||||
const consume = raw => { for (const part of String(raw).split(/[\s,;]+/).filter(Boolean)) add(part); input.value = ""; };
|
||||
const guarded = raw => { try { consume(raw); } catch (error) { toast(error.message, true); } };
|
||||
input.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === ",") { event.preventDefault(); guarded(input.value); } });
|
||||
input.addEventListener("blur", () => { if (input.value.trim()) guarded(input.value); });
|
||||
input.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,;]/.test(value.trim())) return; event.preventDefault(); guarded(value); });
|
||||
box.append(input);
|
||||
for (const value of options.values || []) { try { add(value, false); } catch { } }
|
||||
box.read = () => { if (input.value.trim()) consume(input.value); return [...values]; };
|
||||
box.set = list => { values.length = 0; for (const value of list || []) { try { add(value, false); } catch { } } sync(); };
|
||||
box.input = input;
|
||||
return box;
|
||||
}
|
||||
const validCidr = value => CIDR.test(value);
|
||||
return { create, validCidr };
|
||||
})();
|
||||
|
||||
window.rustProxyCountryPicker = (() => {
|
||||
const CODES = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW".split(" ");
|
||||
const nameOf = code => { try { return new Intl.DisplayNames([document.documentElement.lang || "en"], { type: "region" }).of(code) || code; } catch { return code; } };
|
||||
const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
|
||||
function attach(textarea, options = {}) {
|
||||
if (!textarea || textarea.dataset.countryPicker) return null;
|
||||
textarea.dataset.countryPicker = "1"; textarea.hidden = true;
|
||||
const host = el("div", undefined, "country-picker-host"); textarea.after(host);
|
||||
let picker = null, writing = false;
|
||||
const build = () => {
|
||||
const items = CODES.map(code => ({ id: code, title: `${code} · ${nameOf(code)}`, search: nameOf(code) }));
|
||||
picker = window.rustProxyChoicePicker.create({
|
||||
className: "country-picker", selected: parse(textarea.value), items, limit: options.limit || 250,
|
||||
labels: { choose: "countryPickerChoose", selected: "countryPickerSelected", none: "countryPickerNone", search: "countryPickerSearch", addHint: "countryPickerAddHint", empty: "countryPickerEmpty" },
|
||||
custom: raw => {
|
||||
const text = String(raw || "").trim(); if (!text) return null;
|
||||
const code = text.toUpperCase();
|
||||
if (/^[A-Z]{2}$/.test(code)) return { id: code, title: `${code} · ${nameOf(code)}` };
|
||||
const query = text.toLocaleLowerCase(), matches = CODES.filter(item => nameOf(item).toLocaleLowerCase().includes(query));
|
||||
const exact = matches.find(item => nameOf(item).toLocaleLowerCase() === query) || (matches.length === 1 ? matches[0] : null);
|
||||
return exact ? { id: exact, title: `${exact} · ${nameOf(exact)}` } : null;
|
||||
},
|
||||
});
|
||||
picker.addEventListener("choicechange", event => { if (writing) return; const value = (event.detail || []).join("\n"); if (value === textarea.value) return; textarea.value = value; textarea.dispatchEvent(new Event("input", { bubbles: true })); });
|
||||
host.replaceChildren(picker);
|
||||
picker.setDisabled(textarea.disabled);
|
||||
};
|
||||
const refresh = () => { writing = true; try { build(); } finally { writing = false; } };
|
||||
refresh();
|
||||
new MutationObserver(() => picker?.setDisabled(textarea.disabled)).observe(textarea, { attributes: true, attributeFilter: ["disabled"] });
|
||||
return { refresh, host };
|
||||
}
|
||||
return { attach, codes: CODES, nameOf };
|
||||
})();
|
||||
+69
-32
@@ -1,47 +1,84 @@
|
||||
"use strict";
|
||||
window.rustProxyApiTokens = (() => {
|
||||
let loading = false;
|
||||
let loading = false, state = null, cidrs = null;
|
||||
const hideSecret = () => { $("api-token-secret").textContent = ""; $("api-token-secret-wrap").hidden = true; };
|
||||
const normalizeCidr = value => {
|
||||
if (!window.rustProxyChipInput.validCidr(value)) return false;
|
||||
if (value.includes("/")) return value;
|
||||
return value.includes(":") ? `${value}/128` : `${value}/32`;
|
||||
};
|
||||
function closeEditor() { $("api-tokens-form").hidden = true; $("api-token-new").disabled = false; }
|
||||
function openEditor() {
|
||||
hideSecret();
|
||||
$("api-token-comment").value = "";
|
||||
$("api-token-permission-ro").checked = true;
|
||||
cidrs = window.rustProxyChipInput.create({ className: "api-token-cidr-editor", placeholder: "192.0.2.10 / 10.0.0.0/24 / 2001:db8::/64", label: t("apiTokenIpAllow"), limit: 32, validate: normalizeCidr, invalidMessage: t("apiTokenCidrInvalid"), limitMessage: t("apiTokenCidrLimit") });
|
||||
$("api-token-cidrs").replaceChildren(cidrs);
|
||||
$("api-tokens-form").hidden = false;
|
||||
$("api-token-new").disabled = true;
|
||||
$("api-token-comment").focus?.();
|
||||
}
|
||||
function example(id) {
|
||||
$("api-token-example").textContent = `curl -H "Authorization: Bearer $RUSTPROXY_API_TOKEN" ${location.origin}/api/status`;
|
||||
if (id) $("api-token-example").textContent += `\n\n# ${id}`;
|
||||
}
|
||||
function render() {
|
||||
const list = $("api-token-list"); list.replaceChildren();
|
||||
const tokens = state?.tokens || [], max = Number(state?.max_tokens) || 0;
|
||||
$("api-token-status").textContent = tokens.length ? t("apiTokenCount").replace("{count}", tokens.length).replace("{max}", max || "-") : t("apiTokenEmpty");
|
||||
$("api-token-new").disabled = !$("api-tokens-form").hidden || (max && tokens.length >= max);
|
||||
for (const entry of tokens) {
|
||||
const item = el("div", undefined, "certificate-api-credential-item"), row = el("div", undefined, "certificate-api-credential-row"), info = el("div", undefined, "certificate-api-credential-info");
|
||||
const title = el("div", undefined, "certificate-api-credential-title");
|
||||
title.append(el("b", entry.id, "mono"), el("span", entry.permission === "rw" ? "RW" : "RO", `pill ${entry.permission === "rw" ? "warn" : "live"}`));
|
||||
if (entry.comment) title.append(el("span", entry.comment, "fine"));
|
||||
const chips = el("div", undefined, "certificate-api-chips");
|
||||
for (const cidr of entry.allowed_cidrs || []) chips.append(el("span", cidr, "certificate-api-chip"));
|
||||
const created = entry.created_at ? formatDateTime(entry.created_at * 1000) : "-", used = entry.last_used_at ? formatDateTime(entry.last_used_at * 1000) : t("certificateApiNeverUsed");
|
||||
info.append(title, chips, el("span", `${t("certificateApiCreatedAt")}: ${created} · ${t("certificateApiLastUsed")}: ${used}`, "fine"));
|
||||
const actions = el("div", undefined, "certificate-api-row-actions");
|
||||
const revoke = action(t("apiTokenRevoke"), async () => {
|
||||
if (!(await appConfirm(t("apiTokenRevokeConfirm").replace("{id}", entry.id), { danger: true }))) return;
|
||||
revoke.disabled = true;
|
||||
try { await api(`/api/api-tokens/${encodeURIComponent(entry.id)}`, { method: "DELETE" }); hideSecret(); await refresh(true); toast(t("apiTokenRevoked")); }
|
||||
catch (error) { toast(error.message, true); revoke.disabled = false; }
|
||||
});
|
||||
revoke.classList.add("danger"); actions.append(revoke);
|
||||
row.append(info, actions); item.append(row); list.append(item);
|
||||
}
|
||||
example();
|
||||
}
|
||||
async function refresh() {
|
||||
if (!authenticated || loading) return;
|
||||
loading = true;
|
||||
try {
|
||||
const result = await api("/api/api-tokens");
|
||||
const list = $("api-token-list"); list.replaceChildren();
|
||||
for (const entry of result.tokens || []) {
|
||||
const card = el("div", undefined, "entity");
|
||||
card.append(el("span", `${entry.id} · ${entry.permission.toUpperCase()} · ${entry.comment || "-"}`, "entity-title"));
|
||||
card.append(el("p", `${t("apiTokenIpAllow")}: ${(entry.allowed_cidrs || []).join(", ")}`, "fine"));
|
||||
card.append(el("p", `${t("apiTokenLastUsed")}: ${entry.last_used_at ? formatDateTime(entry.last_used_at * 1000) : "-"}`, "fine"));
|
||||
card.append(action(t("apiTokenRevoke"), async () => {
|
||||
if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return;
|
||||
try { await api(`/api/api-tokens/${encodeURIComponent(entry.id)}`, { method: "DELETE" }); hideSecret(); await refresh(); }
|
||||
catch (error) { toast(error.message, true); }
|
||||
}));
|
||||
list.append(card);
|
||||
}
|
||||
if (!result.tokens?.length) list.append(el("p", t("apiTokenEmpty"), "fine"));
|
||||
} catch (error) { if (error.status !== 401) toast(error.message, true); }
|
||||
try { state = await api("/api/api-tokens"); render(); }
|
||||
catch (error) { if (error.status !== 401) toast(error.message, true); }
|
||||
finally { loading = false; }
|
||||
}
|
||||
$("api-token-new").addEventListener("click", openEditor);
|
||||
$("api-token-cancel").addEventListener("click", () => { closeEditor(); render(); });
|
||||
$("api-token-secret-copy").addEventListener("click", async () => {
|
||||
try { await navigator.clipboard.writeText($("api-token-secret").textContent); toast(t("copied")); }
|
||||
catch { const range = document.createRange(); range.selectNodeContents($("api-token-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
|
||||
});
|
||||
$("api-tokens-form").addEventListener("submit", async event => {
|
||||
event.preventDefault(); if (!authenticated) return;
|
||||
const button = event.submitter; button.disabled = true;
|
||||
const button = event.submitter; if (button) button.disabled = true;
|
||||
hideSecret();
|
||||
try {
|
||||
const result = await api("/api/api-tokens", {
|
||||
method: "POST", body: JSON.stringify({
|
||||
permission: $("api-token-permission").value,
|
||||
comment: $("api-token-comment").value.trim(),
|
||||
allowed_cidrs: $("api-token-cidrs").value.split(/[\n,]+/).map(s => s.trim()).filter(Boolean)
|
||||
})
|
||||
});
|
||||
$("api-token-secret").textContent = result.token;
|
||||
$("api-token-secret-wrap").hidden = false;
|
||||
$("api-token-comment").value = "";
|
||||
const allowed = cidrs?.read() || [];
|
||||
if (!allowed.length) throw fieldError(cidrs, t("apiTokenCidrRequired"));
|
||||
const permission = $("api-token-permission-rw").checked ? "rw" : "ro";
|
||||
const result = await api("/api/api-tokens", { method: "POST", body: JSON.stringify({ permission, comment: $("api-token-comment").value.trim(), allowed_cidrs: allowed }) });
|
||||
closeEditor();
|
||||
await refresh();
|
||||
} catch (error) { toast(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
$("api-token-secret").textContent = result.token;
|
||||
$("api-token-secret-title").textContent = t("apiTokenSecretTitle").replace("{id}", result.id);
|
||||
$("api-token-secret-wrap").hidden = false;
|
||||
toast(t("apiTokenCreated"));
|
||||
} catch (error) { showFieldError(error, $("api-tokens-form")); toast(error.message, true); }
|
||||
finally { if (button) button.disabled = false; }
|
||||
});
|
||||
return { refresh, hideSecret, reset() { hideSecret(); $("api-token-list").replaceChildren(); } };
|
||||
example();
|
||||
return { refresh, hideSecret, reset() { state = null; hideSecret(); closeEditor(); $("api-token-list").replaceChildren(); } };
|
||||
})();
|
||||
@@ -165,7 +165,7 @@ function setPanel(name, navigate = true) {
|
||||
for (const id of ["overview-layout-open", "overview-layout-unlock"]) if ($(id)) $(id).hidden = name !== "overview" || (id === "overview-layout-unlock" && !!window.rustProxyInlineLayout?.isEditing?.());
|
||||
document.querySelectorAll(".nav").forEach(e => e.classList.toggle("active", e.dataset.panel === name));
|
||||
document.querySelectorAll(".panel").forEach(e => e.hidden = e.id !== `panel-${name}`);
|
||||
$("page-label").textContent = t(name); $("page-title").textContent = t(`${name}Title`); $("page-description").textContent = t(`${name}Description`);
|
||||
$("page-label").textContent = t(name); $("page-title").textContent = t(`${name}Title`); const descriptionKey = `${name}Description`, description = t(descriptionKey); $("page-description").textContent = description === descriptionKey ? "" : description; $("page-description").hidden = description === descriptionKey;
|
||||
if (navigate && typeof location !== "undefined" && ["http:", "https:"].includes(location.protocol) && location.pathname !== PANEL_PATHS[name]) history.pushState({ panel: name }, "", PANEL_PATHS[name]);
|
||||
if (name === "web-server" && latestStatus) window.rustProxyWebServer?.renderLive?.(latestStatus, false);
|
||||
if (name === "settings") window.rustProxySettings?.syncLocation?.();
|
||||
@@ -542,6 +542,8 @@ async function activate(info) {
|
||||
void window.rustProxyApiTokens?.refresh?.();
|
||||
window.rustProxySettings?.scrollToApiTokens?.();
|
||||
}
|
||||
if (window.rustProxySettings?.current?.() === "prometheus") void window.rustProxyPrometheusToken?.refresh?.();
|
||||
if (window.rustProxySettings?.current?.() === "certificate-api") void window.rustProxyCertificateApi?.load?.();
|
||||
void refresh(true).catch(error => {
|
||||
if (authenticated && epoch === authEpoch && error?.status !== 401) toast(error.message, true);
|
||||
});
|
||||
|
||||
@@ -35,17 +35,22 @@ window.rustProxyInlineLayout = (() => {
|
||||
|
||||
function renderHidden() {
|
||||
if (!hiddenList || !draft) return;
|
||||
const entries = draft.order.filter(id => draft.hidden.has(id));
|
||||
const docker = window.rustProxyDockerDashboard;
|
||||
const hiddenLabel = id => docker?.isDocker?.(id) ? dashboardWidgetBaseLabel(id) : label(id);
|
||||
const all = draft.order.filter(id => draft.hidden.has(id)), entries = docker?.collapseHidden?.(all) || all;
|
||||
if (hiddenCount) hiddenCount.textContent = `(${entries.length})`;
|
||||
hiddenList.replaceChildren(...(entries.length ? entries.map(id => {
|
||||
const add = control("+", `${t("overviewLayoutInlineRestore")}: ${label(id)}`, "overview-inline-restore", () => {
|
||||
draft.hidden.delete(id);
|
||||
const picker = docker?.agentPicker?.(id);
|
||||
const add = control("+", `${t("overviewLayoutInlineRestore")}: ${hiddenLabel(id)}`, "overview-inline-restore", async () => {
|
||||
const slot = docker?.slotFor?.(id, draft.hidden) || id;
|
||||
await docker?.addWithScope?.(slot, picker);
|
||||
draft.hidden.delete(slot);
|
||||
paint();
|
||||
nodeFor(id)?.querySelector(".overview-inline-grip")?.focus();
|
||||
nodeFor(slot)?.querySelector(".overview-inline-grip")?.focus();
|
||||
});
|
||||
const item = el("div", undefined, "overview-inline-hidden-item");
|
||||
item.append(el("span", label(id)), dashboardWidgetTypeBadge(id));
|
||||
const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope);
|
||||
item.append(el("span", hiddenLabel(id)), dashboardWidgetTypeBadge(id));
|
||||
if (picker) item.append(picker);
|
||||
item.append(add);
|
||||
return item;
|
||||
}) : [el("span", t("overviewLayoutInlineHiddenEmpty"), "fine")]));
|
||||
|
||||
@@ -183,21 +183,24 @@ window.rustProxyDashboardLayout = (() => {
|
||||
});
|
||||
visibleRoot.replaceChildren(...(tiles.length ? tiles : [el("p", t("overviewLayoutEditorEmpty"), "fine")]));
|
||||
const query = (search?.value || "").trim().toLocaleLowerCase();
|
||||
const hidden = draft.order.filter(id => draft.hidden.has(id)
|
||||
&& (typeFilter?.value === "all" || !typeFilter?.value || dashboardWidgetType(id) === typeFilter.value)
|
||||
&& (`${label(id)} ${dashboardWidgetTypeLabel(id)}`).toLocaleLowerCase().includes(query));
|
||||
const docker = window.rustProxyDockerDashboard;
|
||||
const hiddenLabel = id => docker?.isDocker?.(id) ? dashboardWidgetBaseLabel(id) : label(id);
|
||||
const collapsed = docker?.collapseHidden?.(draft.order.filter(id => draft.hidden.has(id))) || draft.order.filter(id => draft.hidden.has(id));
|
||||
const hidden = collapsed.filter(id => (typeFilter?.value === "all" || !typeFilter?.value || dashboardWidgetType(id) === typeFilter.value)
|
||||
&& (`${hiddenLabel(id)} ${dashboardWidgetTypeLabel(id)}`).toLocaleLowerCase().includes(query));
|
||||
const hiddenItems = hidden.map(id => {
|
||||
const item = el("div", undefined, "overview-layout-hidden-item");
|
||||
item.setAttribute("role", "listitem");
|
||||
const name = el("span", label(id));
|
||||
const name = el("span", hiddenLabel(id));
|
||||
const meta = ADMIN_DASHBOARD_BY_ID.get(id)?.description_key;
|
||||
if (meta) name.title = t(meta);
|
||||
const picker = docker?.agentPicker?.(id);
|
||||
const add = el("button", t("overviewLayoutEditorShow"), "outline");
|
||||
add.type = "button";
|
||||
add.setAttribute("aria-label", `${t("overviewLayoutEditorShow")}: ${label(id)}`);
|
||||
add.addEventListener("click", () => { draft.hidden.delete(id); render(); });
|
||||
add.setAttribute("aria-label", `${t("overviewLayoutEditorShow")}: ${hiddenLabel(id)}`);
|
||||
add.addEventListener("click", async () => { const slot = docker?.slotFor?.(id, draft.hidden) || id; add.disabled = true; try { await docker?.addWithScope?.(slot, picker); } finally { add.disabled = false; } draft.hidden.delete(slot); render(); });
|
||||
item.append(name, dashboardWidgetTypeBadge(id));
|
||||
const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope);
|
||||
if (picker) item.append(picker);
|
||||
item.append(add);
|
||||
return item;
|
||||
});
|
||||
|
||||
@@ -26,12 +26,36 @@ window.rustProxyDockerDashboard = (() => {
|
||||
select.addEventListener("change", () => void setScope(id, select.value));
|
||||
return select;
|
||||
}
|
||||
const isDocker = id => ids.includes(id);
|
||||
function collapseHidden(list) {
|
||||
const seen = new Set();
|
||||
return list.filter(id => { if (!isDocker(id)) return true; const base = baseOf(id); if (seen.has(base)) return false; seen.add(base); return true; });
|
||||
}
|
||||
function slotFor(id, hidden) {
|
||||
if (!isDocker(id)) return id;
|
||||
const base = baseOf(id), set = hidden instanceof Set ? hidden : new Set(hidden || []);
|
||||
return ids.find(item => baseOf(item) === base && set.has(item)) || id;
|
||||
}
|
||||
function agentPicker(id) {
|
||||
if (!isDocker(id)) return null;
|
||||
const agents = configuredAgents(); if (agents.length < 2) return null;
|
||||
const select = el("select", undefined, "docker-widget-scope docker-widget-add-scope"); select.setAttribute("aria-label", t("dockerWidgetScope")); select.title = t("dockerWidgetScope");
|
||||
const all = el("option", t("dockerWidgetScopeAll")); all.value = ""; select.append(all);
|
||||
for (const agent of agents) { const option = el("option", agent.name || agent.id); option.value = agent.id; select.append(option); }
|
||||
return select;
|
||||
}
|
||||
async function addWithScope(id, picker) { if (!isDocker(id)) return; const agent = picker?.value || ""; if (agent !== scopeOf(id)) await setScope(id, agent); }
|
||||
function scopeLabel(id) {
|
||||
if (!isDocker(id)) return "";
|
||||
const agentId = scopeOf(id); if (!agentId) return "";
|
||||
const agent = configuredAgents().find(item => item.id === agentId); return agent ? agent.name || agent.id : "";
|
||||
}
|
||||
const card = id => document.querySelector(`[data-dashboard-widget="${id}"]`);
|
||||
const shown = id => card(id) && !card(id).hidden;
|
||||
function syncCardControls() {
|
||||
for (const id of ids) {
|
||||
const node = card(id); if (!node) continue;
|
||||
const instance = id.match(/_([2-9])$/)?.[1]; if (instance) node.querySelector(":scope > span")?.setAttribute("data-instance", instance);
|
||||
const instance = id.match(/_([2-9])$/)?.[1], title = node.querySelector(":scope > span"); if (instance && !scopeOf(id)) title?.setAttribute("data-instance", instance); else title?.removeAttribute("data-instance");
|
||||
const signature = `${configuredAgents().map(agent => `${agent.id}:${agent.name}`).join("|")}#${scopeOf(id)}`;
|
||||
if (node.dataset.dockerScope === signature) continue;
|
||||
node.dataset.dockerScope = signature;
|
||||
@@ -175,5 +199,5 @@ window.rustProxyDockerDashboard = (() => {
|
||||
const detail = alerts.slice(0, 4).map(alertText).join(" · ") + (alerts.length > 4 ? ` · +${alerts.length - 4}` : "");
|
||||
return { level: alerts.some(alert => alert.severity === "error") ? "error" : "warning", label: t("dockerAlertsHealth"), detail };
|
||||
}
|
||||
return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, alertText, notify, healthCheck, ids };
|
||||
return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, scopeLabel, isDocker, collapseHidden, slotFor, agentPicker, addWithScope, alertText, notify, healthCheck, ids };
|
||||
})();
|
||||
@@ -156,7 +156,7 @@ const UI_I18N_ICONS = Object.freeze({
|
||||
renewalEnable: "toggleOn", renewalDisable: "toggleOff", tunnelKill: "ban", certAssignVhosts: "network",
|
||||
});
|
||||
|
||||
const UI_GLYPH_LABEL = /^[×✕−+←→↑↓⠿]$/;
|
||||
const UI_GLYPH_LABEL = /^[×✕−+←→↑↓⠿★☆]$/;
|
||||
function uiIconForTarget(target) {
|
||||
const manual = target.dataset.uiIconName;
|
||||
if (manual === "none") return null;
|
||||
|
||||
@@ -183,7 +183,13 @@ function applyDashboardLayout(order, hidden, sizes = null, heights = undefined)
|
||||
}
|
||||
function dashboardWidgetLabel(id) {
|
||||
const widget = ADMIN_DASHBOARD_BY_ID.get(id);
|
||||
return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id;
|
||||
if (!widget) return id;
|
||||
const scope = window.rustProxyDockerDashboard?.scopeLabel?.(id);
|
||||
return `${t(widget.label_key)}${scope ? ` · ${scope}` : widget.instance > 1 ? ` #${widget.instance}` : ""}`;
|
||||
}
|
||||
function dashboardWidgetBaseLabel(id) {
|
||||
const widget = ADMIN_DASHBOARD_BY_ID.get(id);
|
||||
return widget ? t(widget.label_key) : id;
|
||||
}
|
||||
const DASHBOARD_DISPLAY_TYPE_KEYS = Object.freeze({
|
||||
value: "overviewBlockTypeValue", value_chart: "overviewBlockTypeValueChart",
|
||||
@@ -207,7 +213,9 @@ function renderDashboardWidgetSettings() {
|
||||
const focusedId = focusedRow && list.contains?.(focusedRow) ? focusedRow.dataset.dashboardWidgetSetting : null;
|
||||
const focusedAction = focusedId ? document.activeElement?.dataset.dashboardWidgetAction : null;
|
||||
const current = adminPreferences || ADMIN_APPEARANCE_DEFAULTS, order = dashboardVisualOrder(current.dashboard_widgets, current.dashboard_widget_sizes), hidden = new Set(normalizeHiddenDashboardWidgets(current.dashboard_hidden_widgets));
|
||||
const docker = window.rustProxyDockerDashboard, representatives = new Set(docker?.collapseHidden?.(order.filter(id => hidden.has(id))) || []);
|
||||
const rows = order.map((id, index) => {
|
||||
if (docker?.isDocker?.(id) && hidden.has(id) && !representatives.has(id)) return null;
|
||||
const row = el("div", undefined, "dashboard-widget-setting"); row.dataset.dashboardWidgetSetting = id;
|
||||
const visible = !hidden.has(id);
|
||||
const toggle = el("button", undefined, "dashboard-widget-toggle"); toggle.type = "button"; toggle.dataset.dashboardWidgetAction = "toggle"; toggle.classList.toggle("is-hidden", !visible); toggle.setAttribute("aria-pressed", String(visible)); toggle.setAttribute("aria-label", `${t("dashboardWidgetVisible")}: ${dashboardWidgetLabel(id)}`);
|
||||
@@ -239,7 +247,7 @@ function renderDashboardWidgetSettings() {
|
||||
};
|
||||
up.addEventListener("click", () => move(-1)); down.addEventListener("click", () => move(1)); actions.append(up, down); row.append(toggle, actions); return row;
|
||||
});
|
||||
list.replaceChildren(...rows);
|
||||
list.replaceChildren(...rows.filter(Boolean));
|
||||
list.scrollLeft = previousScroll;
|
||||
if (focusedId && focusedAction) {
|
||||
const row = [...list.children].find(item => item.dataset.dashboardWidgetSetting === focusedId);
|
||||
|
||||
@@ -245,6 +245,10 @@ function syncSettingsDirtyIndicators() {
|
||||
const dirty = dirtyTabs.has(button.dataset.settingsTab); button.classList.toggle("has-unsaved", dirty);
|
||||
if (dirty) button.title = t("unsavedChanges"); else button.removeAttribute("title");
|
||||
});
|
||||
document.querySelectorAll("[data-settings-page] form[id]").forEach(form => {
|
||||
const bar = [...form.children].filter(node => node.classList?.contains("form-actions")).pop(); if (!bar) return;
|
||||
bar.classList.add("settings-save-bar"); bar.dataset.unsavedLabel = t("unsavedChanges"); bar.classList.toggle("has-unsaved", settingsDirty.has(form.id));
|
||||
});
|
||||
window.rustProxyIntegrations?.syncHttp2Availability?.();
|
||||
window.rustProxyIntegrations?.syncHttp3Availability?.();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
let cacheRulesEditor = null, cacheRulesRendered = "";
|
||||
function renderSettings() {
|
||||
if (!envelope) return; const config = envelope.config; window.rustProxySettings?.render();
|
||||
if (!settingsDirty.has("listeners-form")) window.rustProxyIntegrations?.renderListeners();
|
||||
@@ -11,6 +12,12 @@ function renderSettings() {
|
||||
$("compress-min").value = compression.min_bytes ?? 1024; syncServerMode();
|
||||
}
|
||||
if (!settingsDirty.has("cache-form")) {
|
||||
const rulesJson = JSON.stringify(config.cache?.rules || []);
|
||||
if (window.rustProxyCacheRules && (!cacheRulesEditor || rulesJson !== cacheRulesRendered)) {
|
||||
cacheRulesEditor = window.rustProxyCacheRules.create({ scope: "global", rules: config.cache?.rules || [] });
|
||||
cacheRulesRendered = rulesJson;
|
||||
$("cache-rules-root")?.replaceChildren(cacheRulesEditor.node);
|
||||
}
|
||||
const c = config.cache || {}; $("cache-enabled").checked = !!c.enabled; $("cache-varnish-compatible").checked = c.varnish_compatible !== false; $("cache-varnish-grace").value = c.varnish_grace_seconds ?? 60; $("cache-memory").value = (c.max_bytes ?? 268435456) / 1048576;
|
||||
$("cache-transient-memory").value = (c.transient_max_bytes ?? 67108864) / 1048576;
|
||||
$("cache-object").value = (c.max_object_bytes ?? 16777216) / 1024; $("cache-entries").value = c.max_entries ?? 4096;
|
||||
@@ -82,6 +89,7 @@ function renderSettings() {
|
||||
const ua = global.user_agent_blocking || {}, acl = global.acl;
|
||||
$("global-country-mode").value = country.mode || "off";
|
||||
$("global-country-list").value = (country.countries || []).join("\n");
|
||||
globalCountryPicker()?.refresh();
|
||||
$("global-ua-block-enabled").checked = ua.enabled === true;
|
||||
$("global-ua-block-patterns").value = (ua.patterns || []).join("\n");
|
||||
$("global-ip-enabled").checked = !!acl;
|
||||
@@ -123,8 +131,32 @@ function syncGlobalSecurityControls() {
|
||||
]) {
|
||||
const source = $(toggle);
|
||||
const enabled = source.type === "checkbox" ? source.checked : source.value !== "off";
|
||||
for (const id of children) $(id).disabled = !enabled;
|
||||
for (const id of children) { $(id).disabled = !enabled; const holder = $(id).closest("label, .settings-chip-field, .global-rate-fields"); if (holder && holder.contains(source) === false) holder.hidden = !enabled; }
|
||||
const section = source.closest(".global-policy-section");
|
||||
if (section) {
|
||||
section.classList.toggle("is-off", !enabled);
|
||||
const heading = section.querySelector(".global-policy-heading h3");
|
||||
let pill = heading?.querySelector(".global-policy-state");
|
||||
if (heading && !pill) { pill = el("span", "", "pill global-policy-state"); heading.append(pill); }
|
||||
if (pill) { const mode = source.type === "checkbox" ? "" : source.value; pill.textContent = !enabled ? t("globalPolicyOff") : mode === "block" ? t("globalPolicyBlockMode") : mode === "allow" ? t("globalPolicyAllowMode") : t("globalPolicyOn"); pill.className = `pill global-policy-state ${enabled ? "live" : ""}`.trim(); }
|
||||
}
|
||||
}
|
||||
globalCountryPicker();
|
||||
syncGlobalPolicySummary();
|
||||
}
|
||||
let globalCountryPickerInstance = null;
|
||||
function globalCountryPicker() { if (!globalCountryPickerInstance) globalCountryPickerInstance = window.rustProxyCountryPicker?.attach($("global-country-list")) || null; return globalCountryPickerInstance; }
|
||||
function syncGlobalPolicySummary() {
|
||||
const nav = $("global-policy-summary"); if (!nav) return;
|
||||
const items = [...document.querySelectorAll("#global-security-form .global-policy-section")].map(section => {
|
||||
const title = section.querySelector(".global-policy-heading h3")?.firstChild?.textContent?.trim() || "";
|
||||
const state = section.querySelector(".global-policy-state")?.textContent || "";
|
||||
const chip = el("button", undefined, `global-policy-chip${section.classList.contains("is-off") ? "" : " is-on"}`); chip.type = "button"; chip.dataset.uiIconName = "none";
|
||||
chip.append(el("span", title), el("b", state));
|
||||
chip.addEventListener("click", () => { section.scrollIntoView({ block: "start", behavior: "smooth" }); section.querySelector("input, select, textarea, summary")?.focus?.({ preventScroll: true }); });
|
||||
return chip;
|
||||
});
|
||||
nav.replaceChildren(...items);
|
||||
}
|
||||
for (const id of ["global-country-mode", "global-ua-block-enabled", "global-ip-enabled", "global-method-mode", "global-content-type-enabled", "global-rate-enabled", "global-hsts-enabled"]) {
|
||||
$(id)?.addEventListener("change", syncGlobalSecurityControls);
|
||||
@@ -341,7 +373,7 @@ bindSettingsForm("response-form", next => {
|
||||
next.compression = { min_bytes: Number($("compress-min").value) }; for (const name of ["gzip", "br", "zstd", "deflate"]) next.compression[name] = $(`compress-${name}`).checked;
|
||||
}, "response", next => ({ server_header: next.server_header, diagnostic_headers: next.diagnostic_headers, compression: next.compression }));
|
||||
bindSettingsForm("cache-form", next => {
|
||||
next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null };
|
||||
next.cache = { ...(next.cache || {}), enabled: $("cache-enabled").checked, varnish_compatible: $("cache-varnish-compatible").checked, varnish_grace_seconds: Number($("cache-varnish-grace").value), memory_preset: selectedCacheMemoryPreset, max_bytes: Math.round(Number($("cache-memory").value) * 1048576), transient_max_bytes: Math.round(Number($("cache-transient-memory").value) * 1048576), max_object_bytes: Number($("cache-object").value) * 1024, max_entries: Number($("cache-entries").value), hot_eviction_max_objects: Number($("cache-eviction-limit").value), hot_auto_trim_enabled: $("cache-auto-trim-enabled").checked, hot_auto_trim_after_seconds: Number($("cache-auto-trim-after").value), hot_auto_trim_target_percent: Number($("cache-auto-trim-target").value), cold_enabled: $("cache-cold-enabled").checked, cold_preset: selectedCacheColdPreset, cold_path: $("cache-cold-path").value.trim(), cold_max_bytes: Math.round(Number($("cache-cold-bytes").value) * 1048576), cold_max_entries: Number($("cache-cold-entries").value), cold_queue_max_bytes: Math.round(Number($("cache-cold-queue-bytes").value) * 1048576), cold_gc_interval_seconds: Number($("cache-cold-gc-interval").value), cold_gc_max_delete: Number($("cache-cold-gc-max-delete").value), cold_after_seconds: Number($("cache-cold-after").value), cold_max_hot_seconds: Number($("cache-cold-max-hot").value), cold_on_idle: $("cache-cold-on-idle").checked, cold_on_age: $("cache-cold-on-age").checked, cold_on_lru: $("cache-cold-on-lru").checked, cold_on_shutdown: $("cache-cold-on-shutdown").checked, max_ttl_seconds: Number($("cache-ttl").value), default_ttl_seconds: Number($("cache-default-ttl").value), collapse_enabled: $("cache-collapse-enabled").checked, collapse_wait_timeout_ms: Number($("cache-collapse-timeout").value), collapse_timeout_fallback: $("cache-collapse-fallback").value, stale_if_error_timeout: $("cache-sie-timeout").checked, stale_if_error_connection: $("cache-sie-connection").checked, stale_if_error_dns: $("cache-sie-dns").checked, stale_if_error_tls: $("cache-sie-tls").checked, stale_if_error_statuses: $("cache-sie-statuses").value.split(/[\s,]+/).filter(Boolean).map(Number), proactive_refresh_enabled: $("cache-proactive-enabled").checked, proactive_refresh_before_expiry_seconds: Number($("cache-proactive-before").value), proactive_refresh_percent: Number($("cache-proactive-percent").value), proactive_refresh_max_inflight: Number($("cache-proactive-inflight").value), bypass_query: $("cache-query").checked, bypass_prefixes: $("cache-prefixes").value.split(/\r?\n/).map(v => v.trim()).filter(Boolean), http_invalidation_allowed_cidrs: $("cache-http-invalidation-cidrs").value.split(/[\n,]+/).map(v => v.trim()).filter(Boolean), static_ignore_cookies: $("cache-static-cookie").checked, static_extensions: $("cache-static-extensions").value.split(/[\n,]+/).map(v => v.trim().replace(/^\./, "").toLowerCase()).filter(Boolean), expose_status: $("cache-status-header").checked, expose_hits: $("cache-hits-header").checked, expose_cache_status: $("cache-rfc-header").checked, expose_resident_age: $("cache-resident-age-header").checked, expose_only_hits: $("cache-only-hits").checked, via_header: $("cache-via-enabled").checked ? $("cache-via-value").value.trim() : null, rules: cacheRulesEditor ? cacheRulesEditor.read() : (next.cache?.rules || []) };
|
||||
}, "cache");
|
||||
bindSettingsForm("transform-form", next => {
|
||||
next.transform = {
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
"use strict";
|
||||
window.rustProxyCacheRules = (() => {
|
||||
const MAX_RULES = 128;
|
||||
const STAGES = ["request", "response", "deliver"];
|
||||
const STAGE_KEYS = { request: "cacheRuleStageRequest", response: "cacheRuleStageResponse", deliver: "cacheRuleStageDeliver" };
|
||||
const FIELDS = {
|
||||
host: { ops: ["equals", "suffix", "prefix", "regex", "glob"], stages: STAGES },
|
||||
url: { ops: ["prefix", "regex", "glob", "equals", "contains"], stages: STAGES },
|
||||
path: { ops: ["prefix", "equals", "glob", "regex", "suffix", "contains"], stages: STAGES },
|
||||
extension: { ops: ["equals"], stages: STAGES },
|
||||
method: { ops: ["equals"], stages: STAGES },
|
||||
query: { ops: ["exists", "equals", "prefix", "regex"], name: true, stages: STAGES },
|
||||
header: { ops: ["exists", "equals", "contains", "prefix", "regex"], name: true, stages: STAGES },
|
||||
cookie: { ops: ["exists", "equals", "regex"], name: true, stages: STAGES },
|
||||
client_ip: { ops: ["cidr"], stages: STAGES },
|
||||
status: { ops: ["equals"], stages: ["response", "deliver"] },
|
||||
content_type: { ops: ["prefix", "equals", "regex"], stages: ["response", "deliver"] },
|
||||
response_header: { ops: ["exists", "equals", "contains", "regex"], name: true, stages: ["response", "deliver"] },
|
||||
};
|
||||
const ACTIONS = {
|
||||
request: ["pass", "strip_cookies", "strip_query", "hash_header", "hash_cookie"],
|
||||
response: ["ttl", "grace", "no_store", "ignore_cache_control", "strip_set_cookie"],
|
||||
deliver: ["set_header", "remove_header"],
|
||||
};
|
||||
const ASPECTS = { pass: "pass", ttl: "ttl", grace: "grace", no_store: "store" };
|
||||
const tk = (prefix, value) => t(`${prefix}${String(value).split("_").map(part => part[0].toUpperCase() + part.slice(1)).join("")}`);
|
||||
const fieldLabel = field => tk("cacheRuleField", field);
|
||||
const opLabel = op => tk("cacheRuleOp", op);
|
||||
const actionLabel = type => tk("cacheRuleAction", type);
|
||||
const splitList = value => String(value || "").split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
|
||||
const durationUnits = [["s", 1], ["m", 60], ["h", 3600], ["d", 86400]];
|
||||
function slug(value, taken) {
|
||||
let base = String(value || "").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/ł/g, "l").replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56) || "rule";
|
||||
let candidate = base, n = 2;
|
||||
while (taken.has(candidate)) candidate = `${base}-${n++}`;
|
||||
return candidate;
|
||||
}
|
||||
function blankRule(taken, stage = "request") {
|
||||
const id = slug(t("cacheRuleNewName"), taken);
|
||||
return { id, name: t("cacheRuleNewName"), enabled: true, stage, match: "all", conditions: [], actions: [{ type: ACTIONS[stage][0] }], stop: false, vhosts: [] };
|
||||
}
|
||||
function normalize(rule) {
|
||||
return { id: rule.id, name: rule.name || "", enabled: rule.enabled !== false, stage: rule.stage || "request", match: rule.match || "all", conditions: (rule.conditions || []).map(c => ({ ...c, values: [...(c.values || [])] })), actions: (rule.actions || []).map(a => ({ ...a })), stop: !!rule.stop, vhosts: [...(rule.vhosts || [])] };
|
||||
}
|
||||
function clean(rule, global) {
|
||||
const out = { id: rule.id, name: rule.name, enabled: rule.enabled, stage: rule.stage, match: rule.match, conditions: rule.conditions.map(c => { const item = { field: c.field, operator: c.operator, values: c.operator === "exists" ? [] : c.values }; if (FIELDS[c.field]?.name) item.name = c.name || ""; if (c.negate) item.negate = true; return item; }), actions: rule.actions.map(a => ({ ...a })), stop: rule.stop };
|
||||
if (global && rule.vhosts.length) out.vhosts = rule.vhosts;
|
||||
return out;
|
||||
}
|
||||
const esc = value => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const reEsc = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const globRe = value => String(value).split("*").map(reEsc).join(".*");
|
||||
function vclVar(field, name, stage) {
|
||||
const resp = stage === "deliver" ? "resp" : "beresp";
|
||||
return { host: "req.http.host", url: "req.url", path: "req.url", extension: "req.url", method: "req.method", query: "req.url", header: `req.http.${name}`, cookie: "req.http.Cookie", client_ip: "client.ip", status: `${resp}.status`, content_type: `${resp}.http.Content-Type`, response_header: `${resp}.http.${name}` }[field];
|
||||
}
|
||||
function vclCondition(c, stage) {
|
||||
const variable = vclVar(c.field, c.name, stage), values = c.values || [];
|
||||
const one = value => {
|
||||
if (c.field === "status") { const m = String(value).match(/^(\d)xx$/i); if (m) return `(${variable} >= ${m[1]}00 && ${variable} <= ${m[1]}99)`; const r = String(value).split("-"); if (r.length === 2) return `(${variable} >= ${r[0]} && ${variable} <= ${r[1]})`; return `${variable} == ${value}`; }
|
||||
if (c.field === "client_ip") return `client.ip ~ ${c.ruleAcl || "rule_acl"} /* ${value} */`;
|
||||
if (c.field === "extension") return `req.url ~ "\\.${reEsc(value)}(\\?|$)"`;
|
||||
if (c.field === "query") return c.operator === "exists" ? `req.url ~ "[?&]${reEsc(c.name)}="` : `req.url ~ "[?&]${reEsc(c.name)}=${c.operator === "regex" ? value : reEsc(value)}${c.operator === "equals" ? "(&|$)" : ""}"`;
|
||||
if (c.field === "cookie") return c.operator === "exists" ? `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}="` : `req.http.Cookie ~ "(^|;\\s*)${reEsc(c.name)}=${c.operator === "regex" ? value : `${reEsc(value)}(;|$)`}"`;
|
||||
if (c.field === "path" && c.operator === "equals") return `req.url ~ "^${reEsc(value)}(\\?|$)"`;
|
||||
switch (c.operator) {
|
||||
case "equals": return `${variable} == "${esc(value)}"`;
|
||||
case "prefix": return `${variable} ~ "^${esc(reEsc(value))}"`;
|
||||
case "suffix": return `${variable} ~ "${esc(reEsc(value))}$"`;
|
||||
case "contains": return `${variable} ~ "${esc(reEsc(value))}"`;
|
||||
case "glob": return `${variable} ~ "^${esc(globRe(value))}$"`;
|
||||
case "regex": return `${variable} ~ "${esc(value)}"`;
|
||||
default: return variable;
|
||||
}
|
||||
};
|
||||
let expr = c.operator === "exists" && !["query", "cookie"].includes(c.field) ? variable : values.length > 1 ? `(${values.map(one).join(" || ")})` : one(values[0] ?? "");
|
||||
if (c.negate) expr = `!(${expr})`;
|
||||
return expr;
|
||||
}
|
||||
function vclActions(rule) {
|
||||
return rule.actions.map(a => {
|
||||
switch (a.type) {
|
||||
case "pass": return "return (pass);";
|
||||
case "strip_cookies": return a.keep?.length ? `# keep only cookies: ${a.keep.join(", ")}\nset req.http.Cookie = regsuball(req.http.Cookie, "(^|;\\s*)(?!(${a.keep.map(reEsc).join("|")})=)[^;=]+=[^;]*", "");` : "unset req.http.Cookie;";
|
||||
case "strip_query": return a.keep_only ? `# keep only query parameters: ${(a.params || []).join(", ")}` : (a.params?.length ? `set req.url = regsuball(req.url, "([?&])(${a.params.map(p => globRe(p).replace(/\.\*/g, "[^=&]*")).join("|")})=[^&]*", "\\1");` : `set req.url = regsub(req.url, "\\?.*$", "");`);
|
||||
case "hash_header": return `hash_data(req.http.${a.name});`;
|
||||
case "hash_cookie": return `hash_data(regsub(req.http.Cookie, "^.*(?:^|;\\s*)${reEsc(a.name)}=([^;]*).*$", "\\1"));`;
|
||||
case "ttl": return `set beresp.ttl = ${a.seconds ?? 0}s;`;
|
||||
case "grace": return `set beresp.grace = ${a.seconds ?? 0}s;`;
|
||||
case "no_store": return "set beresp.uncacheable = true;";
|
||||
case "ignore_cache_control": return "unset beresp.http.Cache-Control;";
|
||||
case "strip_set_cookie": return "unset beresp.http.Set-Cookie;";
|
||||
case "set_header": return `set resp.http.${a.name} = "${esc(a.value ?? "")}";`;
|
||||
case "remove_header": return `unset resp.http.${a.name};`;
|
||||
default: return `# ${a.type}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
function ruleVcl(rule) {
|
||||
const lines = vclActions(rule).flatMap(line => line.split("\n"));
|
||||
const conditions = rule.conditions.map(c => vclCondition(c, rule.stage));
|
||||
const joined = conditions.join(rule.match === "any" ? " ||\n " : " &&\n ");
|
||||
const body = lines.map(line => ` ${line}`).join("\n");
|
||||
const head = `# ${rule.name || rule.id}${rule.enabled === false ? " (disabled)" : ""}${rule.vhosts?.length ? ` · vhosts: ${rule.vhosts.join(", ")}` : ""}`;
|
||||
return conditions.length ? `${head}\nif (${joined}) {\n${body}\n}` : `${head}\n${body.replace(/^ {4}/gm, "")}`;
|
||||
}
|
||||
function exportVcl(rules) {
|
||||
const subs = { request: "vcl_recv", response: "vcl_backend_response", deliver: "vcl_deliver" };
|
||||
const blocks = ["vcl 4.1;", "# Generated by RustProxy cache rules (read-only preview)"];
|
||||
const indent = text => text.replace(/^/gm, " ");
|
||||
for (const stage of STAGES) {
|
||||
const items = rules.filter(rule => rule.stage === stage);
|
||||
const main = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => !a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
|
||||
const hash = items.map(rule => ({ ...rule, actions: rule.actions.filter(a => a.type.startsWith("hash_")) })).filter(rule => rule.actions.length);
|
||||
if (main.length) blocks.push(`\nsub ${subs[stage]} {\n${main.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
|
||||
if (hash.length) blocks.push(`\nsub vcl_hash {\n${hash.map(rule => indent(ruleVcl(rule))).join("\n\n")}\n}`);
|
||||
}
|
||||
return blocks.join("\n");
|
||||
}
|
||||
function summary(rule) {
|
||||
const actions = rule.actions.map(a => {
|
||||
if (a.type === "ttl" || a.type === "grace") return `${actionLabel(a.type)} ${fmtDuration(a.seconds)}`;
|
||||
if (a.type === "strip_query") return `${actionLabel(a.type)}${a.params?.length ? `: ${a.params.join(", ")}` : ""}`;
|
||||
if (a.type === "set_header" || a.type === "remove_header" || a.type === "hash_header" || a.type === "hash_cookie") return `${actionLabel(a.type)}: ${a.name || "-"}`;
|
||||
return actionLabel(a.type);
|
||||
});
|
||||
return actions.join(" · ");
|
||||
}
|
||||
function fmtDuration(seconds) {
|
||||
seconds = Number(seconds) || 0;
|
||||
for (const [unit, size] of [...durationUnits].reverse()) if (seconds >= size && seconds % size === 0) return `${seconds / size}${unit}`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
const TEMPLATES = {
|
||||
wordpress: () => [{ name: t("cacheRuleTplWordpress"), stage: "request", match: "any", conditions: [{ field: "path", operator: "regex", values: ["^/(wp-admin|wp-login\\.php|xmlrpc\\.php|wp-json)"] }, { field: "header", name: "cookie", operator: "regex", values: ["wordpress_logged_in_|comment_author_|woocommerce_items_in_cart|wp-postpass_"] }], actions: [{ type: "pass" }] }],
|
||||
static: () => [
|
||||
{ name: t("cacheRuleTplStaticCookies"), stage: "request", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }], actions: [{ type: "strip_cookies", keep: [] }] },
|
||||
{ name: t("cacheRuleTplStaticTtl"), stage: "response", match: "all", conditions: [{ field: "extension", operator: "equals", values: ["css", "js", "mjs", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "woff", "woff2"] }, { field: "status", operator: "equals", values: ["200"] }], actions: [{ type: "ttl", seconds: 2592000 }, { type: "strip_set_cookie" }] },
|
||||
],
|
||||
tracking: () => [{ name: t("cacheRuleTplTracking"), stage: "request", match: "all", conditions: [], actions: [{ type: "strip_query", params: ["utm_*", "fbclid", "gclid", "msclkid", "mc_cid", "mc_eid", "_ga"] }] }],
|
||||
api: () => [{ name: t("cacheRuleTplApi"), stage: "request", match: "all", conditions: [{ field: "path", operator: "prefix", values: ["/api/"] }], actions: [{ type: "pass" }] }],
|
||||
language: () => [{ name: t("cacheRuleTplLanguage"), stage: "request", match: "all", conditions: [], actions: [{ type: "hash_cookie", name: "lang" }] }],
|
||||
notfound: () => [{ name: t("cacheRuleTplNotFound"), stage: "response", match: "all", conditions: [{ field: "status", operator: "equals", values: ["404"] }], actions: [{ type: "ttl", seconds: 60 }] }],
|
||||
headers: () => [{ name: t("cacheRuleTplHeaders"), stage: "deliver", match: "all", conditions: [], actions: [{ type: "remove_header", name: "X-Powered-By" }] }],
|
||||
};
|
||||
function applicableGlobals(vhostId) {
|
||||
return (envelope?.config?.cache?.rules || []).filter(rule => rule.enabled !== false && (!rule.vhosts?.length || rule.vhosts.includes(vhostId)));
|
||||
}
|
||||
function aspects(rule) { return new Set(rule.actions.map(a => ASPECTS[a.type]).filter(Boolean)); }
|
||||
function conflictsFor(vhostRules, globals) {
|
||||
const notes = [];
|
||||
for (const local of vhostRules.filter(rule => rule.enabled !== false)) {
|
||||
const mine = aspects(local);
|
||||
if (!mine.size) continue;
|
||||
for (const global of globals) {
|
||||
if (global.stage !== local.stage) continue;
|
||||
const shared = [...aspects(normalize(global))].filter(aspect => mine.has(aspect));
|
||||
if (shared.length) notes.push(t("cacheRulesOverrideNotice").replace("{vhost}", local.name || local.id).replace("{global}", global.name || global.id).replace("{aspects}", shared.map(aspect => t(`cacheRuleAspect${aspect[0].toUpperCase()}${aspect.slice(1)}`)).join(", ")));
|
||||
}
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
function globalOverrideNotes(rule) {
|
||||
const vhosts = envelope?.config?.vhosts || [], mine = aspects(rule), overriddenBy = [], skippedBy = [];
|
||||
for (const vhost of vhosts) {
|
||||
if (rule.vhosts?.length && !rule.vhosts.includes(vhost.id)) continue;
|
||||
if (vhost.cache?.ignore_global_rules) { skippedBy.push(vhost.id); continue; }
|
||||
if ((vhost.cache?.rules || []).some(local => local.enabled !== false && local.stage === rule.stage && [...aspects(normalize(local))].some(aspect => mine.has(aspect)))) overriddenBy.push(vhost.id);
|
||||
}
|
||||
const notes = [];
|
||||
if (overriddenBy.length) notes.push(t("cacheRulesOverriddenIn").replace("{vhosts}", overriddenBy.join(", ")));
|
||||
if (skippedBy.length) notes.push(t("cacheRulesIgnoredIn").replace("{vhosts}", skippedBy.join(", ")));
|
||||
return notes;
|
||||
}
|
||||
let hits = {};
|
||||
async function loadHits() {
|
||||
if (!authenticated) return;
|
||||
try { hits = (await api("/api/cache/rules/stats")).hits || {}; } catch { hits = {}; }
|
||||
}
|
||||
function select(values, current, label) {
|
||||
const node = el("select"); for (const [value, text] of values) { const option = el("option", text); option.value = value; node.append(option); } node.value = current; if (label) node.setAttribute("aria-label", label); return node;
|
||||
}
|
||||
function textInput(value, placeholder = "", cls = "") { const node = el("input", undefined, cls); node.type = "text"; node.value = value ?? ""; node.placeholder = placeholder; node.spellcheck = false; return node; }
|
||||
function durationInput(seconds, onChange) {
|
||||
const wrap = el("span", undefined, "cache-rule-duration"), number = el("input"); number.type = "number"; number.min = 0; number.step = 1;
|
||||
let unit = "s"; for (const [name, size] of [...durationUnits].reverse()) if ((seconds || 0) >= size && (seconds || 0) % size === 0) { unit = name; break; }
|
||||
number.value = Math.round((seconds || 0) / Object.fromEntries(durationUnits)[unit]);
|
||||
const units = select(durationUnits.map(([name]) => [name, t(`cacheRuleUnit${name.toUpperCase()}`)]), unit, t("cacheRuleDurationUnit"));
|
||||
const emit = () => onChange(Math.max(0, Math.round(Number(number.value) || 0) * Object.fromEntries(durationUnits)[units.value]));
|
||||
number.addEventListener("input", emit); units.addEventListener("change", emit);
|
||||
wrap.append(number, units); return wrap;
|
||||
}
|
||||
function create(options = {}) {
|
||||
const scope = options.scope === "vhost" ? "vhost" : "global", vhostId = options.vhostId || "";
|
||||
let rules = (options.rules || []).map(normalize), open = new Set(), ignoreGlobal = !!options.ignoreGlobal;
|
||||
const root = el("div", undefined, `cache-rules cache-rules-${scope}`);
|
||||
const changed = () => { root.dispatchEvent(new Event("input", { bubbles: true })); options.onChange?.(); };
|
||||
const toolbar = el("div", undefined, "cache-rules-toolbar");
|
||||
if (scope === "vhost") { const docs = el("a", t("cacheRulesDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FCACHE.md§ion=cache-rules-vcl-style"; docs.target = "_blank"; docs.rel = "noopener noreferrer"; root.append(docs); }
|
||||
const templates = select([["", t("cacheRulesTemplates")], ...Object.keys(TEMPLATES).map(key => [key, t(`cacheRuleTpl${key[0].toUpperCase()}${key.slice(1)}`)])], "", t("cacheRulesTemplates"));
|
||||
templates.classList.add("cache-rules-templates");
|
||||
const importButton = el("button", t("cacheRulesImportVcl"), "outline"); importButton.type = "button";
|
||||
const exportButton = el("button", t("cacheRulesExportVcl"), "outline"); exportButton.type = "button";
|
||||
const addButton = el("button", t("cacheRulesAdd"), "primary"); addButton.type = "button";
|
||||
toolbar.append(templates, importButton, exportButton, addButton);
|
||||
const ignoreWrap = el("label", undefined, "check cache-rules-ignore"), ignoreBox = el("input"); ignoreBox.type = "checkbox"; ignoreBox.checked = ignoreGlobal; ignoreBox.id = "vh-cache-ignore-global-rules";
|
||||
ignoreWrap.append(ignoreBox, el("span", t("cacheRulesIgnoreGlobal")));
|
||||
const notices = el("div", undefined, "cache-rules-notices");
|
||||
const list = el("div", undefined, "cache-rules-list");
|
||||
const empty = el("p", t(scope === "vhost" ? "cacheRulesEmptyVhost" : "cacheRulesEmpty"), "fine cache-rules-empty");
|
||||
const importBox = el("div", undefined, "cache-rules-import"); importBox.hidden = true;
|
||||
const importText = document.createElement("textarea"); importText.rows = 10; importText.spellcheck = false; importText.placeholder = "sub vcl_recv {\n if (req.url ~ \"^/admin\") {\n return (pass);\n }\n}";
|
||||
const importRun = el("button", t("cacheRulesImportRun"), "primary"); importRun.type = "button";
|
||||
const importCancel = el("button", t("cancel"), "outline"); importCancel.type = "button";
|
||||
const importResult = el("div", undefined, "cache-rules-import-result");
|
||||
const importActions = el("div", undefined, "form-actions"); importActions.append(importRun, importCancel);
|
||||
importBox.append(el("p", t("cacheRulesImportHelp"), "fine"), importText, importActions, importResult);
|
||||
const exportBox = el("details", undefined, "cache-rules-export"); const exportSummary = el("summary", t("cacheRulesVclPreview")); const exportPre = el("pre", "", "metrics-example mono cache-rules-vcl");
|
||||
exportBox.append(exportSummary, exportPre);
|
||||
const tester = buildTester();
|
||||
root.append(toolbar);
|
||||
if (scope === "vhost") root.append(ignoreWrap);
|
||||
root.append(notices, importBox, list, empty, exportBox, tester.node);
|
||||
for (const isolated of [tester.node, importBox]) for (const type of ["input", "change"]) isolated.addEventListener(type, event => event.stopPropagation());
|
||||
root.addEventListener("keydown", event => { if (event.key === "Enter" && event.target.matches?.("input:not([type=checkbox])")) event.preventDefault(); });
|
||||
function taken() { return new Set(rules.map(rule => rule.id)); }
|
||||
function renderNotices() {
|
||||
notices.replaceChildren();
|
||||
if (scope !== "vhost") return;
|
||||
const globals = applicableGlobals(vhostId);
|
||||
if (ignoreGlobal) { if (globals.length) notices.append(el("p", t("cacheRulesGlobalSkipped").replace("{count}", globals.length), "fine cache-rules-notice")); return; }
|
||||
if (globals.length) notices.append(el("p", t("cacheRulesGlobalApply").replace("{count}", globals.length).replace("{names}", globals.slice(0, 6).map(rule => rule.name || rule.id).join(", ") + (globals.length > 6 ? "…" : "")), "fine"));
|
||||
for (const note of conflictsFor(rules, globals)) notices.append(el("p", note, "fine cache-rules-notice"));
|
||||
}
|
||||
function render() {
|
||||
list.replaceChildren(...rules.map((rule, index) => ruleCard(rule, index)));
|
||||
empty.hidden = rules.length > 0;
|
||||
addButton.disabled = rules.length >= MAX_RULES;
|
||||
exportPre.textContent = exportVcl(rules);
|
||||
renderNotices();
|
||||
}
|
||||
function move(from, to) { if (to < 0 || to >= rules.length) return; const [item] = rules.splice(from, 1); rules.splice(to, 0, item); render(); changed(); }
|
||||
function ruleCard(rule, index) {
|
||||
const card = el("div", undefined, `cache-rule${rule.enabled ? "" : " is-disabled"}${open.has(rule.id) ? " is-open" : ""}`); card.draggable = true; card.dataset.index = index;
|
||||
card.addEventListener("dragstart", event => { event.dataTransfer.setData("text/plain", String(index)); card.classList.add("is-dragging"); });
|
||||
card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
|
||||
card.addEventListener("dragover", event => { event.preventDefault(); card.classList.add("is-drop"); });
|
||||
card.addEventListener("dragleave", () => card.classList.remove("is-drop"));
|
||||
card.addEventListener("drop", event => { event.preventDefault(); card.classList.remove("is-drop"); const from = Number(event.dataTransfer.getData("text/plain")); if (Number.isInteger(from) && from !== index) move(from, index); });
|
||||
const head = el("div", undefined, "cache-rule-head");
|
||||
const grip = el("span", "⠿", "cache-rule-grip"); grip.title = t("cacheRulesDrag");
|
||||
const toggle = el("input"); toggle.type = "checkbox"; toggle.checked = rule.enabled; toggle.setAttribute("aria-label", t("enabled"));
|
||||
toggle.addEventListener("change", () => { rule.enabled = toggle.checked; card.classList.toggle("is-disabled", !rule.enabled); exportPre.textContent = exportVcl(rules); changed(); });
|
||||
const title = el("button", undefined, "cache-rule-title"); title.type = "button"; title.dataset.uiIconName = "none";
|
||||
title.append(el("b", rule.name || rule.id), el("span", t(STAGE_KEYS[rule.stage]), "pill cache-rule-stage"), el("span", summary(rule), "fine cache-rule-summary"));
|
||||
title.addEventListener("click", () => { if (open.has(rule.id)) open.delete(rule.id); else open.add(rule.id); render(); });
|
||||
const hitKey = scope === "vhost" ? `vhost:${vhostId}:${rule.id}` : `global:${rule.id}`;
|
||||
const hitCount = el("span", hits[hitKey] != null ? t("cacheRulesHits").replace("{count}", fmt(hits[hitKey])) : "", "fine cache-rule-hits");
|
||||
const actions = el("span", undefined, "cache-rule-actions");
|
||||
const up = el("button", "↑", "quiet"); up.type = "button"; up.disabled = index === 0; up.setAttribute("aria-label", t("cacheRulesMoveUp")); up.addEventListener("click", () => move(index, index - 1));
|
||||
const down = el("button", "↓", "quiet"); down.type = "button"; down.disabled = index === rules.length - 1; down.setAttribute("aria-label", t("cacheRulesMoveDown")); down.addEventListener("click", () => move(index, index + 1));
|
||||
const copy = el("button", t("cacheRulesDuplicate"), "quiet"); copy.type = "button"; copy.addEventListener("click", () => { if (rules.length >= MAX_RULES) return; const clone = normalize(structuredClone(rule)); clone.id = slug(`${rule.id}-copy`, taken()); clone.name = `${rule.name || rule.id} (${t("cacheRulesCopySuffix")})`; rules.splice(index + 1, 0, clone); open.add(clone.id); render(); changed(); });
|
||||
const remove = el("button", t("remove"), "quiet danger"); remove.type = "button"; remove.addEventListener("click", () => { rules.splice(index, 1); open.delete(rule.id); render(); changed(); });
|
||||
actions.append(up, down, copy, remove);
|
||||
head.append(grip, toggle, title, hitCount, actions);
|
||||
card.append(head);
|
||||
if (scope === "global") for (const note of globalOverrideNotes(rule)) card.append(el("p", note, "fine cache-rules-notice cache-rule-note"));
|
||||
if (open.has(rule.id)) card.append(ruleEditor(rule));
|
||||
return card;
|
||||
}
|
||||
function ruleEditor(rule) {
|
||||
const body = el("div", undefined, "cache-rule-body");
|
||||
const grid = el("div", undefined, "cache-rule-grid");
|
||||
const name = textInput(rule.name, t("cacheRuleNamePlaceholder")); name.maxLength = 96;
|
||||
name.addEventListener("input", () => { rule.name = name.value; changed(); syncPreview(); });
|
||||
const id = textInput(rule.id, "", "mono"); id.maxLength = 64; id.pattern = "[A-Za-z0-9_\\-]{1,64}";
|
||||
id.addEventListener("change", () => { const value = id.value.trim(); if (!/^[A-Za-z0-9_-]{1,64}$/.test(value) || (value !== rule.id && taken().has(value))) { id.value = rule.id; toast(t("cacheRuleIdInvalid"), true); return; } open.delete(rule.id); rule.id = value; open.add(value); changed(); });
|
||||
const stage = select(STAGES.map(value => [value, t(STAGE_KEYS[value])]), rule.stage, t("cacheRuleStage"));
|
||||
stage.addEventListener("change", () => { rule.stage = stage.value; rule.actions = rule.actions.filter(a => ACTIONS[rule.stage].includes(a.type)); if (!rule.actions.length) rule.actions = [{ type: ACTIONS[rule.stage][0] }]; rule.conditions = rule.conditions.filter(c => FIELDS[c.field].stages.includes(rule.stage)); render(); changed(); });
|
||||
const match = select([["all", t("cacheRuleMatchAll")], ["any", t("cacheRuleMatchAny")]], rule.match, t("cacheRuleMatch"));
|
||||
match.addEventListener("change", () => { rule.match = match.value; changed(); syncPreview(); });
|
||||
const stop = el("input"); stop.type = "checkbox"; stop.checked = rule.stop; stop.addEventListener("change", () => { rule.stop = stop.checked; changed(); });
|
||||
const labeled = (key, control, help) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); if (help) label.append(el("small", t(help), "fine")); return label; };
|
||||
const stopLabel = el("label", undefined, "check cache-rule-stop"); stopLabel.append(stop, el("span", t("cacheRuleStop")));
|
||||
grid.append(labeled("cacheRuleName", name), labeled("cacheRuleId", id), labeled("cacheRuleStage", stage, `cacheRuleStageHelp${rule.stage[0].toUpperCase()}${rule.stage.slice(1)}`), labeled("cacheRuleMatch", match), stopLabel);
|
||||
body.append(grid);
|
||||
if (scope === "global") {
|
||||
const vhostItems = (envelope?.config?.vhosts || []).map(vhost => ({ id: vhost.id, title: vhost.name || vhost.id, detail: (vhost.frontend?.hosts || []).slice(0, 3).join(", ") }));
|
||||
const picker = window.rustProxyChoicePicker.create({ className: "cache-rule-vhosts", selected: rule.vhosts, items: vhostItems, limit: 64, labels: { choose: "cacheRuleVhostsAll", selected: "cacheRuleVhostsSelected", none: "cacheRuleVhostsNone", empty: "cacheRuleVhostsEmpty" } });
|
||||
picker.addEventListener("choicechange", event => { rule.vhosts = event.detail || []; exportPre.textContent = exportVcl(rules); });
|
||||
picker.addEventListener("change", changed);
|
||||
const field = el("div", undefined, "cache-rule-field cache-rule-vhosts-field"); field.append(el("span", t("cacheRuleVhosts")), picker, el("small", t("cacheRuleVhostsHelp"), "fine"));
|
||||
body.append(field);
|
||||
}
|
||||
const conditions = el("div", undefined, "cache-rule-section");
|
||||
conditions.append(el("h4", t("cacheRuleConditions")));
|
||||
const conditionRows = el("div", undefined, "cache-rule-rows");
|
||||
rule.conditions.forEach((condition, index) => conditionRows.append(conditionRow(rule, condition, index)));
|
||||
if (!rule.conditions.length) conditionRows.append(el("p", t("cacheRuleNoConditions"), "fine"));
|
||||
const addCondition = el("button", t("cacheRuleAddCondition"), "outline"); addCondition.type = "button";
|
||||
addCondition.disabled = rule.conditions.length >= 16;
|
||||
addCondition.addEventListener("click", () => { rule.conditions.push({ field: "path", operator: "prefix", values: [] }); render(); changed(); });
|
||||
conditions.append(conditionRows, addCondition);
|
||||
const actionsSection = el("div", undefined, "cache-rule-section");
|
||||
actionsSection.append(el("h4", t("cacheRuleActions")));
|
||||
const actionRows = el("div", undefined, "cache-rule-rows");
|
||||
rule.actions.forEach((action, index) => actionRows.append(actionRow(rule, action, index)));
|
||||
const addAction = el("button", t("cacheRuleAddAction"), "outline"); addAction.type = "button";
|
||||
addAction.disabled = rule.actions.length >= 16;
|
||||
addAction.addEventListener("click", () => { const used = new Set(rule.actions.map(a => a.type)); rule.actions.push({ type: ACTIONS[rule.stage].find(type => !used.has(type)) || ACTIONS[rule.stage][0] }); render(); changed(); });
|
||||
actionsSection.append(actionRows, addAction);
|
||||
const preview = el("pre", "", "metrics-example mono cache-rule-vcl");
|
||||
const syncPreview = () => { preview.textContent = ruleVcl(rule); exportPre.textContent = exportVcl(rules); };
|
||||
body.addEventListener("input", syncPreview); body.addEventListener("change", syncPreview);
|
||||
const previewWrap = el("div", undefined, "cache-rule-section"); previewWrap.append(el("h4", t("cacheRuleVcl")), preview);
|
||||
body.append(conditions, actionsSection, previewWrap);
|
||||
syncPreview();
|
||||
return body;
|
||||
}
|
||||
function conditionRow(rule, condition, index) {
|
||||
const row = el("div", undefined, "cache-rule-row");
|
||||
const fields = Object.keys(FIELDS).filter(field => FIELDS[field].stages.includes(rule.stage));
|
||||
const field = select(fields.map(value => [value, fieldLabel(value)]), condition.field, t("cacheRuleField"));
|
||||
const name = textInput(condition.name, t("cacheRuleNamePlaceholderField"), "cache-rule-name"); name.hidden = !FIELDS[condition.field].name;
|
||||
const ops = FIELDS[condition.field].ops;
|
||||
if (!ops.includes(condition.operator)) condition.operator = ops[0];
|
||||
const operator = select(ops.map(value => [value, opLabel(value)]), condition.operator, t("cacheRuleOperator"));
|
||||
const values = textInput((condition.values || []).join(", "), t(`cacheRuleValuesPlaceholder${condition.field === "status" ? "Status" : condition.field === "client_ip" ? "Cidr" : condition.field === "extension" ? "Extension" : condition.field === "method" ? "Method" : ""}`), "cache-rule-values");
|
||||
values.hidden = condition.operator === "exists";
|
||||
const negateLabel = el("label", undefined, "check cache-rule-negate"), negate = el("input"); negate.type = "checkbox"; negate.checked = !!condition.negate; negateLabel.append(negate, el("span", t("cacheRuleNegate")));
|
||||
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove"));
|
||||
field.addEventListener("change", () => { condition.field = field.value; condition.operator = FIELDS[field.value].ops[0]; if (!FIELDS[field.value].name) delete condition.name; render(); changed(); });
|
||||
name.addEventListener("input", () => { condition.name = name.value.trim(); changed(); });
|
||||
operator.addEventListener("change", () => { condition.operator = operator.value; if (operator.value === "exists") condition.values = []; render(); changed(); });
|
||||
values.addEventListener("input", () => { condition.values = operator.value === "regex" ? [values.value.trim()].filter(Boolean) : splitList(values.value); changed(); });
|
||||
negate.addEventListener("change", () => { condition.negate = negate.checked; changed(); });
|
||||
remove.addEventListener("click", () => { rule.conditions.splice(index, 1); render(); changed(); });
|
||||
row.append(field, name, operator, values, negateLabel, remove);
|
||||
return row;
|
||||
}
|
||||
function actionRow(rule, action, index) {
|
||||
const row = el("div", undefined, "cache-rule-row");
|
||||
const type = select(ACTIONS[rule.stage].map(value => [value, actionLabel(value)]), action.type, t("cacheRuleAction"));
|
||||
const params = el("span", undefined, "cache-rule-params");
|
||||
const remove = el("button", "×", "quiet"); remove.type = "button"; remove.setAttribute("aria-label", t("remove")); remove.disabled = rule.actions.length <= 1;
|
||||
type.addEventListener("change", () => { rule.actions[index] = { type: type.value }; render(); changed(); });
|
||||
remove.addEventListener("click", () => { rule.actions.splice(index, 1); render(); changed(); });
|
||||
const listInput = (key, placeholder) => { const node = textInput((action[key] || []).join(", "), placeholder); node.addEventListener("input", () => { action[key] = splitList(node.value); changed(); }); return node; };
|
||||
const nameInput = placeholder => { const node = textInput(action.name, placeholder); node.addEventListener("input", () => { action.name = node.value.trim(); changed(); }); return node; };
|
||||
switch (action.type) {
|
||||
case "strip_cookies": params.append(listInput("keep", t("cacheRuleKeepCookies"))); break;
|
||||
case "strip_query": {
|
||||
const keepOnly = el("label", undefined, "check"), box = el("input"); box.type = "checkbox"; box.checked = !!action.keep_only; keepOnly.append(box, el("span", t("cacheRuleKeepOnly")));
|
||||
box.addEventListener("change", () => { action.keep_only = box.checked; changed(); });
|
||||
params.append(listInput("params", t("cacheRuleQueryParams")), keepOnly); break;
|
||||
}
|
||||
case "hash_header": params.append(nameInput("Accept-Language")); break;
|
||||
case "hash_cookie": params.append(nameInput("lang")); break;
|
||||
case "ttl": case "grace": params.append(durationInput(action.seconds ?? (action.type === "ttl" ? 3600 : 60), seconds => { action.seconds = seconds; changed(); })); if (action.seconds == null) action.seconds = action.type === "ttl" ? 3600 : 60; break;
|
||||
case "set_header": { const value = textInput(action.value, t("cacheRuleHeaderValue")); value.addEventListener("input", () => { action.value = value.value; changed(); }); params.append(nameInput("X-Cache-Rule"), value); break; }
|
||||
case "remove_header": params.append(nameInput("X-Powered-By")); break;
|
||||
default: params.append(el("small", t(`cacheRuleActionHelp${action.type.split("_").map(p => p[0].toUpperCase() + p.slice(1)).join("")}`), "fine"));
|
||||
}
|
||||
row.append(type, params, remove);
|
||||
return row;
|
||||
}
|
||||
function buildTester() {
|
||||
const node = el("details", undefined, "cache-rules-tester");
|
||||
node.append(el("summary", t("cacheRulesTester")));
|
||||
const grid = el("div", undefined, "cache-rules-tester-grid");
|
||||
const method = select(["GET", "HEAD", "POST"].map(value => [value, value]), "GET", t("cacheRuleFieldMethod"));
|
||||
const url = textInput("", scope === "vhost" ? "/produkt?id=7&utm_source=fb" : "https://shop.example.com/produkt?id=7&utm_source=fb", "mono");
|
||||
const vhostSelect = select([["", t("cacheRulesTesterNoVhost")], ...(envelope?.config?.vhosts || []).map(vhost => [vhost.id, vhost.name || vhost.id])], vhostId, t("cacheRulesTesterVhost"));
|
||||
const headers = document.createElement("textarea"); headers.rows = 3; headers.placeholder = "Cookie: lang=pl; sid=1\nAccept-Language: pl"; headers.spellcheck = false;
|
||||
const clientIp = textInput("", "203.0.113.10", "mono");
|
||||
const status = el("input"); status.type = "number"; status.min = 100; status.max = 599; status.value = 200;
|
||||
const responseHeaders = document.createElement("textarea"); responseHeaders.rows = 3; responseHeaders.placeholder = "Cache-Control: public, max-age=60\nContent-Type: text/html"; responseHeaders.spellcheck = false;
|
||||
const run = el("button", t("cacheRulesTesterRun"), "primary"); run.type = "button";
|
||||
const result = el("div", undefined, "cache-rules-tester-result");
|
||||
const field = (key, control) => { const label = el("label", undefined, "cache-rule-field"); label.append(el("span", t(key)), control); return label; };
|
||||
grid.append(field("cacheRuleFieldMethod", method), field("cacheRulesTesterUrl", url));
|
||||
if (scope === "global") grid.append(field("cacheRulesTesterVhost", vhostSelect));
|
||||
grid.append(field("cacheRulesTesterHeaders", headers), field("cacheRuleFieldClientIp", clientIp), field("cacheRuleFieldStatus", status), field("cacheRulesTesterResponseHeaders", responseHeaders));
|
||||
const pairs = text => String(text || "").split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => { const at = line.indexOf(":"); return at > 0 ? [line.slice(0, at).trim(), line.slice(at + 1).trim()] : [line, ""]; });
|
||||
run.addEventListener("click", async () => {
|
||||
run.disabled = true; result.replaceChildren(el("p", t("cacheRulesTesterRunning"), "fine"));
|
||||
try {
|
||||
const body = { request: { method: method.value, url: url.value.trim(), headers: pairs(headers.value), client_ip: clientIp.value.trim() || null }, response: { status: Number(status.value) || 200, headers: pairs(responseHeaders.value) } };
|
||||
if (scope === "global") { body.global_rules = read(); body.vhost_id = vhostSelect.value || null; }
|
||||
else { body.vhost_id = vhostId || null; body.vhost_rules = read(); body.ignore_global_rules = ignoreGlobal; if (!vhostId) body.vhost_id = null; }
|
||||
renderResult(await api("/api/cache/rules/test", { method: "POST", body: JSON.stringify(body) }));
|
||||
} catch (error) { result.replaceChildren(el("p", error.message, "fine is-error")); }
|
||||
finally { run.disabled = false; }
|
||||
});
|
||||
function renderResult(data) {
|
||||
const items = [];
|
||||
const line = (label, value, cls = "") => { const row = el("div", undefined, `cache-rules-result-line ${cls}`.trim()); row.append(el("span", label, "fine"), el("strong", value)); items.push(row); };
|
||||
const names = matched => (matched || []).map(item => `${item.name || item.id} (${item.origin === "vhost" ? t("cacheRulesOriginVhost") : t("cacheRulesOriginGlobal")})`).join(", ") || "—";
|
||||
const request = data.request || {};
|
||||
line(t("cacheRulesResultDecision"), request.cacheable ? (data.response?.stored ? t("cacheRulesResultHit").replace("{ttl}", fmtDuration(data.response.ttl)).replace("{grace}", fmtDuration(data.response.grace)) : t("cacheRulesResultNotStored").replace("{reason}", data.response?.reason || "-")) : t("cacheRulesResultPass").replace("{reason}", request.reason || "-"), request.cacheable && data.response?.stored ? "is-ok" : "is-warn");
|
||||
line(t("cacheRulesResultRequest"), names(request.matched));
|
||||
line(t("cacheRulesResultKey"), `${data.host || "-"}${request.target || ""}${request.variant?.length ? ` + ${request.variant.join(", ")}` : ""}`);
|
||||
if (request.cookie != null) line(t("cacheRulesResultCookie"), request.cookie || "—");
|
||||
if (data.response) line(t("cacheRulesResultResponse"), names(data.response.matched));
|
||||
if (data.deliver) line(t("cacheRulesResultDeliver"), [...(data.deliver.set || []).map(([k, v]) => `${k}: ${v}`), ...(data.deliver.remove || []).map(k => `−${k}`)].join(", ") || "—");
|
||||
for (const item of [...(request.overridden || []), ...(data.response?.overridden || [])]) line(t("cacheRulesResultOverridden"), t("cacheRulesResultOverriddenText").replace("{winner}", item.winner).replace("{ignored}", item.ignored).replace("{aspect}", t(`cacheRuleAspect${item.aspect[0].toUpperCase()}${item.aspect.slice(1)}`)), "is-warn");
|
||||
result.replaceChildren(...items);
|
||||
}
|
||||
const actions = el("div", undefined, "form-actions"); actions.append(run);
|
||||
node.append(el("p", t("cacheRulesTesterHelp"), "fine"), grid, actions, result);
|
||||
return { node };
|
||||
}
|
||||
function addRules(items) {
|
||||
const ids = taken(); let added = 0;
|
||||
for (const item of items) {
|
||||
if (rules.length >= MAX_RULES) { toast(t("cacheRulesLimit"), true); break; }
|
||||
const rule = normalize({ ...item, id: slug(item.id || item.name, ids), vhosts: scope === "global" ? item.vhosts || [] : [] });
|
||||
ids.add(rule.id); rules.push(rule); added++;
|
||||
}
|
||||
render(); if (added) changed();
|
||||
return added;
|
||||
}
|
||||
templates.addEventListener("change", () => { const make = TEMPLATES[templates.value]; templates.value = ""; if (!make) return; const added = addRules(make()); if (added) toast(t("cacheRulesTemplateAdded").replace("{count}", added)); });
|
||||
addButton.addEventListener("click", () => { const rule = blankRule(taken()); rules.push(rule); open.add(rule.id); render(); changed(); list.lastElementChild?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); });
|
||||
importButton.addEventListener("click", () => { importBox.hidden = !importBox.hidden; if (!importBox.hidden) importText.focus(); });
|
||||
importCancel.addEventListener("click", () => { importBox.hidden = true; importResult.replaceChildren(); });
|
||||
importRun.addEventListener("click", async () => {
|
||||
importRun.disabled = true; importResult.replaceChildren();
|
||||
try {
|
||||
const data = await api("/api/cache/rules/import-vcl", { method: "POST", body: JSON.stringify({ vcl: importText.value }) });
|
||||
const added = addRules(data.rules || []);
|
||||
importResult.append(el("p", t("cacheRulesImportDone").replace("{count}", added), "fine is-ok"));
|
||||
if (data.warnings?.length) { const list = el("ul", undefined, "cache-rules-warnings"); for (const warning of data.warnings) list.append(el("li", warning)); importResult.append(el("p", t("cacheRulesImportWarnings"), "fine"), list); }
|
||||
} catch (error) { importResult.append(el("p", error.message, "fine is-error")); }
|
||||
finally { importRun.disabled = false; }
|
||||
});
|
||||
exportButton.addEventListener("click", async () => { exportBox.open = true; exportBox.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); try { await navigator.clipboard.writeText(exportPre.textContent); toast(t("copied")); } catch { } });
|
||||
ignoreBox.addEventListener("change", () => { ignoreGlobal = ignoreBox.checked; renderNotices(); changed(); });
|
||||
function read() {
|
||||
for (const rule of rules) {
|
||||
if (!rule.actions.length) throw new Error(t("cacheRuleNeedsAction").replace("{rule}", rule.name || rule.id));
|
||||
for (const c of rule.conditions) {
|
||||
if (FIELDS[c.field].name && !c.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
|
||||
if (c.operator !== "exists" && !(c.values || []).length) throw new Error(t("cacheRuleNeedsValue").replace("{rule}", rule.name || rule.id));
|
||||
}
|
||||
for (const a of rule.actions) if (["hash_header", "hash_cookie", "set_header", "remove_header"].includes(a.type) && !a.name) throw new Error(t("cacheRuleNeedsName").replace("{rule}", rule.name || rule.id));
|
||||
}
|
||||
return rules.map(rule => clean(rule, scope === "global"));
|
||||
}
|
||||
render();
|
||||
void loadHits().then(render);
|
||||
return { node: root, read, ignoreGlobal: () => ignoreGlobal, set(next) { rules = (next || []).map(normalize); open = new Set(); render(); }, refreshHits: () => loadHits().then(render) };
|
||||
}
|
||||
return { create, exportVcl, TEMPLATES };
|
||||
})();
|
||||
+175
-147
@@ -1,55 +1,101 @@
|
||||
"use strict";
|
||||
(() => {
|
||||
const MAX_IDS = 32, ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
||||
let certificateApiState = null, certificateApiLoading = false;
|
||||
let certificateApiEditingKey = null, certificateApiDetailsKey = null;
|
||||
let certificateApiEditingKey = null, certificateApiPicker = null;
|
||||
function certificateApiCredentials() {
|
||||
const values = certificateApiState?.credentials;
|
||||
if (Array.isArray(values)) return values;
|
||||
if (certificateApiState?.configured && certificateApiState?.key_id) return [{ key_id: certificateApiState.key_id, comment: "", created_at: certificateApiState.created_at, last_used_at: certificateApiState.last_used_at }];
|
||||
return [];
|
||||
}
|
||||
const storedCertificates = () => envelope?.config?.tls?.certificates || [];
|
||||
const certificateById = id => storedCertificates().find(cert => cert.id === id);
|
||||
function certificateHosts(cert) {
|
||||
const inventory = typeof certificateInventory !== "undefined" && certificateInventory instanceof Map ? certificateInventory.get(cert.id) : null;
|
||||
const names = inventory?.covered_hosts?.length ? inventory.covered_hosts : cert.covered_hosts?.length ? cert.covered_hosts : cert.hosts || [];
|
||||
return names.map(String);
|
||||
}
|
||||
function pickerItems() {
|
||||
return storedCertificates().map(cert => {
|
||||
const names = certificateHosts(cert), managed = !!cert.issuer;
|
||||
return {
|
||||
id: cert.id, title: cert.id,
|
||||
detail: `${names.slice(0, 4).join(", ")}${names.length > 4 ? ` +${names.length - 4}` : ""}${managed ? ` · ${t("certificateApiManagedReloadOnly")}` : ""}`,
|
||||
search: names.join(" "), badge: managed ? "ACME" : "", badgeClass: "is-allow",
|
||||
};
|
||||
});
|
||||
}
|
||||
function createPicker(selected) {
|
||||
const host = $("certificate-api-certificates");
|
||||
certificateApiPicker = window.rustProxyChoicePicker.create({
|
||||
className: "certificate-api-picker", selected, items: pickerItems(), limit: MAX_IDS, unknownDetail: "certificateApiCertificateNew",
|
||||
labels: { choose: "certificateApiPickerChoose", selected: "certificateApiPickerSelected", none: "certificateApiPickerNone", search: "certificateApiPickerSearch", addHint: "certificateApiPickerAddHint", empty: "certificateApiPickerEmpty" },
|
||||
custom: raw => {
|
||||
const id = String(raw || "").trim(); if (!id) return null;
|
||||
if (id === "*") throw new Error(t("certificateApiWildcardNotAllowed"));
|
||||
if (!ID_PATTERN.test(id)) throw new Error(t("certificateApiCertificateIdInvalid").replace("{id}", id));
|
||||
return { id, title: id, detail: certificateById(id) ? "" : t("certificateApiCertificateNew") };
|
||||
},
|
||||
});
|
||||
certificateApiPicker.addEventListener("choicechange", syncCertificateHelp);
|
||||
certificateApiPicker.addEventListener("choicechange", certificateApiExample);
|
||||
host.replaceChildren(certificateApiPicker);
|
||||
}
|
||||
const selectedIds = () => certificateApiPicker?.read?.() || [];
|
||||
const deployMode = () => $("certificate-api-allow-deploy").checked;
|
||||
function syncCertificateHelp() {
|
||||
const deploy = deployMode(), managed = selectedIds().filter(id => certificateById(id)?.issuer);
|
||||
let text = t(deploy ? "certificateApiCertificatesDeployHelp" : "certificateApiCertificatesReloadHelp");
|
||||
if (deploy && managed.length) text += ` ${t("certificateApiManagedWarning").replace("{ids}", managed.join(", "))}`;
|
||||
$("certificate-api-certificates-help").textContent = text;
|
||||
}
|
||||
function clearCertificateApiSecret() {
|
||||
$("certificate-api-secret").textContent = "";
|
||||
$("certificate-api-secret-wrap").hidden = true;
|
||||
}
|
||||
function showCertificateApiSecret(token) {
|
||||
function showCertificateApiSecret(token, keyId) {
|
||||
$("certificate-api-secret").textContent = token;
|
||||
$("certificate-api-secret-title").textContent = t("certificateApiSecretTitle").replace("{key}", keyId || "");
|
||||
$("certificate-api-secret-wrap").hidden = !token;
|
||||
if (token) $("certificate-api-secret-wrap").scrollIntoView?.({ block: "nearest", behavior: "smooth" });
|
||||
}
|
||||
function resetCertificateApiForm() {
|
||||
function closeEditor() {
|
||||
certificateApiEditingKey = null;
|
||||
$("certificate-api-key-id").value = "";
|
||||
$("certificate-api-key-id").readOnly = false;
|
||||
$("certificate-api-comment").value = "";
|
||||
$("certificate-api-certificate-ids").value = "";
|
||||
$("certificate-api-allow-deploy").checked = false;
|
||||
$("certificate-api-token").value = "";
|
||||
$("certificate-api-token-field").hidden = false;
|
||||
$("certificate-api-edit-note").hidden = true;
|
||||
$("certificate-api-cancel-edit").hidden = true;
|
||||
const submit = $("certificate-api-save");
|
||||
submit.dataset.i18n = "certificateApiRotate";
|
||||
submit.textContent = t("certificateApiRotate");
|
||||
const form = $("certificate-api-form");
|
||||
form.hidden = true;
|
||||
$("certificate-api-card").insertBefore(form, $("certificate-api-credentials"));
|
||||
$("certificate-api-new").disabled = false;
|
||||
certificateApiExample();
|
||||
}
|
||||
function beginCertificateApiEdit(credential) {
|
||||
certificateApiEditingKey = credential.key_id;
|
||||
certificateApiDetailsKey = credential.key_id;
|
||||
$("certificate-api-key-id").value = credential.key_id;
|
||||
$("certificate-api-key-id").readOnly = true;
|
||||
$("certificate-api-comment").value = credential.comment || "";
|
||||
$("certificate-api-certificate-ids").value = (credential.certificate_ids || []).join("\n");
|
||||
$("certificate-api-allow-deploy").checked = !!credential.allow_deploy;
|
||||
function openEditor(credential = null) {
|
||||
clearCertificateApiSecret();
|
||||
certificateApiEditingKey = credential?.key_id || null;
|
||||
const editing = !!credential, form = $("certificate-api-form");
|
||||
$("certificate-api-editor-title").textContent = editing ? t("certificateApiEditTitle").replace("{key}", credential.key_id) : t("certificateApiNewTitle");
|
||||
$("certificate-api-key-id").value = credential?.key_id || "";
|
||||
$("certificate-api-key-id").readOnly = editing;
|
||||
$("certificate-api-key-id").closest("label").hidden = editing;
|
||||
$("certificate-api-comment").value = credential?.comment || "";
|
||||
$("certificate-api-allow-deploy").checked = !!credential?.allow_deploy;
|
||||
$("certificate-api-mode-reload").checked = !credential?.allow_deploy;
|
||||
$("certificate-api-token").value = "";
|
||||
$("certificate-api-token-field").hidden = true;
|
||||
$("certificate-api-edit-note").hidden = false;
|
||||
$("certificate-api-cancel-edit").hidden = false;
|
||||
const submit = $("certificate-api-save");
|
||||
submit.dataset.i18n = "certificateApiSave";
|
||||
submit.textContent = t("certificateApiSave");
|
||||
$("certificate-api-token-field").hidden = editing;
|
||||
$("certificate-api-token-field").open = false;
|
||||
$("certificate-api-edit-note").hidden = !editing;
|
||||
const ids = credential?.certificate_ids || [], legacy = ids.includes("*");
|
||||
$("certificate-api-legacy-note").textContent = legacy ? t("certificateApiLegacyWildcard") : "";
|
||||
$("certificate-api-legacy-note").hidden = !legacy;
|
||||
createPicker(ids.filter(id => id !== "*"));
|
||||
syncCertificateHelp();
|
||||
$("certificate-api-save").textContent = t(editing ? "certificateApiSave" : "certificateApiCreate");
|
||||
const anchor = editing ? $("certificate-api-credentials").querySelector(`[data-key-id="${CSS.escape(credential.key_id)}"]`) : null;
|
||||
if (anchor) anchor.append(form); else $("certificate-api-card").insertBefore(form, $("certificate-api-credentials"));
|
||||
form.hidden = false;
|
||||
$("certificate-api-new").disabled = !editing;
|
||||
certificateApiExample();
|
||||
$("certificate-api-form").scrollIntoView?.({ block: "start", behavior: "smooth" });
|
||||
$("certificate-api-comment").focus?.();
|
||||
form.scrollIntoView?.({ block: "nearest", behavior: "smooth" });
|
||||
(editing ? $("certificate-api-comment") : $("certificate-api-key-id")).focus?.();
|
||||
}
|
||||
function setCertificateApiCredential(credential) {
|
||||
if (!certificateApiState) return;
|
||||
@@ -60,42 +106,28 @@
|
||||
certificateApiState.configured = certificateApiState.credentials.length > 0;
|
||||
}
|
||||
function certificateApiExample() {
|
||||
const key = $("certificate-api-key-id").value.trim() || certificateApiCredentials()[0]?.key_id || "certbot-main";
|
||||
const enteredIds = $("certificate-api-certificate-ids").value.split(/[\n,]+/).map(value => value.trim()).filter(Boolean);
|
||||
const selected = enteredIds[0] || certificateApiCredentials()[0]?.certificate_ids?.find(value => value !== "*") || "CERTIFICATE_ID";
|
||||
const reload = `curl --fail --show-error --request POST \
|
||||
--header 'Authorization: Bearer $RUSTPROXY_CERT_TOKEN' \
|
||||
--header 'X-RustProxy-Certificate-Key: ${key}' \
|
||||
const editing = !$("certificate-api-form").hidden;
|
||||
const current = certificateApiCredentials()[0];
|
||||
const key = (editing && $("certificate-api-key-id").value.trim()) || current?.key_id || "opnsense-acme";
|
||||
const ids = editing ? selectedIds() : (current?.certificate_ids || []).filter(id => id !== "*");
|
||||
const selected = ids[0] || "CERTIFICATE_ID", deploy = editing ? deployMode() : !!current?.allow_deploy;
|
||||
const reload = `curl --fail --show-error --request POST \\
|
||||
--header "Authorization: Bearer $RUSTPROXY_CERT_TOKEN" \\
|
||||
--header 'X-RustProxy-Certificate-Key: ${key}' \\
|
||||
${location.origin}/api/certificates/${selected}/reload`;
|
||||
if (!$("certificate-api-allow-deploy").checked) {
|
||||
$("certificate-api-curl").textContent = reload;
|
||||
return;
|
||||
}
|
||||
$("certificate-api-curl").textContent = `${reload}
|
||||
$("certificate-api-curl").textContent = deploy ? `${reload}
|
||||
|
||||
# Optional higher-privilege deploy for the same allowlisted certificate IDs:
|
||||
curl --fail --show-error --request POST \
|
||||
--header 'Authorization: Bearer $RUSTPROXY_CERT_TOKEN' \
|
||||
--header 'X-RustProxy-Certificate-Key: ${key}' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data @deploy.json \
|
||||
${location.origin}/api/certificates/deploy`;
|
||||
curl --fail --show-error --request POST \\
|
||||
--header "Authorization: Bearer $RUSTPROXY_CERT_TOKEN" \\
|
||||
--header 'X-RustProxy-Certificate-Key: ${key}' \\
|
||||
--header 'Content-Type: application/json' \\
|
||||
--data '{"certificate_id":"${selected}","cert_pem":"…","key_pem":"…"}' \\
|
||||
${location.origin}/api/certificates/deploy` : reload;
|
||||
}
|
||||
function certificateApiDetailNode(credential) {
|
||||
const detail = el("div", undefined, "certificate-api-details");
|
||||
const item = (label, value) => {
|
||||
const line = el("div", undefined, "certificate-api-detail-line");
|
||||
line.append(el("span", `${label}:`, "fine"), el("strong", String(value), "mono"));
|
||||
detail.append(line);
|
||||
};
|
||||
item(t("certificateApiKeyId"), credential.key_id);
|
||||
item(t("certificateApiComment"), credential.comment || "-");
|
||||
item(t("certificateApiCreatedAt"), formatDateTime(Number(credential.created_at) * 1000));
|
||||
item(t("certificateApiLastUsed"), credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed"));
|
||||
item(t("certificateApiPermissions"), credential.allow_deploy ? t("certificateApiScopeDeployReload") : t("certificateApiScopeReloadOnly"));
|
||||
item(t("certificateApiCertificateIds"), (credential.certificate_ids || []).join(", "));
|
||||
item(t("certificateApiTokenLabel"), t("certificateApiTokenHidden"));
|
||||
return detail;
|
||||
function certificateChip(id) {
|
||||
const cert = certificateById(id), chip = el("span", id, `certificate-api-chip${cert ? "" : " is-new"}${cert?.issuer ? " is-managed" : ""}`);
|
||||
chip.title = id === "*" ? t("certificateApiLegacyWildcardShort") : cert ? certificateHosts(cert).join(", ") || id : t("certificateApiCertificateNew");
|
||||
return chip;
|
||||
}
|
||||
function renderCertificateApi() {
|
||||
const state = certificateApiState, target = $("certificate-api-credentials");
|
||||
@@ -103,75 +135,67 @@ curl --fail --show-error --request POST \
|
||||
const credentials = certificateApiCredentials(), max = Number(state.max_credentials) || 32;
|
||||
$("certificate-api-status").textContent = credentials.length
|
||||
? t("certificateApiConfiguredCount").replace("{count}", credentials.length).replace("{max}", max)
|
||||
: t("certificateApiDisabled");
|
||||
: t("certificateApiEmpty");
|
||||
$("certificate-api-revoke-all").disabled = !credentials.length;
|
||||
if (target) {
|
||||
target.replaceChildren();
|
||||
for (const credential of credentials) {
|
||||
const container = el("div", undefined, "certificate-api-credential-item");
|
||||
const row = el("div", undefined, "certificate-api-credential-row");
|
||||
const info = el("div", undefined, "certificate-api-credential-info");
|
||||
info.append(el("b", credential.key_id || "-", "mono"));
|
||||
if (credential.comment) info.append(el("span", credential.comment, "fine"));
|
||||
const scope = credential.allow_deploy ? t("certificateApiScopeDeployReload") : t("certificateApiScopeReloadOnly");
|
||||
const ids = Array.isArray(credential.certificate_ids) ? credential.certificate_ids.join(", ") : "-";
|
||||
info.append(el("span", `${scope} · ${t("certificateApiAllowedIds")}: ${ids}`, "fine mono"));
|
||||
const lastUsed = credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed");
|
||||
info.append(el("span", `${t("certificateApiLastUsed")}: ${lastUsed}`, "fine"));
|
||||
const actions = el("div", undefined, "certificate-api-row-actions");
|
||||
const path = `/api/certificate-api/${encodeURIComponent(credential.key_id)}`;
|
||||
const preview = action(t(certificateApiDetailsKey === credential.key_id ? "certificateApiHide" : "certificateApiView"), async () => {
|
||||
if (certificateApiDetailsKey === credential.key_id) { certificateApiDetailsKey = null; renderCertificateApi(); return; }
|
||||
preview.disabled = true;
|
||||
clearCertificateApiSecret();
|
||||
try {
|
||||
const data = await api(path);
|
||||
setCertificateApiCredential(data.credential);
|
||||
certificateApiDetailsKey = credential.key_id;
|
||||
renderCertificateApi();
|
||||
} catch (error) { toast(error.message, true); preview.disabled = false; }
|
||||
});
|
||||
const edit = action(t("certificateApiEdit"), async () => {
|
||||
edit.disabled = true;
|
||||
clearCertificateApiSecret();
|
||||
try {
|
||||
const data = await api(path);
|
||||
setCertificateApiCredential(data.credential);
|
||||
beginCertificateApiEdit(data.credential);
|
||||
renderCertificateApi();
|
||||
} catch (error) { toast(error.message, true); edit.disabled = false; }
|
||||
});
|
||||
const regenerate = action(t("certificateApiRegenerate"), async () => {
|
||||
if (!await appConfirm(t("certificateApiRegenerateConfirm").replace("{key}", credential.key_id), { danger: true })) return;
|
||||
regenerate.disabled = true;
|
||||
clearCertificateApiSecret();
|
||||
try {
|
||||
const data = await api(`${path}/regenerate`, { method: "POST" });
|
||||
setCertificateApiCredential(data.credential);
|
||||
showCertificateApiSecret(data.token || "");
|
||||
renderCertificateApi();
|
||||
toast(t("certificateApiRegenerated"));
|
||||
} catch (error) { toast(error.message, true); regenerate.disabled = false; }
|
||||
});
|
||||
const remove = action(t("certificateApiRevoke"), async () => {
|
||||
if (!await appConfirm(t("certificateApiRevokeOneConfirm").replace("{key}", credential.key_id), { danger: true })) return;
|
||||
remove.disabled = true;
|
||||
try {
|
||||
await api(path, { method: "DELETE" });
|
||||
certificateApiState.credentials = certificateApiCredentials().filter(value => value.key_id !== credential.key_id);
|
||||
certificateApiState.configured = certificateApiState.credentials.length > 0;
|
||||
if (certificateApiEditingKey === credential.key_id) resetCertificateApiForm();
|
||||
if (certificateApiDetailsKey === credential.key_id) certificateApiDetailsKey = null;
|
||||
clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
|
||||
} catch (error) { toast(error.message, true); remove.disabled = false; }
|
||||
});
|
||||
remove.classList.add("danger");
|
||||
actions.append(preview, edit, regenerate, remove);
|
||||
row.append(info, actions);
|
||||
container.append(row);
|
||||
if (certificateApiDetailsKey === credential.key_id) container.append(certificateApiDetailNode(credential));
|
||||
target.append(container);
|
||||
}
|
||||
$("certificate-api-new").disabled = credentials.length >= max || ($("certificate-api-form").hidden === false && !certificateApiEditingKey);
|
||||
const form = $("certificate-api-form"), editingForm = !form.hidden && certificateApiEditingKey;
|
||||
if (editingForm) $("certificate-api-card").insertBefore(form, target);
|
||||
target.replaceChildren();
|
||||
for (const credential of credentials) {
|
||||
const container = el("div", undefined, "certificate-api-credential-item"); container.dataset.keyId = credential.key_id;
|
||||
const row = el("div", undefined, "certificate-api-credential-row");
|
||||
const info = el("div", undefined, "certificate-api-credential-info");
|
||||
const title = el("div", undefined, "certificate-api-credential-title");
|
||||
title.append(el("b", credential.key_id || "-", "mono"));
|
||||
title.append(el("span", t(credential.allow_deploy ? "certificateApiScopeDeployReload" : "certificateApiScopeReloadOnly"), `pill ${credential.allow_deploy ? "warn" : "live"}`));
|
||||
if (credential.comment) title.append(el("span", credential.comment, "fine"));
|
||||
const chips = el("div", undefined, "certificate-api-chips");
|
||||
const ids = Array.isArray(credential.certificate_ids) ? credential.certificate_ids : [];
|
||||
if (ids.length) ids.forEach(id => chips.append(certificateChip(id))); else chips.append(el("span", "-", "fine"));
|
||||
const created = credential.created_at ? formatDateTime(Number(credential.created_at) * 1000) : "-";
|
||||
const lastUsed = credential.last_used_at ? formatDateTime(Number(credential.last_used_at) * 1000) : t("certificateApiNeverUsed");
|
||||
info.append(title, chips, el("span", `${t("certificateApiCreatedAt")}: ${created} · ${t("certificateApiLastUsed")}: ${lastUsed}`, "fine"));
|
||||
if (ids.includes("*")) info.append(el("span", t("certificateApiLegacyWildcardShort"), "fine certificate-api-legacy"));
|
||||
const actions = el("div", undefined, "certificate-api-row-actions");
|
||||
const path = `/api/certificate-api/${encodeURIComponent(credential.key_id)}`;
|
||||
const edit = action(t("certificateApiEdit"), async () => {
|
||||
if (certificateApiEditingKey === credential.key_id && !$("certificate-api-form").hidden) { closeEditor(); return; }
|
||||
edit.disabled = true;
|
||||
try {
|
||||
const data = await api(path);
|
||||
setCertificateApiCredential(data.credential);
|
||||
renderCertificateApi();
|
||||
openEditor(data.credential);
|
||||
} catch (error) { toast(error.message, true); edit.disabled = false; }
|
||||
});
|
||||
const regenerate = action(t("certificateApiRegenerate"), async () => {
|
||||
if (!await appConfirm(t("certificateApiRegenerateConfirm").replace("{key}", credential.key_id), { danger: true })) return;
|
||||
regenerate.disabled = true;
|
||||
try {
|
||||
const data = await api(`${path}/regenerate`, { method: "POST" });
|
||||
setCertificateApiCredential(data.credential);
|
||||
closeEditor(); renderCertificateApi();
|
||||
showCertificateApiSecret(data.token || "", credential.key_id);
|
||||
toast(t("certificateApiRegenerated"));
|
||||
} catch (error) { toast(error.message, true); regenerate.disabled = false; }
|
||||
});
|
||||
const remove = action(t("certificateApiRevoke"), async () => {
|
||||
if (!await appConfirm(t("certificateApiRevokeOneConfirm").replace("{key}", credential.key_id), { danger: true })) return;
|
||||
remove.disabled = true;
|
||||
try {
|
||||
await api(path, { method: "DELETE" });
|
||||
certificateApiState.credentials = certificateApiCredentials().filter(value => value.key_id !== credential.key_id);
|
||||
certificateApiState.configured = certificateApiState.credentials.length > 0;
|
||||
if (certificateApiEditingKey === credential.key_id) closeEditor();
|
||||
clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
|
||||
} catch (error) { toast(error.message, true); remove.disabled = false; }
|
||||
});
|
||||
remove.classList.add("danger");
|
||||
actions.append(edit, regenerate, remove);
|
||||
row.append(info, actions);
|
||||
container.append(row);
|
||||
target.append(container);
|
||||
if (editingForm && certificateApiEditingKey === credential.key_id) container.append(form);
|
||||
}
|
||||
certificateApiExample();
|
||||
}
|
||||
@@ -189,16 +213,18 @@ curl --fail --show-error --request POST \
|
||||
try {
|
||||
const keyId = $("certificate-api-key-id").value.trim();
|
||||
const comment = $("certificate-api-comment").value.trim();
|
||||
const certificateIds = $("certificate-api-certificate-ids").value.split(/[\n,]+/).map(value => value.trim()).filter(Boolean);
|
||||
if (!certificateIds.length) throw fieldError($("certificate-api-certificate-ids"), t("certificateApiCertificateIdsRequired"));
|
||||
const allowDeploy = $("certificate-api-allow-deploy").checked;
|
||||
const certificateIds = selectedIds();
|
||||
const pickerNode = $("certificate-api-certificates");
|
||||
if (!certificateApiEditingKey && keyId && !/^[A-Za-z0-9_-]{3,64}$/.test(keyId)) throw fieldError($("certificate-api-key-id"), t("certificate_api.invalid_key_id"));
|
||||
if (!certificateIds.length) throw fieldError(pickerNode, t("certificateApiCertificateIdsRequired"));
|
||||
if (certificateIds.length > MAX_IDS) throw fieldError(pickerNode, t("certificateApiCertificateIdsTooMany"));
|
||||
const allowDeploy = deployMode();
|
||||
if (certificateApiEditingKey) {
|
||||
const result = await api(`/api/certificate-api/${encodeURIComponent(certificateApiEditingKey)}`, {
|
||||
method: "PATCH", body: JSON.stringify({ comment, certificate_ids: certificateIds, allow_deploy: allowDeploy })
|
||||
});
|
||||
setCertificateApiCredential(result.credential);
|
||||
resetCertificateApiForm();
|
||||
renderCertificateApi();
|
||||
closeEditor(); renderCertificateApi();
|
||||
toast(t("certificateApiSaved"));
|
||||
} else {
|
||||
const token = $("certificate-api-token").value.trim();
|
||||
@@ -206,37 +232,39 @@ curl --fail --show-error --request POST \
|
||||
method: "PUT", body: JSON.stringify({ key_id: keyId || null, token: token || null, comment, certificate_ids: certificateIds, allow_deploy: allowDeploy })
|
||||
});
|
||||
certificateApiState = { ...result }; delete certificateApiState.token; delete certificateApiState.credential;
|
||||
resetCertificateApiForm();
|
||||
showCertificateApiSecret(result.token || "");
|
||||
renderCertificateApi();
|
||||
closeEditor(); renderCertificateApi();
|
||||
showCertificateApiSecret(result.token || "", result.credential?.key_id || keyId);
|
||||
toast(t("certificateApiRotated"));
|
||||
}
|
||||
} catch (error) { showFieldError(error, $("certificate-api-form")); toast(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
$("certificate-api-cancel-edit").addEventListener("click", resetCertificateApiForm);
|
||||
$("certificate-api-new").addEventListener("click", () => openEditor(null));
|
||||
$("certificate-api-cancel-edit").addEventListener("click", () => { closeEditor(); renderCertificateApi(); });
|
||||
$("certificate-api-secret-copy").addEventListener("click", async () => {
|
||||
const value = $("certificate-api-secret").textContent;
|
||||
try { await navigator.clipboard.writeText(value); toast(t("copied")); }
|
||||
catch { const range = document.createRange(); range.selectNodeContents($("certificate-api-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
|
||||
});
|
||||
$("certificate-api-revoke-all").addEventListener("click", async () => {
|
||||
if (!await appConfirm(t("certificateApiRevokeAllConfirm"), { danger: true })) return;
|
||||
const button = $("certificate-api-revoke-all"); button.disabled = true;
|
||||
try {
|
||||
await api("/api/certificate-api", { method: "DELETE" });
|
||||
certificateApiState = { configured: false, credentials: [], max_credentials: certificateApiState?.max_credentials || 32, scopes: certificateApiState?.scopes || [] };
|
||||
certificateApiDetailsKey = null;
|
||||
resetCertificateApiForm(); clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
|
||||
closeEditor(); clearCertificateApiSecret(); renderCertificateApi(); toast(t("certificateApiRevoked"));
|
||||
} catch (error) { toast(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
$("certificate-api-key-id").addEventListener("input", certificateApiExample);
|
||||
$("certificate-api-certificate-ids").addEventListener("input", certificateApiExample);
|
||||
$("certificate-api-allow-deploy").addEventListener("change", certificateApiExample);
|
||||
for (const id of ["certificate-api-allow-deploy", "certificate-api-mode-reload"]) $(id).addEventListener("change", () => { syncCertificateHelp(); certificateApiExample(); });
|
||||
window.rustProxyCertificateApi = {
|
||||
render: renderCertificateApi,
|
||||
load: loadCertificateApi,
|
||||
reset() {
|
||||
certificateApiState = null;
|
||||
certificateApiLoading = false;
|
||||
certificateApiDetailsKey = null;
|
||||
resetCertificateApiForm();
|
||||
closeEditor();
|
||||
clearCertificateApiSecret();
|
||||
$("certificate-api-credentials").replaceChildren();
|
||||
}
|
||||
|
||||
@@ -79,6 +79,9 @@
|
||||
--traffic-h2: var(--chart-secondary);
|
||||
--traffic-h3: var(--chart-tertiary);
|
||||
--ui-scale: 1;
|
||||
--rp-vw: calc(1vw / var(--ui-scale, 1));
|
||||
--rp-vh: calc(1vh / var(--ui-scale, 1));
|
||||
--rp-dvh: calc(1dvh / var(--ui-scale, 1));
|
||||
--ui-field-font-size: 12px;
|
||||
--ui-field-pad-y: 6px;
|
||||
--ui-field-pad-x: 8px;
|
||||
|
||||
@@ -153,7 +153,7 @@ html[data-interface-icons="true"] .nav>span:first-of-type,
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: calc(clamp(32px, 3.6vw, 52px));
|
||||
font-size: calc(clamp(32px, calc(3.6 * var(--rp-vw)), 52px));
|
||||
line-height: 1.1;
|
||||
font-weight: 520;
|
||||
letter-spacing: -2px;
|
||||
@@ -566,7 +566,7 @@ button.is-saving {
|
||||
position: fixed;
|
||||
bottom: 26px;
|
||||
right: 26px;
|
||||
max-width: calc(min(580px, 100vw - 40px));
|
||||
max-width: calc(min(580px, calc(100 * var(--rp-vw)) - 40px));
|
||||
background: var(--toast-bg);
|
||||
color: var(--toast-text);
|
||||
border: 1px solid var(--toast-line);
|
||||
@@ -759,7 +759,7 @@ progress::-moz-progress-bar {
|
||||
|
||||
#pool-search,
|
||||
#bo-search {
|
||||
width: calc(min(250px, 30vw));
|
||||
width: calc(min(250px, calc(30 * var(--rp-vw))));
|
||||
min-width: 170px;
|
||||
}
|
||||
|
||||
@@ -769,7 +769,7 @@ progress::-moz-progress-bar {
|
||||
inset: auto 18px 18px auto;
|
||||
margin: 0;
|
||||
width: max-content;
|
||||
max-width: calc(min(520px, 100vw - 28px));
|
||||
max-width: calc(min(520px, calc(100 * var(--rp-vw)) - 28px));
|
||||
padding: 12px 16px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
@@ -796,11 +796,11 @@ progress::-moz-progress-bar {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0;
|
||||
max-width: calc(100vw - 24px);
|
||||
max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
|
||||
box-shadow: 0 18px 70px var(--shadow-strong);
|
||||
border-radius: var(--rp-radius-surface, 7px);
|
||||
width: calc(min(1040px, 100vw - 24px));
|
||||
max-height: calc(100dvh - 28px);
|
||||
width: calc((calc(min(1040px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -809,11 +809,11 @@ progress::-moz-progress-bar {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0;
|
||||
max-width: calc(100vw - 24px);
|
||||
max-height: calc(100dvh - 28px);
|
||||
max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
|
||||
box-shadow: 0 18px 70px var(--shadow-strong);
|
||||
border-radius: var(--rp-radius-surface, 7px);
|
||||
width: 1180px;
|
||||
width: calc((1180px) / var(--ui-scale, 1));
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
@@ -822,11 +822,11 @@ progress::-moz-progress-bar {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0;
|
||||
max-width: calc(100vw - 24px);
|
||||
max-height: calc(100dvh - 28px);
|
||||
max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
|
||||
box-shadow: 0 18px 70px var(--shadow-strong);
|
||||
border-radius: var(--rp-radius-surface, 7px);
|
||||
width: 960px;
|
||||
width: calc((960px) / var(--ui-scale, 1));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@@ -923,7 +923,7 @@ progress::-moz-progress-bar {
|
||||
}
|
||||
|
||||
#cache-object-scroll {
|
||||
max-height: calc(min(49vh, 520px));
|
||||
max-height: calc(min(calc(49 * var(--rp-vh)), 520px));
|
||||
overflow: auto;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
@@ -965,8 +965,8 @@ dialog .vh-form,
|
||||
}
|
||||
|
||||
#location-help-dialog {
|
||||
width: calc(min(760px, 100vw - 28px));
|
||||
max-height: calc(min(82vh, 760px));
|
||||
width: calc((calc(min(760px, 100vw - 28px))) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(min(82vh, 760px))) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
#location-help-body {
|
||||
@@ -1041,7 +1041,7 @@ dialog .vh-form,
|
||||
#vhost-search,
|
||||
#web-service-search,
|
||||
#stream-search {
|
||||
width: calc(min(260px, 32vw));
|
||||
width: calc(min(260px, calc(32 * var(--rp-vw))));
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
@@ -1324,7 +1324,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
|
||||
z-index: 40;
|
||||
top: calc(100% + 7px);
|
||||
right: 0;
|
||||
width: calc(min(360px, 100vw - 44px));
|
||||
width: calc(min(360px, calc(100 * var(--rp-vw)) - 44px));
|
||||
padding: 10px 11px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--rp-radius-surface, 6px);
|
||||
@@ -1348,8 +1348,8 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon {
|
||||
}
|
||||
|
||||
.about-dialog {
|
||||
width: calc(min(640px, 100vw - 24px));
|
||||
max-height: calc(100vh - 24px);
|
||||
width: calc((calc(min(640px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100vh - 24px)) / var(--ui-scale, 1));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ html.app-loading .shell {
|
||||
#certificate-api-cancel-edit[hidden],
|
||||
#certificate-api-edit-note[hidden],
|
||||
#certificate-api-token-field[hidden],
|
||||
#certificate-api-form[hidden],
|
||||
#certificate-api-secret-wrap[hidden],
|
||||
#certificate-api-legacy-note[hidden],
|
||||
html:not(.app-loading) .app-startup,
|
||||
html.app-startup-failed .app-startup-message,
|
||||
html.app-startup-failed .app-startup-spinner,
|
||||
@@ -247,7 +250,7 @@ nav {
|
||||
}
|
||||
|
||||
.app-health-dialog {
|
||||
width: min(620px, calc(100vw - 24px));
|
||||
width: calc((min(620px, calc(100vw - 24px))) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.app-health-card {
|
||||
@@ -403,7 +406,7 @@ main {
|
||||
}
|
||||
|
||||
.login-section h1 {
|
||||
font-size: calc(clamp(42px, 5vw, 68px));
|
||||
font-size: calc(clamp(42px, calc(5 * var(--rp-vw)), 68px));
|
||||
letter-spacing: -3px;
|
||||
max-width: 640px;
|
||||
}
|
||||
@@ -487,7 +490,7 @@ main {
|
||||
}
|
||||
|
||||
.app-confirm-dialog {
|
||||
width: calc(min(520px, 100vw - 28px));
|
||||
width: calc((calc(min(520px, 100vw - 28px))) / var(--ui-scale, 1));
|
||||
max-width: none;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
@@ -528,7 +531,7 @@ main {
|
||||
}
|
||||
|
||||
.auth-page {
|
||||
min-height: 100vh;
|
||||
min-height: calc(100 * var(--rp-vh));
|
||||
}
|
||||
|
||||
.auth-top {
|
||||
@@ -636,7 +639,7 @@ main {
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
z-index: 900;
|
||||
width: calc(min(330px, 100vw - 28px));
|
||||
width: calc(min(330px, calc(100 * var(--rp-vw)) - 28px));
|
||||
padding: 0;
|
||||
border: 1px solid var(--border-hover);
|
||||
border-radius: var(--rp-radius-surface, 0);
|
||||
@@ -706,7 +709,7 @@ main {
|
||||
.draft-dock-list {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
max-height: calc(min(42vh, 360px));
|
||||
max-height: calc(min(calc(42 * var(--rp-vh)), 360px));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ html[data-theme=cream] :is(.card, .stat, dialog) {
|
||||
font-weight: 450;
|
||||
letter-spacing: -1px;
|
||||
line-height: 1.3;
|
||||
font-size: calc(clamp(20px, 1.8vw, 26px));
|
||||
font-size: calc(clamp(20px, calc(1.8 * var(--rp-vw)), 26px));
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
@@ -1638,7 +1638,7 @@ html[data-chart-style] :is(#workspace, dialog) svg polyline {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
max-height: calc(min(30vh, 240px));
|
||||
max-height: calc(min(calc(30 * var(--rp-vh)), 240px));
|
||||
overflow-y: auto;
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
@@ -2349,8 +2349,8 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty
|
||||
}
|
||||
|
||||
.overview-presets-dialog {
|
||||
width: calc(min(730px, 100vw - 24px));
|
||||
max-height: calc(100dvh - 24px);
|
||||
width: calc((calc(min(730px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 24px)) / var(--ui-scale, 1));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
@@ -2887,7 +2887,7 @@ html[data-table-density=compact] .bo-stack { margin-top: 3px; }
|
||||
.docker-load-name { overflow: hidden; color: var(--text); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.docker-load-bar { display: grid; grid-template-columns: auto 1fr; align-items: center; gap: 4px; min-width: 0; }
|
||||
.docker-load-bar>small { color: var(--muted); font: 9px var(--mono); }
|
||||
.docker-load-bar>i { display: block; height: 5px; overflow: hidden; border-radius: 3px; background: var(--line); }
|
||||
.docker-load-bar>i { display: block; height: 5px; overflow: hidden; border-radius: var(--rp-progress-radius, 0px); background: var(--line); }
|
||||
.docker-load-bar>i>b { display: block; height: 100%; border-radius: inherit; background: var(--green); }
|
||||
.docker-load-bar>i.is-warn>b { background: var(--accent); }
|
||||
.docker-load-bar>i.is-high>b { background: var(--red); }
|
||||
|
||||
@@ -1562,7 +1562,7 @@ html.app-loading,
|
||||
.vhost-backend-popup {
|
||||
position: fixed;
|
||||
z-index: 1600;
|
||||
max-height: calc(min(360px, 100dvh - 24px));
|
||||
max-height: calc(min(360px, calc(100 * var(--rp-dvh)) - 24px));
|
||||
overflow: auto;
|
||||
padding: 12px;
|
||||
background: var(--panel);
|
||||
|
||||
@@ -367,7 +367,7 @@
|
||||
}
|
||||
|
||||
.docker-toolbar input[type=search] {
|
||||
width: calc(min(280px, 38vw));
|
||||
width: calc(min(280px, calc(38 * var(--rp-vw))));
|
||||
box-sizing: border-box;
|
||||
height: var(--toolbar-control-height);
|
||||
min-height: var(--toolbar-control-height);
|
||||
@@ -528,7 +528,7 @@
|
||||
}
|
||||
|
||||
.audit-dialog .table-scroll {
|
||||
max-height: calc(min(68dvh, 680px));
|
||||
max-height: calc((calc(min(68dvh, 680px))) / var(--ui-scale, 1));
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
@@ -980,19 +980,6 @@
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.certificate-api-details {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.certificate-api-detail-line {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.certificate-api-credential-row {
|
||||
display: flex;
|
||||
@@ -1508,7 +1495,7 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
.docker-system-item { display: grid; gap: 2px; min-width: 0; padding: 7px 9px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 8px); background: var(--panel); }
|
||||
.docker-system-item>span { color: var(--muted); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.docker-system-item>strong { font: 600 12px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.docker-system-meter { display: block; height: 4px; margin-top: 3px; overflow: hidden; border-radius: 3px; background: var(--line); }
|
||||
.docker-system-meter { display: block; height: 4px; margin-top: 3px; overflow: hidden; border-radius: var(--rp-progress-radius, 0px); background: var(--line); }
|
||||
.docker-system-meter>b { display: block; height: 100%; background: var(--green); border-radius: inherit; }
|
||||
.docker-system-meter.is-warn>b { background: var(--accent); }
|
||||
.docker-system-meter.is-high>b { background: var(--red); }
|
||||
@@ -1535,8 +1522,376 @@ html[data-dashboard-density=normal] #panel-overview .stat>span,
|
||||
.docker-alert-editor>summary { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; cursor: pointer; font-weight: 600; font-size: 13px; }
|
||||
.docker-alert-editor>summary small { font-weight: 400; }
|
||||
.docker-alert-grid { margin-top: 10px; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); }
|
||||
.docker-agent-test-row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; margin: 0 0 10px; }
|
||||
.docker-agent-test-result.is-ok { color: var(--green); }
|
||||
.docker-agent-test-result.is-error { color: var(--red); overflow-wrap: anywhere; }
|
||||
.docker-agent-test-wrap { position: relative; display: inline-flex; }
|
||||
.docker-agent-test-wrap>.docker-agent-test { min-height: 32px; box-sizing: border-box; }
|
||||
.docker-agent-test-result { position: absolute; top: calc(100% + 8px); right: 0; z-index: 30; width: max-content; max-width: min(360px, calc(80 * var(--rp-vw))); padding: 8px 11px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel); box-shadow: 0 8px 24px var(--shadow-mid); font-size: 12px; line-height: 1.4; color: var(--text); overflow-wrap: anywhere; cursor: pointer; }
|
||||
.docker-agent-test-result::before { content: ""; position: absolute; top: -6px; right: 18px; width: 10px; height: 10px; background: inherit; border-left: 1px solid var(--line); border-top: 1px solid var(--line); transform: rotate(45deg); }
|
||||
.docker-agent-test-result[hidden] { display: none; }
|
||||
.docker-agent-test-result.is-running { color: var(--muted); }
|
||||
.docker-agent-test-result.is-ok { border-color: var(--green); color: var(--green); }
|
||||
.docker-agent-test-result.is-error { border-color: var(--red); color: var(--red); }
|
||||
.docker-label-badge { align-self: center; }
|
||||
.docker-container-state { display: inline-flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
|
||||
.docker-container-state { display: flex; flex-wrap: wrap; gap: 5px 6px; align-items: center; margin-top: 2px; }
|
||||
.docker-container-state .docker-container-pill { font-size: 11px; }
|
||||
.docker-container-state .docker-container-pill.muted { color: var(--muted); }
|
||||
.docker-container-state .docker-container-uptime { font-weight: 400; opacity: .8; }
|
||||
.docker-container-state .docker-container-chip { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); font-size: 11px; line-height: 1.5; color: var(--text); background: var(--panel); }
|
||||
.docker-container-state .docker-container-chip-label { color: var(--muted); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.docker-container-state .docker-container-chip>b { font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.docker-container-state .docker-container-chip-bar { position: relative; width: 38px; height: 4px; border-radius: var(--rp-progress-radius, 0px); background: var(--line); overflow: hidden; }
|
||||
.docker-container-state .docker-container-chip-bar>i { position: absolute; inset: 0 auto 0 0; border-radius: var(--rp-progress-radius, 0px); background: var(--green); }
|
||||
.docker-container-state .docker-container-chip.is-warn { border-color: var(--warn-line); }
|
||||
.docker-container-state .docker-container-chip.is-warn .docker-container-chip-bar>i { background: var(--accent); }
|
||||
.docker-container-state .docker-container-chip.is-warn>b { color: var(--accent); }
|
||||
.docker-container-state .docker-container-chip.is-danger { border-color: var(--danger-line-strong); }
|
||||
.docker-container-state .docker-container-chip.is-danger .docker-container-chip-bar>i { background: var(--red); }
|
||||
.docker-container-state .docker-container-chip.is-danger>b { color: var(--red); }
|
||||
.docker-target-hint { display: block; margin-top: 4px; }
|
||||
.docker-label-help { display: flex; gap: 6px; align-items: flex-start; }
|
||||
.docker-label-help>span { flex: 1 1 auto; min-width: 0; }
|
||||
.docker-label-info { flex: 0 0 auto; width: 20px; height: 20px; min-height: 0; padding: 0; border-radius: var(--rp-radius-control, 0px); border: 1px solid var(--line); background: var(--panel); color: var(--accent); font-size: 12px; font-weight: 700; line-height: 1; cursor: pointer; }
|
||||
.docker-label-info:hover { border-color: var(--accent); }
|
||||
#location-help-body .docker-label-table { width: 100%; table-layout: auto; border-collapse: collapse; font-size: 13px; }
|
||||
#location-help-body .docker-label-table td { padding: 5px 8px; border-bottom: 1px solid var(--line); vertical-align: top; white-space: normal; overflow: visible; text-overflow: clip; max-width: none; font-family: inherit; line-height: 1.45; }
|
||||
#location-help-body .docker-label-table td:first-child { width: 1%; white-space: nowrap; }
|
||||
.docker-label-example-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 12px; }
|
||||
.docker-label-example-head>h3 { margin: 0; }
|
||||
.docker-label-example { margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--bg, transparent); overflow: auto; font-size: 12px; line-height: 1.5; }
|
||||
.docker-certificate-hint.is-warn { color: var(--accent); }
|
||||
|
||||
.certificate-api-card>.card-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.certificate-api-heading-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.certificate-api-secret { margin-top: 12px; padding: 12px; border: 1px solid var(--green); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
|
||||
.certificate-api-secret-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 8px; }
|
||||
.certificate-api-secret pre { margin: 0; user-select: all; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.certificate-api-editor { display: grid; gap: 12px; margin-top: 12px; padding: 14px; border: 1px solid var(--accent); border-radius: var(--rp-radius-surface, 0px); background: var(--panel); }
|
||||
.certificate-api-credential-item>.certificate-api-editor { margin: 0 9px 9px; }
|
||||
.certificate-api-editor>h3 { margin: 0; font-size: 15px; }
|
||||
.certificate-api-editor>.fine { margin: 0; }
|
||||
.certificate-api-editor-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 14px; }
|
||||
.certificate-api-editor-grid>label { display: grid; gap: 5px; margin: 0; }
|
||||
.certificate-api-editor-grid>label[hidden] { display: none; }
|
||||
.certificate-api-mode { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 8px; margin: 0; padding: 0; border: 0; }
|
||||
.certificate-api-mode>legend { padding: 0; margin-bottom: 6px; font-size: 13px; }
|
||||
.certificate-api-mode-option { display: flex; gap: 10px; align-items: flex-start; margin: 0 !important; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel2); cursor: pointer; }
|
||||
.certificate-api-mode-option:has(input:checked) { border-color: var(--accent); }
|
||||
.certificate-api-mode-option>input { margin-top: 3px; }
|
||||
.certificate-api-mode-option>span { display: grid; gap: 3px; min-width: 0; }
|
||||
.certificate-api-certificates-field { display: grid; gap: 6px; }
|
||||
.certificate-api-certificates-field>.fine { margin: 0; }
|
||||
#certificate-api-legacy-note { color: var(--accent); }
|
||||
.certificate-api-token-field>summary { cursor: pointer; font-size: 13px; }
|
||||
.certificate-api-token-field>input { margin-top: 8px; width: 100%; max-width: 520px; }
|
||||
.certificate-api-token-field>.fine { margin: 6px 0 0; }
|
||||
.certificate-api-credential-title { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }
|
||||
.certificate-api-chips { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.certificate-api-chip { padding: 1px 8px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); font-family: var(--mono, monospace); font-size: 11px; line-height: 1.6; color: var(--text); }
|
||||
.certificate-api-chip.is-new { border-style: dashed; color: var(--muted); }
|
||||
.certificate-api-chip.is-managed { border-color: var(--green); }
|
||||
.certificate-api-legacy { color: var(--accent); }
|
||||
.certificate-api-example { margin-top: 14px; }
|
||||
.certificate-api-example>summary { cursor: pointer; font-size: 13px; }
|
||||
#panel-settings [data-restart]>span[data-restart-badge]::after { content: attr(data-restart-badge); display: inline-block; margin-left: 7px; padding: 0 5px; border: 1px solid var(--warn-line); border-radius: var(--rp-radius-control, 0px); color: var(--accent); font-size: 9.5px; font-weight: 600; letter-spacing: .05em; line-height: 1.5; text-transform: uppercase; vertical-align: 1px; }
|
||||
#panel-settings .help-clamp { cursor: pointer; }
|
||||
#panel-settings .help-clamp:not(.is-open) { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }
|
||||
#panel-settings .help-clamp:hover, #panel-settings .help-clamp:focus-visible { color: var(--text); }
|
||||
#panel-settings .settings-page form.card>.settings-save-bar { position: sticky; bottom: 0; z-index: 6; margin-top: 14px; margin-bottom: 0; padding: 10px 0; border-top: 1px solid var(--line); background: var(--panel); align-items: center; }
|
||||
#panel-settings .settings-save-bar.has-unsaved::before { content: attr(data-unsaved-label); order: 99; margin-left: auto; color: var(--accent); font-size: 12px; }
|
||||
.settings-section { display: grid; gap: 10px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
.settings-section>.subheading { margin: 0; }
|
||||
.settings-section>.fine, .settings-section>.check { margin: 0 !important; }
|
||||
.settings-chip-field { display: grid; gap: 5px; }
|
||||
.settings-token-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.global-policy-summary { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0 4px; }
|
||||
.global-policy-summary:empty { display: none; }
|
||||
.global-policy-chip { display: inline-flex; gap: 6px; align-items: center; min-height: 0; padding: 4px 10px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 0px); background: var(--panel2); color: var(--muted); font-size: 12px; cursor: pointer; }
|
||||
.global-policy-chip>b { font-weight: 600; font-size: 11px; }
|
||||
.global-policy-chip.is-on { border-color: var(--green); color: var(--text); }
|
||||
.global-policy-chip.is-on>b { color: var(--green); }
|
||||
.global-policy-heading h3 .global-policy-state { margin-left: 8px; font-size: 10px; vertical-align: 2px; }
|
||||
.global-policy-section.is-off .global-policy-heading>.fine { opacity: .75; }
|
||||
.country-picker-host { min-width: 0; }
|
||||
.named-listener-row.listener-card { padding: 0; background: var(--panel2); }
|
||||
.listener-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; width: 100%; min-height: 0; padding: 10px 12px; border: 0; background: none; color: var(--text); text-align: left; cursor: pointer; }
|
||||
.listener-card-chevron::before { content: "▾"; display: inline-block; color: var(--muted); transition: transform .15s; }
|
||||
.listener-card.is-collapsed .listener-card-chevron::before { transform: rotate(-90deg); }
|
||||
.listener-card-title { display: inline-flex; gap: 8px; align-items: baseline; }
|
||||
.listener-card-id { color: var(--muted); font-size: 11px; }
|
||||
.listener-card-addresses { display: inline-flex; flex-wrap: wrap; gap: 4px; }
|
||||
.listener-card-badges { display: inline-flex; flex-wrap: wrap; gap: 4px; margin-left: auto; }
|
||||
.listener-card-badges>.pill { font-size: 10px; }
|
||||
.listener-card-body { padding: 4px 12px 12px; border-top: 1px solid var(--line); }
|
||||
.listener-card.is-collapsed>.listener-card-body { display: none; }
|
||||
#listeners-form>.listener-active-summary { margin: 10px 0 4px; }
|
||||
#global-policy-summary>.global-policy-chip { width: auto; flex: 0 0 auto; justify-content: flex-start; margin: 0; }
|
||||
.certificate-api-mode>label.certificate-api-mode-option { display: flex !important; flex-direction: row; grid-template-columns: none; }
|
||||
.cache-rules { display: grid; gap: 10px; margin-top: 8px; }
|
||||
.cache-rules-toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.cache-rules-toolbar>.cache-rules-templates { width: auto; min-width: 220px; }
|
||||
.cache-rules-toolbar>.primary { margin-left: auto; }
|
||||
.cache-rules-notices { display: grid; gap: 4px; }
|
||||
.cache-rules-notices:empty { display: none; }
|
||||
.cache-rules-notice { color: var(--accent); margin: 0; }
|
||||
.cache-rules-list { display: grid; gap: 6px; }
|
||||
.cache-rule { border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
|
||||
.cache-rule.is-open { border-color: var(--accent); }
|
||||
.cache-rule.is-disabled .cache-rule-title { opacity: .55; }
|
||||
.cache-rule.is-dragging { opacity: .5; }
|
||||
.cache-rule.is-drop { border-style: dashed; border-color: var(--accent); }
|
||||
.cache-rule-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; }
|
||||
.cache-rule-grip { cursor: grab; color: var(--muted); user-select: none; }
|
||||
.cache-rule-title { display: flex; flex: 1 1 auto; flex-wrap: wrap; align-items: center; gap: 4px 10px; min-width: 0; min-height: 0; padding: 0; border: 0; background: none; color: var(--text); text-align: left; cursor: pointer; }
|
||||
.cache-rule-title>b { font-weight: 600; }
|
||||
.cache-rule-title>.cache-rule-summary { overflow-wrap: anywhere; }
|
||||
.cache-rule-stage { font-size: 10px; }
|
||||
.cache-rule-hits { white-space: nowrap; }
|
||||
.cache-rule-actions { display: inline-flex; gap: 2px; }
|
||||
.cache-rule-note { padding: 0 10px 8px 34px; }
|
||||
.cache-rule-body { display: grid; gap: 12px; padding: 10px 12px 12px; border-top: 1px solid var(--line); }
|
||||
.cache-rule-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px 14px; align-items: end; }
|
||||
.cache-rule-field { display: grid; gap: 5px; margin: 0 !important; min-width: 0; }
|
||||
.cache-rule-field>small { margin: 0; }
|
||||
.cache-rule-stop { margin: 0 !important; }
|
||||
.cache-rule-section { display: grid; gap: 6px; }
|
||||
.cache-rule-section>h4 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
|
||||
.cache-rule-rows { display: grid; gap: 6px; }
|
||||
.cache-rule-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.cache-rule-row>select { width: auto; min-width: 150px; }
|
||||
.cache-rule-row>.cache-rule-name { width: 140px; }
|
||||
.cache-rule-row>.cache-rule-values { flex: 1 1 220px; min-width: 160px; }
|
||||
.cache-rule-row>.cache-rule-params { display: flex; flex: 1 1 260px; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
|
||||
.cache-rule-params>input[type=text] { flex: 1 1 160px; min-width: 120px; }
|
||||
.cache-rule-negate { margin: 0 !important; }
|
||||
.cache-rule-duration { display: inline-flex; gap: 4px; }
|
||||
.cache-rule-duration>input { width: 100px; }
|
||||
.cache-rule-duration>select { width: auto; }
|
||||
.cache-rule-vcl, .cache-rules-vcl { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
|
||||
.cache-rules-import { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); background: var(--panel2); }
|
||||
.cache-rules-import>textarea { font-family: var(--mono); font-size: 12px; }
|
||||
.cache-rules-warnings { margin: 0; padding-left: 18px; color: var(--accent); font-size: 12px; }
|
||||
.cache-rules-export>summary, .cache-rules-tester>summary { cursor: pointer; font-size: 13px; }
|
||||
.cache-rules-tester { padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--rp-radius-surface, 0px); }
|
||||
.cache-rules-tester-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px 14px; margin-top: 8px; }
|
||||
.cache-rules-tester-grid textarea { font-family: var(--mono); font-size: 12px; }
|
||||
.cache-rules-tester-result { display: grid; gap: 4px; margin-top: 8px; }
|
||||
.cache-rules-result-line { display: grid; grid-template-columns: minmax(140px, 200px) minmax(0, 1fr); gap: 10px; overflow-wrap: anywhere; }
|
||||
.cache-rules-result-line.is-ok>strong { color: var(--green); }
|
||||
.cache-rules-result-line.is-warn>strong { color: var(--accent); }
|
||||
.cache-rules .is-ok { color: var(--green); }
|
||||
.cache-rules .is-error { color: var(--red); }
|
||||
.vh-cache-rules { display: grid; gap: 6px; margin-top: 6px; padding-top: 10px; border-top: 1px solid var(--line); }
|
||||
.vh-cache-rules>h4 { margin: 0; }
|
||||
.cache-rule-actions { flex: 0 0 auto; }
|
||||
.cache-rule-actions>button { white-space: nowrap; flex-direction: row; }
|
||||
.cache-rule-grid { align-items: start; }
|
||||
.docs-links { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 4px 0 0; font-size: 12px; }
|
||||
.docs-link { font-size: 12px; justify-self: start; }
|
||||
|
||||
.system-info-page {
|
||||
display: grid;
|
||||
gap: var(--ui-gap);
|
||||
}
|
||||
|
||||
.system-info-page > .card,
|
||||
.system-info-page > .stats-grid {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.system-info-page .card-heading h2 {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.system-info-chips {
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
.system-info-stats > .stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.system-info-stats > .stat svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
margin-top: auto;
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.system-info-stats > .stat .pr-meter {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
width: 100%;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.system-info-columns {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr);
|
||||
gap: var(--ui-gap);
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.system-info-columns > .card {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.system-info-page .pr-row {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.system-info-split {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.system-info-split i,
|
||||
.system-info-legend i {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.system-info-split .h,
|
||||
.system-info-legend .h {
|
||||
background: var(--chart-secondary);
|
||||
}
|
||||
|
||||
.system-info-split .t,
|
||||
.system-info-legend .t {
|
||||
background: var(--chart-senary);
|
||||
}
|
||||
|
||||
.system-info-split .a,
|
||||
.system-info-legend .a {
|
||||
background: var(--chart-accent);
|
||||
}
|
||||
|
||||
.system-info-split .f,
|
||||
.system-info-legend .f {
|
||||
background: var(--chart-tertiary);
|
||||
}
|
||||
|
||||
.system-info-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 14px;
|
||||
margin: 4px 0 6px;
|
||||
color: var(--muted);
|
||||
font: 10px var(--mono);
|
||||
}
|
||||
|
||||
.system-info-legend > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.system-info-legend i {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--rp-progress-radius, 0);
|
||||
}
|
||||
|
||||
.system-info-legend b {
|
||||
color: var(--text);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.system-info-network td code {
|
||||
padding: 0;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.system-info-idle {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.system-info-idle summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.system-info-chain {
|
||||
align-items: center;
|
||||
margin: 6px 0 10px;
|
||||
}
|
||||
|
||||
.system-info-chain > span {
|
||||
color: var(--text-subtle);
|
||||
font: 11px var(--mono);
|
||||
}
|
||||
|
||||
.system-info-chain .pr-chip.is-ready {
|
||||
border-color: var(--pill-live-line);
|
||||
}
|
||||
|
||||
.system-info-chain .pr-chip.is-ready dd {
|
||||
color: var(--green);
|
||||
}
|
||||
|
||||
.system-info-chain .pr-chip.is-missing {
|
||||
border-color: var(--danger-line);
|
||||
}
|
||||
|
||||
.system-info-chain .pr-chip.is-missing dd {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.system-info-copy-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.system-info-copy-row dd {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.system-info-copy-row code {
|
||||
padding: 0;
|
||||
background: none;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.system-info-copy-row button {
|
||||
padding: 3px 8px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.system-info-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.system-info-footer .pr-chips {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.system-info-clipboard {
|
||||
position: fixed;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.system-info-columns {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.system-info-page .pr-cols {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.stats-grid.cache-stats.system-info-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
}
|
||||
@@ -29,7 +29,7 @@
|
||||
z-index: 80;
|
||||
inset-inline-end: 0;
|
||||
top: calc(100% + 4px);
|
||||
width: calc(min(190px, 100vw - 24px));
|
||||
width: calc(min(190px, calc(100 * var(--rp-vw)) - 24px));
|
||||
overflow: visible;
|
||||
padding: 4px;
|
||||
display: grid;
|
||||
@@ -121,7 +121,7 @@
|
||||
}
|
||||
|
||||
.logs-dialog .table-scroll {
|
||||
max-height: calc(min(60dvh, 580px));
|
||||
max-height: calc((calc(min(60dvh, 580px))) / var(--ui-scale, 1));
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
@@ -152,13 +152,13 @@
|
||||
position: fixed;
|
||||
inset: auto 12px 10px auto;
|
||||
margin: 0;
|
||||
width: calc(min(1180px, 100vw - 24px));
|
||||
max-height: 46dvh;
|
||||
width: calc((calc(min(1180px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-height: calc((46dvh) / var(--ui-scale, 1));
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
.logs-dialog.docked .table-scroll {
|
||||
max-height: calc(46dvh - 160px);
|
||||
max-height: calc((calc(46dvh - 160px)) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.cache-toolbar {
|
||||
@@ -443,7 +443,7 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
|
||||
}
|
||||
|
||||
.cache-operation-dialog {
|
||||
width: calc(min(920px, 100vw - 32px));
|
||||
width: calc((calc(min(920px, 100vw - 32px))) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.transform-applied-key,
|
||||
@@ -495,16 +495,16 @@ html[data-dashboard-density] #panel-overview .dashboard-overview-grid>.card.pool
|
||||
}
|
||||
|
||||
.config-history-dialog {
|
||||
width: calc(min(1180px, 100vw - 24px));
|
||||
max-width: calc(100vw - 24px);
|
||||
max-height: calc(100dvh - 28px);
|
||||
width: calc((calc(min(1180px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.config-history-dialog[open] {
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
height: calc(min(820px, 100dvh - 28px));
|
||||
height: calc((calc(min(820px, 100dvh - 28px))) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.config-history-layout {
|
||||
@@ -663,7 +663,7 @@ button.config-history-day.is-selected,
|
||||
}
|
||||
|
||||
.file-logs-table {
|
||||
max-height: 62vh;
|
||||
max-height: calc(62 * var(--rp-vh));
|
||||
}
|
||||
|
||||
.file-logs-table thead th {
|
||||
@@ -727,7 +727,7 @@ button.config-history-day.is-selected,
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
max-height: 24vh;
|
||||
max-height: calc(24 * var(--rp-vh));
|
||||
margin-top: 5px;
|
||||
line-height: 1.28;
|
||||
}
|
||||
@@ -767,7 +767,7 @@ button.config-history-day.is-selected,
|
||||
inset-inline-end: 0;
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
width: calc(min(420px, 100vw - 36px));
|
||||
width: calc(min(420px, calc(100 * var(--rp-vw)) - 36px));
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel2);
|
||||
@@ -792,7 +792,7 @@ button.config-history-day.is-selected,
|
||||
}
|
||||
|
||||
.file-log-column-picker .log-column-options {
|
||||
width: calc(min(360px, 100vw - 24px));
|
||||
width: calc(min(360px, calc(100 * var(--rp-vw)) - 24px));
|
||||
max-height: 420px;
|
||||
overflow: auto;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
@@ -895,8 +895,8 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
|
||||
}
|
||||
|
||||
.cache-varnish-info .metric-info-popover {
|
||||
width: calc(min(440px, 100vw - 56px));
|
||||
max-height: calc(min(65vh, 450px));
|
||||
width: calc(min(440px, calc(100 * var(--rp-vw)) - 56px));
|
||||
max-height: calc(min(calc(65 * var(--rp-vh)), 450px));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
@@ -908,9 +908,9 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
|
||||
}
|
||||
|
||||
.cache-maintenance-info .metric-info-popover {
|
||||
max-height: calc(min(60vh, 420px));
|
||||
max-height: calc(min(calc(60 * var(--rp-vh)), 420px));
|
||||
overflow-y: auto;
|
||||
width: calc(min(440px, 100vw - 56px));
|
||||
width: calc(min(440px, calc(100 * var(--rp-vw)) - 56px));
|
||||
}
|
||||
|
||||
.cache-maintenance-info .metric-info-popover code {
|
||||
@@ -1049,9 +1049,9 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
|
||||
}
|
||||
|
||||
.config-history-json-dialog {
|
||||
width: calc(min(1200px, 100vw - 24px));
|
||||
max-width: calc(100vw - 24px);
|
||||
max-height: calc(100dvh - 28px);
|
||||
width: calc((calc(min(1200px, 100vw - 24px))) / var(--ui-scale, 1));
|
||||
max-width: calc((calc(100vw - 24px)) / var(--ui-scale, 1));
|
||||
max-height: calc((calc(100dvh - 28px)) / var(--ui-scale, 1));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@@ -1068,7 +1068,7 @@ html[data-table-density=ultra] .file-log-inline-detail pre {
|
||||
background: var(--panel);
|
||||
border: 0;
|
||||
overflow: auto;
|
||||
max-height: 68dvh;
|
||||
max-height: calc(68 * var(--rp-dvh));
|
||||
font: 11px/1.5 var(--mono);
|
||||
}
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@
|
||||
}
|
||||
|
||||
.config-history-browser {
|
||||
max-height: calc(min(300px, 38dvh));
|
||||
max-height: calc(min(300px, calc(38 * var(--rp-dvh))));
|
||||
overflow-y: auto;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
@@ -298,7 +298,7 @@
|
||||
}
|
||||
|
||||
.vhost-dialog {
|
||||
max-width: calc(100vw - 12px);
|
||||
max-width: calc((calc(100vw - 12px)) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.sidebar .brand {
|
||||
@@ -512,7 +512,7 @@
|
||||
}
|
||||
|
||||
#panel-filelogs .file-log-search-help-popover {
|
||||
width: calc(min(320px, 100vw - 54px));
|
||||
width: calc(min(320px, calc(100 * var(--rp-vw)) - 54px));
|
||||
}
|
||||
|
||||
#panel-filelogs .file-log-aggregate-form,
|
||||
@@ -1023,7 +1023,7 @@
|
||||
}
|
||||
|
||||
.logs-dialog .table-scroll {
|
||||
max-height: 50dvh;
|
||||
max-height: calc((50dvh) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.log-tools select {
|
||||
@@ -1032,11 +1032,11 @@
|
||||
}
|
||||
|
||||
.logs-dialog.docked {
|
||||
max-height: 55dvh;
|
||||
max-height: calc((55dvh) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.logs-dialog.docked .table-scroll {
|
||||
max-height: calc(55dvh - 230px);
|
||||
max-height: calc((calc(55dvh - 230px)) / var(--ui-scale, 1));
|
||||
}
|
||||
|
||||
.page-editor,
|
||||
@@ -1176,7 +1176,7 @@
|
||||
}
|
||||
|
||||
.config-history-json-columns pre {
|
||||
max-height: 38dvh;
|
||||
max-height: calc(38 * var(--rp-dvh));
|
||||
}
|
||||
|
||||
.appearance-settings-grid.dashboard-appearance-grid>.dashboard-density-setting {
|
||||
@@ -1282,9 +1282,9 @@
|
||||
}
|
||||
|
||||
.backend-column-options {
|
||||
width: min(330px, calc(100vw - 32px));
|
||||
width: min(330px, calc(calc(100 * var(--rp-vw)) - 32px));
|
||||
min-width: 0;
|
||||
max-width: calc(100vw - 32px);
|
||||
max-width: calc(calc(100 * var(--rp-vw)) - 32px);
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
@@ -1481,7 +1481,7 @@
|
||||
|
||||
@media (max-width:480px) {
|
||||
.page-intro-title-row h1 {
|
||||
font-size: calc(clamp(18px, 5vw, 24px));
|
||||
font-size: calc(clamp(18px, calc(5 * var(--rp-vw)), 24px));
|
||||
letter-spacing: -.6px;
|
||||
}
|
||||
|
||||
@@ -1548,7 +1548,7 @@
|
||||
.log-column-options {
|
||||
top: auto;
|
||||
bottom: calc(100% + 4px);
|
||||
width: calc(min(360px, 100vw - 24px));
|
||||
width: calc(min(360px, calc(100 * var(--rp-vw)) - 24px));
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@@ -1642,11 +1642,11 @@
|
||||
}
|
||||
|
||||
html[data-dashboard-density=normal] #panel-overview .dashboard-overview-grid.is-aligned>.stat strong {
|
||||
font-size: calc(clamp(20px, 5.8vw, 26px));
|
||||
font-size: calc(clamp(20px, calc(5.8 * var(--rp-vw)), 26px));
|
||||
}
|
||||
|
||||
html[data-dashboard-density=compact] #panel-overview .dashboard-overview-grid.is-aligned>.stat strong {
|
||||
font-size: calc(clamp(19px, 5vw, 22px));
|
||||
font-size: calc(clamp(19px, calc(5 * var(--rp-vw)), 22px));
|
||||
}
|
||||
|
||||
#panel-overview .dashboard-overview-grid.is-aligned>.card:not(.pool-card):where(:not([data-dashboard-span])) {
|
||||
@@ -1755,7 +1755,7 @@
|
||||
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-acl-editor,
|
||||
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-protocol-editor,
|
||||
.docker-service-editor[open]:not(.docker-service-metrics)>.docker-timeout-editor { margin-top: 10px; }
|
||||
.docker-service-editor>summary:focus-visible, .docker-acl-editor>summary:focus-visible, .docker-protocol-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; border-radius: 4px; }
|
||||
.docker-service-editor>summary:focus-visible, .docker-acl-editor>summary:focus-visible, .docker-protocol-editor>summary:focus-visible, .docker-timeout-editor>summary:focus-visible, .docker-health-editor>summary:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; border-radius: var(--rp-radius-control, 0px); }
|
||||
|
||||
.vh-tabs { gap: 2px; padding: 4px 0 0; border-bottom: 1px solid var(--line); margin-bottom: 12px; }
|
||||
.vh-tabs button { font-size: 12px; padding: 8px 12px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--muted); margin-bottom: -1px; }
|
||||
|
||||
+115
-27
@@ -95,7 +95,7 @@
|
||||
const field = el("div", undefined, "docker-field docker-alias-field host-chip-field"), box = el("div", undefined, "host-chip-editor docker-alias-editor"), inputNode = input("", "text", "docker-alias-input");
|
||||
field.append(el("span", t("dockerAliases"))); inputNode.maxLength = 253; inputNode.placeholder = "alias1 / app.example.com"; inputNode.setAttribute("aria-label", t("dockerAliasAdd"));
|
||||
const aliasDomain = el("select", undefined, "docker-alias-domain"); aliasDomain.setAttribute("aria-label", t("dockerAliasDomain")); aliasDomain.title = t("dockerAliasDomain");
|
||||
const fillAliasDomains = () => { const current = aliasDomain.value; aliasDomain.replaceChildren(); const master = el("option", `.${scope.master() || "…"} (${t("dockerDomainMasterShort")})`); master.value = ""; aliasDomain.append(master); for (const domain of scope.domains) { const option = el("option", `.${domain}`); option.value = domain; aliasDomain.append(option); } aliasDomain.value = [...aliasDomain.options].some(option => option.value === current) ? current : ""; };
|
||||
const fillAliasDomains = () => { const current = aliasDomain.value; aliasDomain.replaceChildren(); const master = el("option", `.${scope.master() || "…"} (${t("dockerDomainMasterShort")})`); master.value = ""; aliasDomain.append(master); const masterName = scope.master(); for (const domain of scope.domains) { if (domain === masterName) continue; const option = el("option", `.${domain}`); option.value = domain; aliasDomain.append(option); } aliasDomain.value = [...aliasDomain.options].some(option => option.value === current) ? current : ""; aliasDomain.hidden = aliasDomain.options.length < 2; };
|
||||
fillAliasDomains();
|
||||
const values = [];
|
||||
const normalize = raw => {
|
||||
@@ -213,20 +213,43 @@
|
||||
const items = (envelope?.config?.tls?.certificates || []).map(cert => { const names = certificateNames(cert); return { id: cert.id, title: cert.id, detail: names.slice(0, 4).join(", ") + (names.length > 4 ? ` +${names.length - 4}` : ""), search: names.join(" "), badge: cert.issuer ? "ACME" : "", badgeClass: "is-allow" }; });
|
||||
return window.rustProxyChoicePicker.create({ className: "docker-agent-certificates", selected, items, limit: MAX_CERTIFICATES, unknownDetail: "dockerCertificateUnknown", labels: { choose: "dockerCertificatesChoose", selected: "dockerCertificatesSelected", none: "dockerCertificatesNone", empty: "dockerCertificatesEmpty" } });
|
||||
}
|
||||
function detectedAddresses(agentId) { return (obs(agentId)?.inventory?.addresses || []).map(address => { const details = [address.interface, address.scope, address.source].filter(Boolean).join(" · "); return [address.ip, details ? `${address.ip} (${details})` : address.ip]; }); }
|
||||
function addressGroup(address, primary) {
|
||||
const sources = String(address.source || "").split(/[\s,]+/).filter(Boolean);
|
||||
if (address.ip === primary || sources.some(source => ["override", "route", "public_api"].includes(source))) return "recommended";
|
||||
if (sources.includes("bridge")) return "bridge";
|
||||
return "host";
|
||||
}
|
||||
function detectedAddresses(agentId) {
|
||||
const inventory = obs(agentId)?.inventory || {}, primary = inventory.public_ip || "";
|
||||
return (inventory.addresses || []).map(address => {
|
||||
const details = [address.interface, address.scope, address.source].filter(Boolean).join(" · ");
|
||||
return { ip: address.ip, label: details ? `${address.ip} (${details})` : address.ip, group: addressGroup(address, primary), primary: address.ip === primary };
|
||||
});
|
||||
}
|
||||
function targetIpControl(agent, current) {
|
||||
const wrap = el("div", undefined, "docker-target-control"), select = el("select", undefined, "docker-agent-target"), custom = input("", "text", "docker-agent-target-custom mono");
|
||||
custom.placeholder = "10.0.0.20 / 2001:db8::20"; custom.maxLength = 45; custom.spellcheck = false;
|
||||
const auto = el("option", t("dockerTargetAutoDetected")); auto.value = ""; select.append(auto);
|
||||
const detected = detectedAddresses(agent?.id);
|
||||
for (const [ip, label] of detected) { const option = el("option", label); option.value = ip; select.append(option); }
|
||||
for (const [group, key] of [["recommended", "dockerTargetGroupRecommended"], ["host", "dockerTargetGroupHost"], ["bridge", "dockerTargetGroupBridge"]]) {
|
||||
const items = detected.filter(item => item.group === group); if (!items.length) continue;
|
||||
const holder = el("optgroup"); holder.label = t(key);
|
||||
for (const item of items) { const option = el("option", item.primary ? `★ ${item.label}` : item.label); option.value = item.ip; holder.append(option); }
|
||||
select.append(holder);
|
||||
}
|
||||
const customOption = el("option", t("dockerTargetCustom")); customOption.value = CUSTOM_IP; select.append(customOption);
|
||||
current = String(current || "");
|
||||
if (!current) select.value = ""; else if (detected.some(([ip]) => ip === current)) select.value = current; else { select.value = CUSTOM_IP; custom.value = current; }
|
||||
const sync = () => { custom.hidden = select.value !== CUSTOM_IP; custom.required = select.value === CUSTOM_IP; };
|
||||
if (!current) select.value = ""; else if (detected.some(item => item.ip === current)) select.value = current; else { select.value = CUSTOM_IP; custom.value = current; }
|
||||
const hint = el("small", "", "fine docker-target-hint");
|
||||
const sync = () => {
|
||||
custom.hidden = select.value !== CUSTOM_IP; custom.required = select.value === CUSTOM_IP;
|
||||
const chosen = detected.find(item => item.ip === select.value);
|
||||
hint.textContent = chosen?.group === "bridge" ? t("dockerTargetBridgeHint") : "";
|
||||
hint.hidden = !hint.textContent;
|
||||
};
|
||||
select.addEventListener("change", () => { sync(); if (select.value === CUSTOM_IP) custom.focus(); }); sync();
|
||||
if (!detected.length) wrap.title = t("dockerTargetNoDetected");
|
||||
wrap.append(select, custom);
|
||||
wrap.append(select, custom, hint);
|
||||
return { node: wrap, read() { if (select.value !== CUSTOM_IP) return select.value || null; const value = custom.value.trim(); if (!value) throw fieldError(custom, t("dockerTargetCustomRequired")); return value; } };
|
||||
}
|
||||
function percent(part, total) { return total > 0 ? Math.max(0, Math.min(100, part / total * 100)) : 0; }
|
||||
@@ -294,6 +317,38 @@
|
||||
}
|
||||
function renderSettingsDiagnostics() { document.querySelectorAll("#docker-agent-settings-list .docker-agent-diagnostics").forEach(renderAgentDiagnostics); }
|
||||
|
||||
const LABEL_EXAMPLE = `services:
|
||||
shop:
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- "8080:80"
|
||||
labels:
|
||||
rustproxy.enable: "true"
|
||||
rustproxy.host: "shop"
|
||||
rustproxy.domain: "apps.example.com"
|
||||
rustproxy.aliases: "sklep, www.shop.apps.example.com"
|
||||
rustproxy.port: "80"
|
||||
rustproxy.scheme: "http"
|
||||
rustproxy.force_ssl: "true"
|
||||
rustproxy.websockets: "true"
|
||||
rustproxy.cache: "false"
|
||||
rustproxy.compression: "true"
|
||||
rustproxy.preserve_host: "true"`;
|
||||
function openLabelHelp() {
|
||||
const dialog = $("location-help-dialog"), title = $("location-help-title"), body = $("location-help-body"); if (!dialog || !title || !body) return;
|
||||
title.textContent = t("dockerLabelHelpTitle");
|
||||
const table = el("table", undefined, "docker-label-table"), tbody = el("tbody");
|
||||
for (const [label, key] of [["rustproxy.enable", "dockerLabelHelpEnable"], ["rustproxy.host", "dockerLabelHelpHost"], ["rustproxy.domain", "dockerLabelHelpDomain"], ["rustproxy.aliases", "dockerLabelHelpAliases"], ["rustproxy.port", "dockerLabelHelpPort"], ["rustproxy.scheme", "dockerLabelHelpScheme"], ["rustproxy.force_ssl", "dockerLabelHelpForceSsl"], ["rustproxy.websockets", "dockerLabelHelpWebsockets"], ["rustproxy.cache", "dockerLabelHelpCache"], ["rustproxy.compression", "dockerLabelHelpCompression"], ["rustproxy.preserve_host", "dockerLabelHelpPreserveHost"]]) {
|
||||
const tr = el("tr"), name = el("td"); name.append(el("code", label)); tr.append(name, el("td", t(key))); tbody.append(tr);
|
||||
}
|
||||
table.append(tbody);
|
||||
const pre = el("pre", undefined, "docker-label-example"), code = el("code", LABEL_EXAMPLE); pre.append(code);
|
||||
const copy = el("button", t("copyEntry"), "outline docker-label-copy"); copy.type = "button"; copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(LABEL_EXAMPLE); toast(t("copied")); } catch { const range = document.createRange(); range.selectNodeContents(code); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); } });
|
||||
const exampleHead = el("div", undefined, "docker-label-example-head"); exampleHead.append(el("h3", t("dockerLabelHelpExample")), copy);
|
||||
const docs = el("a", t("dockerLabelHelpDocs"), "docs-link"); docs.href = "/docs#doc=docs%2FDOCKER_DISCOVERY.md§ion=publishing-from-container-labels"; docs.target = "_blank"; docs.rel = "noopener noreferrer";
|
||||
body.replaceChildren(el("p", t("dockerLabelHelpIntro"), "location-doc-intro"), table, exampleHead, pre, el("p", t("dockerLabelHelpNote"), "fine"), docs);
|
||||
dialog.showModal();
|
||||
}
|
||||
function agentSettingsRow(agent = null, options = {}) {
|
||||
const value = agent || { id: "", name: "", enabled: true, endpoint: "https://127.0.0.1:9876", token: "", tls_fingerprint_sha256: null, domains: [], poll_interval_seconds: 30, certificate_ids: [], acl_profile_id: null, default_target_ip: null, listener_ids: [firstListener()], assignments: [] };
|
||||
const row = el("div", undefined, "docker-agent-settings entity"); row.dataset.originalId = agent?.id || ""; row._assignments = structuredClone(value.assignments || []);
|
||||
@@ -301,7 +356,9 @@
|
||||
const enabled = input("", "checkbox", "docker-agent-enabled"); enabled.checked = value.enabled !== false;
|
||||
const enabledLabel = el("label", undefined, "check"); enabledLabel.append(enabled, el("span", t("enabled")));
|
||||
const state = agent ? obs(agent.id) : null, stateBadge = el("span", state?.ok ? t("dockerConnected") : state ? t("dockerError") : t("dockerWaiting"), `pill docker-agent-status-badge ${state?.ok ? "live" : ""}`.trim());
|
||||
const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("docker-agents-form"); }), actions = el("div", undefined, "entity-actions docker-agent-heading-actions"); actions.append(enabledLabel, stateBadge, remove); head.append(title, actions);
|
||||
const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("docker-agents-form"); }), actions = el("div", undefined, "entity-actions docker-agent-heading-actions");
|
||||
const testWrap = el("span", undefined, "docker-agent-test-wrap"), testButton = el("button", t("dockerTestConnection"), "outline docker-agent-test"), testResult = el("div", "", "docker-agent-test-result"); testButton.type = "button"; testResult.hidden = true; testResult.setAttribute("role", "status"); testWrap.append(testButton, testResult);
|
||||
actions.append(enabledLabel, stateBadge, testWrap, remove); head.append(title, actions);
|
||||
const id = input(value.id, "text", "docker-agent-id"); id.maxLength = 64; id.required = true; id.pattern = "[A-Za-z0-9_\\-]{1,64}"; if (agent) id.readOnly = true;
|
||||
const name = input(value.name, "text", "docker-agent-name"); name.maxLength = 96; name.required = true;
|
||||
name.addEventListener("input", () => { titleText.textContent = name.value.trim() || id.value.trim() || t("dockerAgentNew"); });
|
||||
@@ -350,18 +407,23 @@
|
||||
provisionInput.addEventListener("keydown", event => { if (event.key === "Enter") { event.preventDefault(); void applyProvision(); } });
|
||||
row.focusProvision = () => { provision.open = true; provisionInput.focus(); };
|
||||
const labelPublish = input("", "checkbox", "docker-agent-label-publish"); labelPublish.checked = value.label_publish === true;
|
||||
const labelField = checkboxField("dockerLabelPublish", labelPublish); labelField.append(el("small", t("dockerLabelPublishHelp"), "fine"));
|
||||
const testButton = el("button", t("dockerTestConnection"), "outline docker-agent-test"), testResult = el("small", "", "fine docker-agent-test-result"); testButton.type = "button";
|
||||
const labelField = checkboxField("dockerLabelPublish", labelPublish), labelHelp = el("small", undefined, "fine docker-label-help"), labelInfo = el("button", "?", "docker-label-info"); labelInfo.type = "button"; labelInfo.dataset.uiIconName = "none"; labelInfo.title = t("dockerLabelHelpTitle"); labelInfo.setAttribute("aria-label", t("dockerLabelHelpTitle")); labelInfo.addEventListener("click", openLabelHelp);
|
||||
labelHelp.append(el("span", t("dockerLabelPublishHelp")), labelInfo); labelField.append(labelHelp);
|
||||
let closeBubble = null;
|
||||
const showBubble = (text, kind) => {
|
||||
testResult.textContent = text; testResult.className = `docker-agent-test-result${kind ? ` is-${kind}` : ""}`; testResult.hidden = false;
|
||||
if (!closeBubble) { closeBubble = event => { if (!testWrap.contains(event.target)) { testResult.hidden = true; document.removeEventListener("pointerdown", closeBubble); closeBubble = null; } }; document.addEventListener("pointerdown", closeBubble); }
|
||||
};
|
||||
testResult.addEventListener("click", () => { testResult.hidden = true; });
|
||||
testButton.addEventListener("click", async () => {
|
||||
testButton.disabled = true; testResult.className = "fine docker-agent-test-result"; testResult.textContent = t("dockerTestRunning");
|
||||
testButton.disabled = true; showBubble(t("dockerTestRunning"), "running");
|
||||
try {
|
||||
const data = await api("/api/docker/test", { method: "POST", body: JSON.stringify({ endpoint: endpoint.value.trim().replace(/\/$/, ""), token: token.value, tls_fingerprint_sha256: fingerprint.value.trim() || null }) });
|
||||
if (data.ok) { testResult.classList.add("is-ok"); testResult.textContent = t("dockerTestOk").replace("{host}", data.hostname || "-").replace("{version}", data.agent_version || "-").replace("{services}", data.services ?? 0).replace("{ms}", data.elapsed_ms ?? "-"); }
|
||||
else { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${data.error || "-"}`; }
|
||||
} catch (error) { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${error.message}`; }
|
||||
if (data.ok) showBubble(t("dockerTestOk").replace("{host}", data.hostname || "-").replace("{version}", data.agent_version || "-").replace("{services}", data.services ?? 0).replace("{ms}", data.elapsed_ms ?? "-"), "ok");
|
||||
else showBubble(`${t("dockerTestFailed")}: ${data.error || "-"}`, "error");
|
||||
} catch (error) { showBubble(`${t("dockerTestFailed")}: ${error.message}`, "error"); }
|
||||
finally { testButton.disabled = false; }
|
||||
});
|
||||
const testRow = el("div", undefined, "docker-agent-test-row"); testRow.append(testButton, testResult);
|
||||
const grid = el("div", undefined, "field-grid docker-agent-grid");
|
||||
const idField = labeled("dockerAgentId", id);
|
||||
grid.append(labeled("dockerAgentName", name), idField, labeled("dockerAgentEndpoint", endpoint, t("dockerAgentEndpointHelp")), labeled("dockerAgentToken", token), labeled("dockerTlsFingerprint", fingerprint, t("dockerTlsFingerprintHelp")), labeled("dockerPollInterval", poll, t("dockerPollIntervalHelp")), domainsField, certificateField, labeled("dockerDefaultTarget", target.node, t("dockerDefaultTargetHelp")), defaultAclField, labelField);
|
||||
@@ -369,7 +431,7 @@
|
||||
const listenerControl = window.rustProxyIntegrations.bindings(listenerField, value.listener_ids || [], !agent); listenerField.querySelector(".listener-choices")?.classList.add("docker-agent-listener-choices"); row._readListeners = listenerControl.read; grid.append(listenerField);
|
||||
const security = el("div", undefined, "docker-agent-security"), secBadge = el("span", "", "pill docker-agent-security-badge"), secHint = el("span", "", "fine docker-agent-security-hint"); security.append(secBadge, secHint);
|
||||
const diagnostics = el("div", undefined, "docker-agent-diagnostics"); diagnostics.dataset.agentId = agent?.id || ""; renderAgentDiagnostics(diagnostics);
|
||||
endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, provision, diagnostics, security, testRow, grid); updateSecurityBadge(row);
|
||||
endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, provision, diagnostics, security, grid); updateSecurityBadge(row);
|
||||
window.rustProxyAutoId.attach(id, { elements: [name], taken: () => [...(cfg().agents || []).map(item => item.id), ...[...document.querySelectorAll("#docker-agent-settings-list .docker-agent-id")].filter(node => node !== id).map(node => node.value.trim())].filter(Boolean) });
|
||||
return row;
|
||||
}
|
||||
@@ -618,6 +680,35 @@
|
||||
const saved = await saveSection("docker-agents", current); if (saved) row.classList.remove("is-dirty"); return saved;
|
||||
}
|
||||
|
||||
function shortUptime(started) {
|
||||
const since = Date.parse(started || ""); if (!Number.isFinite(since)) return "";
|
||||
let seconds = Math.max(0, Math.floor((Date.now() - since) / 1000)); const days = Math.floor(seconds / 86400); seconds %= 86400; const hours = Math.floor(seconds / 3600), minutes = Math.floor(seconds % 3600 / 60);
|
||||
return days ? `${days}d ${hours}h` : hours ? `${hours}h ${minutes}m` : `${minutes}m`;
|
||||
}
|
||||
function containerChip(label, value, cls = "", ratio = null) {
|
||||
const chip = el("span", undefined, `docker-container-chip ${cls}`.trim()); chip.append(el("span", label, "docker-container-chip-label"), el("b", value));
|
||||
if (ratio != null) { const bar = el("span", undefined, "docker-container-chip-bar"), fill = el("i"); const pct = Math.max(0, Math.min(100, ratio * 100)); fill.style.width = `${pct.toFixed(1)}%`; if (pct >= 90) chip.classList.add("is-danger"); else if (pct >= 75) chip.classList.add("is-warn"); bar.append(fill); chip.append(bar); }
|
||||
return chip;
|
||||
}
|
||||
function containerStateLine(container) {
|
||||
const line = el("span", undefined, "docker-container-state"), state = String(container.state || "");
|
||||
if (state) {
|
||||
const stateCls = state === "running" ? "live" : ["restarting", "exited", "dead", "removing"].includes(state) ? "danger" : "warn";
|
||||
const pill = el("span", state, `pill docker-container-pill ${stateCls}`); const uptime = state === "running" ? shortUptime(container.started_at) : "";
|
||||
if (uptime) pill.append(el("small", ` ${uptime}`, "docker-container-uptime"));
|
||||
if (container.started_at) pill.title = `${t("dockerContainerStarted")}: ${new Date(container.started_at).toLocaleString()}`;
|
||||
line.append(pill);
|
||||
}
|
||||
if (container.health) {
|
||||
const healthText = { healthy: t("dockerContainerHealthy"), unhealthy: t("dockerContainerUnhealthy"), starting: t("dockerContainerHealthStarting"), none: t("dockerContainerNoHealthcheck") }[container.health] || container.health;
|
||||
const healthCls = { healthy: "live", unhealthy: "danger", starting: "warn" }[container.health] || "muted";
|
||||
const pill = el("span", healthText, `pill docker-container-pill docker-container-health ${healthCls}`); if (container.health === "none") pill.title = t("dockerContainerNoHealthcheckHelp"); line.append(pill);
|
||||
}
|
||||
if (container.cpu_percent != null) { const cpu = Number(container.cpu_percent); line.append(containerChip("CPU", `${cpu.toFixed(1)}%`, "", cpu / 100)); }
|
||||
if (container.memory_bytes != null) { const used = Number(container.memory_bytes), limit = Number(container.memory_limit_bytes || 0); const chip = containerChip("RAM", bytes(used), "", limit ? used / limit : null); if (limit) chip.title = `${bytes(used)} / ${bytes(limit)} (${percent(used, limit).toFixed(1)}%)`; line.append(chip); }
|
||||
if (container.restart_count != null) { const restarts = Number(container.restart_count); const chip = containerChip(t("dockerContainerRestarts"), fmt(restarts), restarts > 0 ? "is-warn" : ""); line.append(chip); }
|
||||
return line;
|
||||
}
|
||||
function assignmentRow(agent, inventory, service, assignment, stale = false) {
|
||||
const key = assignment?.service_key || service.key, row = el("article", undefined, "docker-service-row"); row.dataset.key = key; row.dataset.viewKey = viewKey(agent.id, key); if (assignment?.from_labels) row.dataset.fromLabels = "1";
|
||||
const runtime = runtimeFor(agent.id, key), member = runtime?.members?.[0], technicalName = service?.technical_name || assignment?.service_key || "";
|
||||
@@ -638,16 +729,7 @@
|
||||
if (issue) { const badge = el("span", t("dockerLabelIssue"), "pill warn docker-label-badge"); badge.title = issue.error; meta.append(badge); }
|
||||
const container = service?.container;
|
||||
if (container && (container.state || container.health || container.cpu_percent != null || container.memory_bytes != null)) {
|
||||
const stateLine = el("span", undefined, "docker-container-state"), healthCls = container.health === "unhealthy" || ["restarting", "exited", "dead"].includes(container.state) ? "danger" : container.health === "healthy" ? "live" : "";
|
||||
const healthText = { healthy: t("dockerContainerHealthy"), unhealthy: t("dockerContainerUnhealthy"), starting: t("dockerContainerHealthStarting"), none: t("dockerContainerNoHealthcheck") }[container.health] || container.health;
|
||||
if (container.state || container.health) { const pill = el("span", [container.state, healthText].filter(Boolean).join(" · "), `pill ${healthCls}`.trim()); if (container.health === "none") pill.title = t("dockerContainerNoHealthcheckHelp"); stateLine.append(pill); }
|
||||
const parts = [];
|
||||
if (container.cpu_percent != null) parts.push(`CPU ${Number(container.cpu_percent).toFixed(1)}%`);
|
||||
if (container.memory_bytes != null) parts.push(`RAM ${bytes(Number(container.memory_bytes))}${container.memory_limit_bytes ? ` / ${bytes(Number(container.memory_limit_bytes))}` : ""}`);
|
||||
if (container.restart_count != null) parts.push(`${t("dockerContainerRestarts")}: ${fmt(container.restart_count)}`);
|
||||
if (parts.length) stateLine.append(el("small", parts.join(" · "), "fine"));
|
||||
if (container.started_at) stateLine.title = `${t("dockerContainerStarted")}: ${container.started_at}`;
|
||||
meta.append(stateLine);
|
||||
meta.append(containerStateLine(container));
|
||||
}
|
||||
const visibility = el("button", "", "quiet docker-view-toggle"); visibility.type = "button";
|
||||
const syncVisibility = () => { visibility.textContent = t(hiddenVhosts.has(row.dataset.viewKey) ? "dockerUnhideVhost" : "dockerHideVhost"); }; syncVisibility(); visibility.addEventListener("click", () => { const key = row.dataset.viewKey; if (hiddenVhosts.has(key)) hiddenVhosts.delete(key); else hiddenVhosts.add(key); saveHidden(); syncVisibility(); applyViewFilters(); });
|
||||
@@ -698,8 +780,14 @@
|
||||
const certificateBar = el("div", undefined, "docker-service-certificate-bar");
|
||||
const certificateHint = el("small", "", "fine docker-certificate-hint"); certificateBar.append(mismatchLabel, certificateHint);
|
||||
const syncCertificateHint = () => {
|
||||
const ids = agentCertificates(agent); if (!ids.length) { certificateHint.textContent = t("dockerCertificateHintAuto"); return; }
|
||||
const hosts = [expandedHost(host.value.trim() || technical, domainSelect.value), ...aliases.peek().map(alias => expandedHost(alias, domainSelect.value))].filter(Boolean);
|
||||
const ids = agentCertificates(agent), hosts = [expandedHost(host.value.trim() || technical, domainSelect.value), ...aliases.peek().map(alias => expandedHost(alias, domainSelect.value))].filter(Boolean);
|
||||
certificateHint.classList.remove("is-warn");
|
||||
if (!ids.length) {
|
||||
const all = (envelope?.config?.tls?.certificates || []).map(cert => cert.id), uncovered = hosts.filter(name => !pickCertificate(all, [name])), picked = hosts.length ? pickCertificate(all, hosts.slice(0, 1)) : "";
|
||||
if (uncovered.length) { certificateHint.textContent = t("dockerCertificateHintAutoMissing").replace("{hosts}", uncovered.join(", ")); certificateHint.classList.add("is-warn"); }
|
||||
else certificateHint.textContent = picked ? t("dockerCertificateHintAutoMatched").replace("{id}", picked) : t("dockerCertificateHintAuto");
|
||||
return;
|
||||
}
|
||||
const picked = pickCertificate(ids, hosts);
|
||||
certificateHint.textContent = picked ? t("dockerCertificateHintMatched").replace("{id}", picked) : t(certMismatch.checked ? "dockerCertificateHintForced" : "dockerCertificateHintGeneric").replace("{id}", ids[0]);
|
||||
};
|
||||
|
||||
@@ -415,4 +415,4 @@ html[data-corner-style=extra] {
|
||||
.swagger-ui input,
|
||||
.swagger-ui textarea {
|
||||
border-radius: var(--rp-docs-radius-control, 0);
|
||||
}
|
||||
}.reader-target { outline: 2px solid var(--accent, #f69b74); outline-offset: 4px; transition: outline-color 1s; }
|
||||
+27
-9
@@ -99,12 +99,16 @@
|
||||
const parsed = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(token); const anchor = document.createElement("a");
|
||||
anchor.textContent = parsed[1]; const target = parsed[2].trim();
|
||||
if (/^https?:\/\//i.test(target)) { anchor.href = target; anchor.target = "_blank"; anchor.rel = "noreferrer"; }
|
||||
else if (target.startsWith("#")) { anchor.href = target; }
|
||||
else if (target.startsWith("#")) {
|
||||
const section = target.slice(1);
|
||||
anchor.href = `#doc=${encodeURIComponent(basePath)}§ion=${encodeURIComponent(section)}`;
|
||||
anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(basePath, true, section); });
|
||||
}
|
||||
else {
|
||||
const resolved = normalizeDocPath(basePath, target);
|
||||
const resolved = normalizeDocPath(basePath, target), section = target.includes("#") ? target.slice(target.indexOf("#") + 1) : "";
|
||||
if (docsByPath.has(resolved)) {
|
||||
anchor.href = `#doc=${encodeURIComponent(resolved)}`;
|
||||
anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(resolved, true); });
|
||||
anchor.href = `#doc=${encodeURIComponent(resolved)}${section ? `§ion=${encodeURIComponent(section)}` : ""}`;
|
||||
anchor.addEventListener("click", event => { event.preventDefault(); selectDocument(resolved, true, section); });
|
||||
} else { anchor.href = target; }
|
||||
}
|
||||
parent.append(anchor);
|
||||
@@ -114,6 +118,14 @@
|
||||
if (offset < text.length) parent.append(document.createTextNode(text.slice(offset)));
|
||||
}
|
||||
|
||||
function headingSlug(text) {
|
||||
return String(text || "").trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");
|
||||
}
|
||||
function scrollToSection(section) {
|
||||
if (!section) { element("docs-reader-content").scrollTop = 0; return; }
|
||||
const node = element("docs-reader-content").querySelector(`[id="${CSS.escape(section)}"]`);
|
||||
if (node) { node.scrollIntoView({ block: "start" }); node.classList.add("reader-target"); setTimeout(() => node.classList.remove("reader-target"), 1600); }
|
||||
}
|
||||
function renderMarkdown(documentInfo) {
|
||||
const target = element("docs-reader-content"); target.replaceChildren();
|
||||
const lines = documentInfo.content.replaceAll("\r\n", "\n").split("\n");
|
||||
@@ -139,7 +151,7 @@
|
||||
}
|
||||
table = null;
|
||||
const heading = /^(#{1,4})\s+(.+)$/.exec(line);
|
||||
if (heading) { flushParagraph(); closeList(); const h = document.createElement(`h${heading[1].length}`); appendInline(h, heading[2], documentInfo.path); target.append(h); continue; }
|
||||
if (heading) { flushParagraph(); closeList(); const h = document.createElement(`h${heading[1].length}`); appendInline(h, heading[2], documentInfo.path); h.id = headingSlug(h.textContent); target.append(h); continue; }
|
||||
const bullet = /^\s*[-*]\s+(.+)$/.exec(line), ordered = /^\s*\d+\.\s+(.+)$/.exec(line);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph(); const tag = ordered ? "ol" : "ul";
|
||||
@@ -170,10 +182,11 @@
|
||||
}
|
||||
if (!root.children.length) { const empty = document.createElement("div"); empty.className = "reader-empty"; empty.textContent = t("docsReaderEmpty"); root.append(empty); }
|
||||
}
|
||||
function selectDocument(path, updateHash = false) {
|
||||
function selectDocument(path, updateHash = false, section = "") {
|
||||
const item = docsByPath.get(path) || docsByPath.get("docs/README.md") || documents[0]; if (!item) return;
|
||||
currentDocument = item; renderReaderList(); renderMarkdown(item);
|
||||
if (updateHash) history.replaceState(null, "", `#doc=${encodeURIComponent(item.path)}`);
|
||||
if (currentDocument !== item) { currentDocument = item; renderReaderList(); renderMarkdown(item); }
|
||||
if (updateHash) history.replaceState(null, "", `#doc=${encodeURIComponent(item.path)}${section ? `§ion=${encodeURIComponent(section)}` : ""}`);
|
||||
requestAnimationFrame(() => scrollToSection(section));
|
||||
}
|
||||
|
||||
function selectTab(tab) {
|
||||
@@ -201,9 +214,14 @@
|
||||
window.document.querySelectorAll("[data-i18n]").forEach(n => n.textContent = t(n.dataset.i18n)); window.document.querySelectorAll("[data-i18n-placeholder]").forEach(n => n.placeholder = t(n.dataset.i18nPlaceholder));
|
||||
session = info; spec = documentSpec; documents = Array.isArray(docBundle.documents) ? docBundle.documents : []; docsByPath = new Map(documents.map(item => [item.path, item]));
|
||||
element("docs-session").textContent = `${t("docsAccount")}: ${session.username}`; element("docs-error").textContent = "";
|
||||
const hash = new URLSearchParams(location.hash.replace(/^#/, "")).get("doc"); selectDocument(hash && docsByPath.has(hash) ? hash : "docs/README.md"); selectTab("reader");
|
||||
const params = new URLSearchParams(location.hash.replace(/^#/, "")), hash = params.get("doc"); currentDocument = null; selectTab("reader"); selectDocument(hash && docsByPath.has(hash) ? hash : "docs/README.md", false, params.get("section") || "");
|
||||
} catch (error) { if (mine === epoch) { clear(); element("docs-error").textContent = error.message; } }
|
||||
}
|
||||
window.addEventListener("hashchange", () => {
|
||||
if (!session) return;
|
||||
const params = new URLSearchParams(location.hash.replace(/^#/, "")), path = params.get("doc");
|
||||
if (path && docsByPath.has(path)) { selectTab("reader"); selectDocument(path, false, params.get("section") || ""); }
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden && session) void checkSession().catch(() => expired()); });
|
||||
window.addEventListener("pageshow", event => { if (event.persisted) { clear(); void boot(); } });
|
||||
setInterval(() => { if (!document.hidden && session) void checkSession().catch(() => expired()); }, 30000);
|
||||
|
||||
+820
-418
File diff suppressed because it is too large.
Load diff
@@ -60,7 +60,7 @@
|
||||
input.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,]/.test(value.trim())) return; event.preventDefault(); try { consume(value); } catch (error) { toast(error.message, true); } });
|
||||
box.append(input); wrapper.append(box, label("p", locked.size ? "listenerStartupLocked" : "listenerAddressesHelp", "fine")); parent.append(wrapper);
|
||||
for (const value of initial) { try { add(value, false); } catch { } }
|
||||
const read = () => { if (input.value.trim()) consume(input.value); return [...values]; }; read.input = input; return read;
|
||||
const read = () => { if (input.value.trim()) consume(input.value); return [...values]; }; read.input = input; read.peek = () => [...values]; return read;
|
||||
}
|
||||
const h2Defaults = { idle_timeout_seconds: 300, max_connection_lifetime_seconds: 0, drain_timeout_seconds: 10 };
|
||||
const effectiveHttp2Settings = binding => ({ ...h2Defaults, ...(envelope?.config.http2 || {}), ...(binding?.http2_settings || {}) });
|
||||
@@ -116,7 +116,17 @@
|
||||
}
|
||||
function addRow(item = { id: `listener-${$("named-listener-rows").children.length + 1}`, name: "", scope: "internal", enabled: true, binding: { address: "127.0.0.1:8181", tls: false, http2: false, http2_settings: null, h2c: false, http3: null } }) {
|
||||
if ($("named-listener-rows").children.length >= 64) { toast(t("listenerLimit"), true); return; }
|
||||
const row = el("fieldset", undefined, "named-listener-row"); row.append(label("legend", "listenerEndpoint")); const grid = el("div", undefined, "vh-grid"); row.append(grid); const b = item.binding || {};
|
||||
const fresh = !item.id || !(envelope?.config.listeners?.endpoints || []).some(endpoint => endpoint.id === item.id);
|
||||
const row = el("fieldset", undefined, `named-listener-row listener-card${fresh ? "" : " is-collapsed"}`);
|
||||
const head = el("button", undefined, "listener-card-head"); head.type = "button"; head.dataset.uiIconName = "none";
|
||||
const headTitle = el("span", undefined, "listener-card-title"), headBadges = el("span", undefined, "listener-card-badges"), headAddresses = el("span", undefined, "listener-card-addresses");
|
||||
head.append(el("span", "", "listener-card-chevron"), headTitle, headAddresses, headBadges);
|
||||
const body = el("div", undefined, "listener-card-body");
|
||||
row.append(head, body);
|
||||
const expand = open => { row.classList.toggle("is-collapsed", !open); head.setAttribute("aria-expanded", String(open)); };
|
||||
head.addEventListener("click", () => expand(row.classList.contains("is-collapsed")));
|
||||
head.setAttribute("aria-expanded", String(fresh));
|
||||
const grid = el("div", undefined, "vh-grid"); body.append(grid); const b = item.binding || {};
|
||||
const id = field(grid, "listener-id", "listenerId", item.id, "text", { required: true, maxLength: 64, pattern: "[A-Za-z0-9_\\-]{1,64}" });
|
||||
const name = field(grid, "listener-name", "listenerName", item.name, "text", { maxLength: 96 });
|
||||
const scope = field(grid, "listener-scope", "listenerScope", item.scope || "internal", "select", { values: [["internal", "listenerInternal"], ["public", "listenerPublic"]] });
|
||||
@@ -127,7 +137,7 @@
|
||||
const enabled = field(grid, "listener-enabled", "vhEnabled", item.enabled !== false, "checkbox");
|
||||
const tls = field(grid, "listener-tls", "vhTls", !!b.tls, "checkbox"); const h2 = field(grid, "listener-h2", "vhHttp2", b.tls && b.http2 !== false, "checkbox"); const h2c = field(grid, "listener-h2c", "listenerH2c", !b.tls && !!b.h2c, "checkbox");
|
||||
const preservedHttp2 = effectiveHttp2Settings(b);
|
||||
const protocolActions = el("div", undefined, "listener-protocol-settings-actions vh-wide"); row.append(protocolActions);
|
||||
const protocolActions = el("div", undefined, "listener-protocol-settings-actions vh-wide"); body.append(protocolActions);
|
||||
const h2Settings = button(protocolActions, "h2Configure", () => {
|
||||
window.rustProxySettings?.select("connections");
|
||||
window.rustProxySettings?.selectHttpTab?.("http2");
|
||||
@@ -146,25 +156,40 @@
|
||||
h2.disabled = !tls.checked; h2c.disabled = tls.checked; h3.disabled = !tls.checked;
|
||||
h2Settings.hidden = !((tls.checked && h2.checked) || (!tls.checked && h2c.checked));
|
||||
h3Settings.hidden = !tls.checked || !h3.checked;
|
||||
syncHead();
|
||||
};
|
||||
const syncHead = () => {
|
||||
headTitle.replaceChildren(el("b", name.value.trim() || id.value.trim() || "-"), el("code", id.value.trim(), "listener-card-id"));
|
||||
let addresses = []; try { addresses = readAddresses.peek ? readAddresses.peek() : []; } catch { }
|
||||
headAddresses.replaceChildren(...addresses.map(value => el("span", value, "certificate-api-chip")));
|
||||
const badges = [[scope.value === "public" ? t("listenerPublic") : t("listenerInternal"), scope.value === "public" ? "warn" : ""]];
|
||||
if (tls.checked) badges.push(["TLS", "live"]);
|
||||
badges.push(["H1", ""]);
|
||||
if ((tls.checked && h2.checked) || (!tls.checked && h2c.checked)) badges.push([tls.checked ? "H2" : "h2c", ""]);
|
||||
if (tls.checked && h3.checked) badges.push(["H3", ""]);
|
||||
if (!enabled.checked) badges.push([t("vhDisabled"), "danger"]);
|
||||
headBadges.replaceChildren(...badges.map(([text, cls]) => el("span", text, `pill ${cls}`.trim())));
|
||||
};
|
||||
for (const input of [tls, h2, h2c, h3]) input.addEventListener("change", sync);
|
||||
for (const type of ["input", "change", "keyup"]) row.addEventListener(type, syncHead); body.addEventListener("click", () => setTimeout(syncHead));
|
||||
sync();
|
||||
const removeButton = button(row, "remove", () => { if (startupLocked) return; const users = (envelope?.config.vhosts || []).filter(v => v.frontend.listener_ids?.includes(id.value.trim())); if (users.length) { toast(`${t("listenerInUse")}: ${users.map(v => v.id).join(", ")}`, true); return; } row.remove(); setSettingsDirty("listeners-form"); });
|
||||
const removeButton = button(body, "remove", () => { if (startupLocked) return; const users = (envelope?.config.vhosts || []).filter(v => v.frontend.listener_ids?.includes(id.value.trim())); if (users.length) { toast(`${t("listenerInUse")}: ${users.map(v => v.id).join(", ")}`, true); return; } row.remove(); setSettingsDirty("listeners-form"); });
|
||||
if (startupLocked) {
|
||||
row.classList.add("listener-startup-locked");
|
||||
enabled.disabled = true;
|
||||
tls.disabled = true;
|
||||
removeButton.disabled = true;
|
||||
removeButton.title = t("listenerStartupLocked");
|
||||
row.append(label("p", "listenerStartupLocked", "fine"));
|
||||
body.append(label("p", "listenerStartupLocked", "fine"));
|
||||
}
|
||||
row.read = () => {
|
||||
const readRow = () => {
|
||||
const addresses = readAddresses();
|
||||
if (!addresses.length || addresses.length > 16 || new Set(addresses).size !== addresses.length) throw fieldError(readAddresses.input, t("listenerAddressesInvalid"));
|
||||
if (addresses.length > 1 && addresses.some(value => /^0\.0\.0\.0:/.test(value) || /^\[?::\]?:/.test(value))) throw fieldError(readAddresses.input, t("listenerAddressesExplicit"));
|
||||
const http2Enabled = (tls.checked && h2.checked) || (!tls.checked && h2c.checked);
|
||||
return { id: id.value.trim(), name: name.value.trim(), scope: scope.value, enabled: enabled.checked, binding: { address: addresses[0], tls: tls.checked, http2: tls.checked && h2.checked, http2_settings: http2Enabled ? preservedHttp2 : null, h2c: !tls.checked && h2c.checked, http3: tls.checked && h3.checked ? (preservedHttp3 || { ...h3Defaults }) : null }, additional_addresses: addresses.slice(1) };
|
||||
};
|
||||
row.read = () => { try { return readRow(); } catch (error) { expand(true); throw error; } };
|
||||
$("named-listener-rows").append(row);
|
||||
}
|
||||
$("add-named-listener").addEventListener("click", () => { addRow(); setSettingsDirty("listeners-form"); });
|
||||
|
||||
@@ -3,7 +3,9 @@ window.rustProxyPrometheusToken = (() => {
|
||||
let isConfigured = false;
|
||||
const hideSecret = () => { $("prom-token-secret").textContent = ""; $("prom-token-secret-wrap").hidden = true; };
|
||||
function showStatus() {
|
||||
$("prom-token-status").textContent = t(isConfigured ? "promTokenConfigured" : "promTokenMissing");
|
||||
$("prom-token-status").textContent = t(isConfigured ? "promTokenConfigured" : "promTokenMissingShort");
|
||||
$("prom-token-status").className = `pill ${isConfigured ? "live" : "warn"}`;
|
||||
$("prom-token-status").title = isConfigured ? "" : t("promTokenMissing");
|
||||
$("prom-token-revoke").disabled = !isConfigured;
|
||||
}
|
||||
async function refresh() {
|
||||
@@ -25,11 +27,15 @@ window.rustProxyPrometheusToken = (() => {
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
$("prom-token-revoke").addEventListener("click", async () => {
|
||||
if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return;
|
||||
if (!(await appConfirm(t("promTokenRevokeConfirm"), { danger: true }))) return;
|
||||
try {
|
||||
await api("/api/prometheus-token", { method: "DELETE" });
|
||||
isConfigured = false; hideSecret(); showStatus(); window.rustProxySettings?.render?.();
|
||||
} catch (error) { toast(error.message, true); }
|
||||
});
|
||||
$("prom-token-secret-copy").addEventListener("click", async () => {
|
||||
try { await navigator.clipboard.writeText($("prom-token-secret").textContent); toast(t("copied")); }
|
||||
catch { const range = document.createRange(); range.selectNodeContents($("prom-token-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
|
||||
});
|
||||
return { configured: () => isConfigured, refresh, hideSecret, reset() { isConfigured = false; hideSecret(); showStatus(); } };
|
||||
})();
|
||||
+21
-46
@@ -71,16 +71,6 @@
|
||||
const target = $("api-tokens-card");
|
||||
if (target) { target.scrollIntoView({ block: "start" }); target.focus({ preventScroll: true }); }
|
||||
}
|
||||
$("api-tokens-security-link")?.addEventListener("click", event => {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
select("security");
|
||||
if (typeof location !== "undefined" && ["http:", "https:"].includes(location.protocol)) {
|
||||
const url = new URL($("api-tokens-security-link").href);
|
||||
history.replaceState({ ...(history.state || {}), panel: "settings", settingsTab: "security" }, "", `${url.pathname}${url.search}${url.hash}`);
|
||||
}
|
||||
scrollToApiTokens();
|
||||
});
|
||||
const policyTabs = [...document.querySelectorAll("[data-policy-settings-tab]")].filter(button => typeof button.addEventListener === "function" && typeof button.setAttribute === "function");
|
||||
function selectPolicyTab(name, focus = false) {
|
||||
if (!policyTabs.some(button => button.dataset.policySettingsTab === name)) return;
|
||||
@@ -170,7 +160,7 @@
|
||||
if (!envelope) return; const p = { ...defaults, ...envelope.config.prometheus };
|
||||
if (!settingsDirty.has("prometheus-form")) {
|
||||
$("prom-enabled").checked = p.enabled; $("prom-listen").value = p.listen; $("prom-path").value = p.path;
|
||||
$("prom-cidrs").value = p.allowed_cidrs.join("\n"); $("prom-trusted-no-token").checked = !!p.allow_trusted_network_without_token;
|
||||
$("prom-cidrs").replaceChildren(window.rustProxyChipInput.create({ className: "prom-cidr-editor", values: p.allowed_cidrs, placeholder: "127.0.0.0/8 / 10.0.0.0/24", label: t("prometheusCidrs"), limit: 64, validate: value => window.rustProxyChipInput.validCidr(value) && (value.includes("/") ? value : value.includes(":") ? `${value}/128` : `${value}/32`), invalidMessage: t("apiTokenCidrInvalid") })); $("prom-trusted-no-token").checked = !!p.allow_trusted_network_without_token;
|
||||
for (const [id, key] of [["system", "include_system"], ["vhosts", "include_vhosts"], ["traffic", "include_traffic"], ["backends", "include_backends"], ["docker-vhosts", "include_docker_vhosts"], ["domains", "include_cache_domains"], ["streams", "include_streams"], ["logging", "include_logging"]]) $(`prom-${id}`).checked = p[key];
|
||||
}
|
||||
const status = latestStatus?.prometheus;
|
||||
@@ -209,40 +199,7 @@
|
||||
$("admin-listen").disabled = listenLocked; $("admin-listen-lock-note").hidden = !listenLocked;
|
||||
const syncAdminTls = () => { $("admin-certificate").disabled = !$("admin-tls").checked; }; syncAdminTls();
|
||||
$("admin-status").textContent = adminStatus?.restart_required ? t("restartPending") : adminStatus?.active?.tls ? `${t("administrationActiveHttps")}: ${adminStatus.active.listen}` : `${t("administrationActiveHttp")}: ${adminStatus?.active?.listen || latestStatus?.admin_listen || "-"}`;
|
||||
const runtime = latestStatus?.runtime || {};
|
||||
const system = latestStatus?.system || {};
|
||||
const hasMetric = value => value !== null && value !== undefined && Number.isFinite(Number(value));
|
||||
const humanCount = value => hasMetric(value) ? Number(value).toLocaleString(locale()) : t("unavailable");
|
||||
const humanBytes = value => hasMetric(value) ? bytes(Number(value)) : t("unavailable");
|
||||
const humanUptime = value => hasMetric(value) ? uptime(Number(value)) : t("unavailable");
|
||||
const percent = value => hasMetric(value) ? `${Number(value).toLocaleString(locale(), { maximumFractionDigits: 1 })}%` : t("unavailable");
|
||||
const ram = hasMetric(system.memory_used_bytes) || hasMetric(system.memory_total_bytes)
|
||||
? `${humanBytes(system.memory_used_bytes)} / ${humanBytes(system.memory_total_bytes)}` : t("unavailable");
|
||||
for (const [id, value] of [
|
||||
["runtime-platform", runtime.platform],
|
||||
["runtime-operating-system", runtime.operating_system],
|
||||
["runtime-kernel-version", runtime.kernel_version],
|
||||
["runtime-architecture", runtime.architecture],
|
||||
["runtime-logical-cpus", humanCount(system.logical_cpus)],
|
||||
["runtime-cpu-usage", percent(system.cpu_percent)],
|
||||
["runtime-system-memory", ram],
|
||||
["runtime-system-uptime", humanUptime(system.system_uptime_seconds)],
|
||||
["runtime-statistics-source", runtime.statistics_source],
|
||||
["runtime-data-directory", runtime.data_directory],
|
||||
["runtime-database-path", runtime.database_path]
|
||||
]) { const node = $(id); if (node) node.textContent = value ?? t("unavailable"); }
|
||||
const certificateRuntime = runtime.certificate_runtime || {};
|
||||
const availability = flag => flag === true ? t("runtimeAvailable") : flag === false ? t("runtimeUnavailable") : t("unavailable");
|
||||
const modeLabel = certificateRuntime.status === "unavailable" ? t("certificateRuntimeUnavailable") : certificateRuntime.status === "ready" && certificateRuntime.mode === "managed" ? t("certificateRuntimeManaged") : certificateRuntime.status === "ready" && certificateRuntime.mode === "system" ? t("certificateRuntimeSystem") : t("certificateRuntimePreparing");
|
||||
const versioned = (flag, version) => version && flag === true ? `${availability(flag)} · ${version}` : availability(flag);
|
||||
for (const [id, value] of [
|
||||
["runtime-acme-mode", modeLabel],
|
||||
["runtime-acme-status", certificateRuntime.message ? t(certificateRuntime.message) : t("unavailable")],
|
||||
["runtime-python", versioned(certificateRuntime.python, certificateRuntime.python_version)],
|
||||
["runtime-pip", versioned(certificateRuntime.pip, certificateRuntime.pip_version)],
|
||||
["runtime-certbot", versioned(certificateRuntime.certbot, certificateRuntime.certbot_version)],
|
||||
["runtime-acme-directory", certificateRuntime.managed_directory]
|
||||
]) { const node = $(id); if (node) node.textContent = value || t("unavailable"); }
|
||||
window.rustProxySystemInfo?.render(latestStatus);
|
||||
|
||||
const policy = envelope.config.tls?.policy || { tls12: true, tls13: true, cipher_suites: [] };
|
||||
if (!settingsDirty.has("tls-policy-form")) { $("tls-policy-12").checked = policy.tls12 !== false; $("tls-policy-13").checked = policy.tls13 !== false; $("tls-policy-ciphers").value = (policy.cipher_suites || []).join("\n"); $("tls-policy-pqc").checked = policy.post_quantum === true; }
|
||||
@@ -281,7 +238,7 @@
|
||||
});
|
||||
bindSettingsForm("prometheus-form", next => {
|
||||
next.prometheus = {
|
||||
enabled: $("prom-enabled").checked, listen: $("prom-listen").value.trim(), path: $("prom-path").value.trim(), allowed_cidrs: $("prom-cidrs").value.split(/[\n,]/).map(v => v.trim()).filter(Boolean), bearer_token_env: envelope?.config?.prometheus?.bearer_token_env || null, allow_trusted_network_without_token: $("prom-trusted-no-token").checked,
|
||||
enabled: $("prom-enabled").checked, listen: $("prom-listen").value.trim(), path: $("prom-path").value.trim(), allowed_cidrs: $("prom-cidrs").firstElementChild?.read?.() || [], bearer_token_env: envelope?.config?.prometheus?.bearer_token_env || null, allow_trusted_network_without_token: $("prom-trusted-no-token").checked,
|
||||
include_system: $("prom-system").checked, include_vhosts: $("prom-vhosts").checked, include_traffic: $("prom-traffic").checked, include_backends: $("prom-backends").checked, include_docker_vhosts: $("prom-docker-vhosts").checked, include_cache_domains: $("prom-domains").checked, include_streams: $("prom-streams").checked, include_logging: $("prom-logging").checked
|
||||
};
|
||||
}, "prometheus");
|
||||
@@ -303,6 +260,24 @@
|
||||
const text = await response.text(); if (epoch !== authEpoch || !authenticated) return; $("prom-preview-output").textContent = text.slice(0, 262144); $("prom-preview-output").hidden = false;
|
||||
} catch (error) { if (epoch === authEpoch) toast(error.message, true); } finally { button.disabled = false; }
|
||||
});
|
||||
const HELP_CLAMP_LENGTH = 220;
|
||||
function decorateSettings() {
|
||||
const panel = $("panel-settings"); if (!panel) return;
|
||||
const restart = t("restartFieldBadge");
|
||||
panel.querySelectorAll("[data-restart]").forEach(node => { const span = node.querySelector(":scope > span"); if (span && span.dataset.restartBadge !== restart) span.dataset.restartBadge = restart; node.title = t("restartFieldHelp"); });
|
||||
panel.querySelectorAll(".settings-page .fine:not([role=status]):not(.help-clamp)").forEach(node => {
|
||||
if (node.id?.endsWith("-status") || node.closest(".certificate-api-credential-item, .acl-picker, .docker-container-state, dialog")) return;
|
||||
if ((node.textContent || "").trim().length < HELP_CLAMP_LENGTH) return;
|
||||
node.classList.add("help-clamp"); node.tabIndex = 0; node.setAttribute("aria-expanded", "false");
|
||||
const toggle = () => { const open = !node.classList.contains("is-open"); node.classList.toggle("is-open", open); node.setAttribute("aria-expanded", String(open)); };
|
||||
node.addEventListener("click", event => { if (event.target.closest("a, button")) return; toggle(); });
|
||||
node.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); toggle(); } });
|
||||
});
|
||||
}
|
||||
let decorateQueued = false;
|
||||
const queueDecorate = () => { if (decorateQueued) return; decorateQueued = true; requestAnimationFrame(() => { decorateQueued = false; decorateSettings(); }); };
|
||||
if (typeof MutationObserver === "function" && $("panel-settings")) new MutationObserver(queueDecorate).observe($("panel-settings"), { childList: true, subtree: true });
|
||||
queueDecorate();
|
||||
window.rustProxySettings = { select, selectHttpTab, syncLocation, render, refreshSearch: applySettingsSearch, current: () => active, scrollToApiTokens, reset() { if (search) search.value = ""; applySettingsSearch(); select(validTab(rememberedTab) ? rememberedTab : "appearance", false, false); selectPolicyTab("block-allow"); selectCacheTab("general"); selectLoggingTab("outputs"); selectHttpTab("http2"); window.rustProxyCertificateApi?.reset(); window.rustProxyApiTokens?.reset?.(); window.rustProxyPrometheusToken?.reset?.(); $("prom-preview-output").textContent = ""; $("prom-preview-output").hidden = true; } };
|
||||
select(active); render();
|
||||
})();
|
||||
@@ -0,0 +1,245 @@
|
||||
(() => {
|
||||
"use strict";
|
||||
const HISTORY = 60;
|
||||
const history = { sampled: null, cpu: [], process: [], rx: [], tx: [] };
|
||||
let latest = null;
|
||||
const known = value => value !== null && value !== undefined && value !== "" && Number.isFinite(Number(value));
|
||||
const na = () => t("unavailable");
|
||||
const size = value => known(value) ? bytes(Number(value)) : na();
|
||||
const count = value => known(value) ? Number(value).toLocaleString(locale()) : na();
|
||||
const percent = value => known(value) ? `${Number(value).toLocaleString(locale(), { maximumFractionDigits: 1 })}%` : na();
|
||||
const ratio = (part, whole) => known(part) && known(whole) && Number(whole) > 0 ? Math.max(0, Math.min(100, Number(part) / Number(whole) * 100)) : 0;
|
||||
const rate = value => known(value) ? `${bytes(Number(value))}/s` : na();
|
||||
const setText = (id, value) => { const node = $(id); if (node) node.textContent = value ?? na(); };
|
||||
const setMeter = (id, value) => {
|
||||
const node = $(id); if (!node) return;
|
||||
node.style.width = `${Math.max(0, Math.min(100, value))}%`;
|
||||
node.classList.toggle("is-high", value >= 90);
|
||||
};
|
||||
const push = (list, value) => { list.push(known(value) ? Number(value) : 0); if (list.length > HISTORY) list.shift(); };
|
||||
const points = (values, max) => {
|
||||
if (values.length < 2) return "0,58 300,58";
|
||||
const top = Math.max(max || 0, ...values, 1e-9);
|
||||
return values.map((value, index) => `${(index / (values.length - 1) * 300).toFixed(1)},${(58 - value / top * 52).toFixed(1)}`).join(" ");
|
||||
};
|
||||
const shared = name => {
|
||||
try {
|
||||
const value = { cpu: () => systemSamples, process: () => processCpuSamples, rx: () => networkRxSamples, tx: () => networkTxSamples }[name]();
|
||||
return Array.isArray(value) ? value : [];
|
||||
} catch { return []; }
|
||||
};
|
||||
const series = name => { const own = history[name], overview = shared(name); return overview.length > own.length ? overview.slice(-HISTORY) : own; };
|
||||
const setLine = (id, values, max) => { const node = $(id); if (node) node.setAttribute("points", points(values, max)); };
|
||||
|
||||
function record(system) {
|
||||
const sampled = system.sampled_at_ms ?? null;
|
||||
if (sampled === null || sampled === history.sampled) return;
|
||||
history.sampled = sampled;
|
||||
push(history.cpu, system.cpu_percent);
|
||||
push(history.process, system.process_cpu_percent);
|
||||
push(history.rx, system.network_rx_bytes_per_second);
|
||||
push(history.tx, system.network_tx_bytes_per_second);
|
||||
}
|
||||
|
||||
function liveState() {
|
||||
const options = window.rustProxyRefresh?.current?.() || {};
|
||||
return options.live_enabled !== false && Number(options.system_info_seconds) > 0;
|
||||
}
|
||||
|
||||
function renderHost(status, runtime, system) {
|
||||
setText("system-info-title", runtime.operating_system || t("systemInformation"));
|
||||
const environment = system.environment ? `${t("systemInfoEnvironment")}: ${system.environment}. ` : "";
|
||||
setText("system-info-help", `${environment}${t("systemInformationHelp")}`);
|
||||
const live = liveState(), pill = $("system-info-live");
|
||||
if (pill) { pill.textContent = t(live ? "systemInfoLive" : "systemInfoManual"); pill.classList.toggle("live", live); }
|
||||
const note = $("system-info-refresh-note"); if (note) note.hidden = live;
|
||||
const age = known(system.sampled_at_ms) ? Math.max(0, Math.round((Date.now() - Number(system.sampled_at_ms)) / 1000)) : null;
|
||||
setText("system-info-sample-age", age === null ? "-" : t("systemInfoSampledAgo").replace("{seconds}", String(age)));
|
||||
setText("runtime-architecture", runtime.architecture || na());
|
||||
setText("runtime-kernel-version", runtime.kernel_version || na());
|
||||
setText("runtime-logical-cpus", count(system.logical_cpus));
|
||||
setText("system-info-ram-total", size(system.memory_total_bytes));
|
||||
setText("system-info-swap", known(system.system_swap_total_bytes) && Number(system.system_swap_total_bytes) > 0
|
||||
? `${size(system.system_swap_used_bytes)} / ${size(system.system_swap_total_bytes)}` : t("systemInfoNone"));
|
||||
setText("runtime-system-uptime", known(system.system_uptime_seconds) ? uptime(Number(system.system_uptime_seconds)) : na());
|
||||
const started = Number(system.process_start_time_seconds), sampled = Number(system.sampled_at_ms);
|
||||
setText("system-info-process-uptime", known(system.process_start_time_seconds) && known(system.sampled_at_ms) ? uptime(sampled / 1000 - started) : na());
|
||||
setText("system-info-version", status.version ? `v${status.version}` : "-");
|
||||
}
|
||||
|
||||
function renderTiles(system, memory) {
|
||||
setText("runtime-cpu-usage", percent(system.cpu_percent));
|
||||
setText("system-info-cpu-note", known(system.logical_cpus) ? t("systemInfoCores").replace("{count}", count(system.logical_cpus)) : na());
|
||||
setLine("system-info-cpu-line", series("cpu"), 100);
|
||||
setText("system-info-process-cpu", percent(system.process_cpu_percent));
|
||||
setLine("system-info-process-cpu-line", series("process"));
|
||||
const load = Array.isArray(system.load_average) ? system.load_average : [];
|
||||
setText("system-info-load", load.length ? fmt(load[0], 2) : na());
|
||||
setText("system-info-load-note", load.length > 2 ? `5 min ${fmt(load[1], 2)} · 15 min ${fmt(load[2], 2)}` : t("systemInfoLoadUnavailable"));
|
||||
setMeter("system-info-load-meter", load.length ? ratio(load[0], system.logical_cpus) : 0);
|
||||
setText("runtime-system-memory", size(system.memory_used_bytes));
|
||||
const rss = memory.process_rss_bytes ?? system.process_rss_bytes;
|
||||
setText("system-info-memory-note", `${t("systemInfoOf")} ${size(system.memory_total_bytes)} · RustProxy ${ratio(rss, system.memory_used_bytes).toFixed(0)}%`);
|
||||
setMeter("system-info-memory-meter", ratio(system.memory_used_bytes, system.memory_total_bytes));
|
||||
setText("system-info-fds", count(system.open_fds));
|
||||
setText("system-info-fds-note", t("systemInfoFdsNote").replace("{limit}", count(system.max_fds)).replace("{count}", count(system.process_threads)));
|
||||
setMeter("system-info-fds-meter", ratio(system.open_fds, system.max_fds));
|
||||
}
|
||||
|
||||
function renderProcess(system, memory) {
|
||||
const rss = Number(memory.process_rss_bytes ?? system.process_rss_bytes) || 0;
|
||||
setText("system-info-rss", size(memory.process_rss_bytes ?? system.process_rss_bytes));
|
||||
const split = $("system-info-rss-split");
|
||||
if (split) {
|
||||
const parts = { h: memory.cache_hot_bytes, t: memory.cache_transient_bytes, a: system.process_rss_anon_bytes, f: system.process_rss_file_bytes };
|
||||
for (const [name, value] of Object.entries(parts)) { const node = split.querySelector(`.${name}`); if (node) node.style.width = `${ratio(value, rss)}%`; }
|
||||
}
|
||||
setText("system-info-legend-hot", size(memory.cache_hot_bytes));
|
||||
setText("system-info-legend-transient", size(memory.cache_transient_bytes));
|
||||
setText("system-info-legend-anon", size(system.process_rss_anon_bytes));
|
||||
setText("system-info-legend-file", size(system.process_rss_file_bytes));
|
||||
setText("system-info-hot", `${size(memory.cache_hot_bytes)} / ${size(memory.cache_hot_limit_bytes)}`);
|
||||
setMeter("system-info-hot-meter", ratio(memory.cache_hot_bytes, memory.cache_hot_limit_bytes));
|
||||
setText("system-info-transient", `${size(memory.cache_transient_bytes)} / ${size(memory.cache_transient_limit_bytes)}`);
|
||||
setMeter("system-info-transient-meter", ratio(memory.cache_transient_bytes, memory.cache_transient_limit_bytes));
|
||||
setText("system-info-transforms", known(memory.transform_max_inflight) ? `${count(memory.transform_inflight)}/${count(memory.transform_max_inflight)} · ${size(memory.transform_budget_bytes)}` : na());
|
||||
setMeter("system-info-transforms-meter", ratio(memory.transform_reserved_bytes, memory.transform_budget_bytes));
|
||||
setText("system-info-started", known(system.process_start_time_seconds) ? formatDateTime(Number(system.process_start_time_seconds) * 1000) : na());
|
||||
setText("system-info-virtual", size(system.process_virtual_memory_bytes));
|
||||
setText("system-info-process-swap", size(system.process_swap_bytes));
|
||||
setText("system-info-io", known(system.process_read_bytes) || known(system.process_write_bytes) ? `${size(system.process_read_bytes)} / ${size(system.process_write_bytes)}` : na());
|
||||
setText("system-info-cgroup", known(system.cgroup_memory_max_bytes) ? `${size(system.cgroup_memory_current_bytes)} / ${size(system.cgroup_memory_max_bytes)}` : t("systemInfoNoLimit"));
|
||||
}
|
||||
|
||||
function renderNetwork(system) {
|
||||
setText("system-info-network-rate", known(system.network_rx_bytes_per_second) ? `↓ ${rate(system.network_rx_bytes_per_second)} · ↑ ${rate(system.network_tx_bytes_per_second)}` : na());
|
||||
const interfaces = Array.isArray(system.network_interfaces) ? system.network_interfaces : [];
|
||||
const active = interfaces.filter(item => Number(item.rx_bytes) > 0 || Number(item.tx_bytes) > 0);
|
||||
const idle = interfaces.filter(item => !active.includes(item));
|
||||
const body = $("system-info-network-rows");
|
||||
if (body) {
|
||||
const rows = active.map(item => {
|
||||
const row = document.createElement("tr"), name = document.createElement("td"), code = document.createElement("code");
|
||||
code.textContent = item.name; name.append(code);
|
||||
const cells = [rate(item.rx_bytes_per_second), rate(item.tx_bytes_per_second), `${size(item.rx_bytes)} / ${size(item.tx_bytes)}`].map(value => { const cell = document.createElement("td"); cell.textContent = value; return cell; });
|
||||
row.append(name, ...cells); return row;
|
||||
});
|
||||
if (!rows.length) { const row = document.createElement("tr"), cell = document.createElement("td"); cell.colSpan = 4; cell.className = "fine"; cell.textContent = t("systemInfoNoInterfaces"); row.append(cell); rows.push(row); }
|
||||
body.replaceChildren(...rows);
|
||||
}
|
||||
const details = $("system-info-network-idle");
|
||||
if (details) {
|
||||
details.hidden = !idle.length;
|
||||
setText("system-info-network-idle-summary", t("systemInfoIdleInterfaces").replace("{count}", String(idle.length)));
|
||||
setText("system-info-network-idle-list", idle.map(item => item.name).join(", "));
|
||||
}
|
||||
const rx = series("rx"), tx = series("tx"), max = Math.max(...rx, ...tx, 1);
|
||||
setLine("system-info-rx-line", rx, max);
|
||||
setLine("system-info-tx-line", tx, max);
|
||||
setText("system-info-network-history-value", known(system.network_rx_bytes_per_second) ? `${rate(system.network_rx_bytes_per_second)} / ${rate(system.network_tx_bytes_per_second)}` : na());
|
||||
}
|
||||
|
||||
function renderToolchain(runtime) {
|
||||
const certificate = runtime.certificate_runtime || {};
|
||||
const mode = certificate.status === "unavailable" ? t("certificateRuntimeUnavailable")
|
||||
: certificate.status === "ready" && certificate.mode === "managed" ? t("certificateRuntimeManaged")
|
||||
: certificate.status === "ready" && certificate.mode === "system" ? t("certificateRuntimeSystem") : t("certificateRuntimePreparing");
|
||||
const pill = $("runtime-acme-mode");
|
||||
if (pill) { pill.textContent = mode; pill.classList.toggle("live", certificate.status === "ready"); }
|
||||
for (const [tool, version] of [["python", "python_version"], ["pip", "pip_version"], ["certbot", "certbot_version"]]) {
|
||||
const flag = certificate[tool];
|
||||
setText(`runtime-${tool}`, flag === true ? (certificate[version] || t("runtimeAvailable")) : flag === false ? t("runtimeUnavailable") : na());
|
||||
const chip = $(`system-info-${tool}-chip`);
|
||||
if (chip) { chip.classList.toggle("is-ready", flag === true); chip.classList.toggle("is-missing", flag === false); }
|
||||
}
|
||||
setText("runtime-acme-status", certificate.message ? t(certificate.message) : na());
|
||||
setText("runtime-acme-directory", certificate.managed_directory || na());
|
||||
}
|
||||
|
||||
function renderSources(runtime) {
|
||||
const list = $("runtime-statistics-source"); if (!list) return;
|
||||
const sources = String(runtime.statistics_source || "").split("+").map(item => item.trim()).filter(Boolean);
|
||||
list.replaceChildren(...(sources.length ? sources : [na()]).map(source => {
|
||||
const chip = document.createElement("div"), label = document.createElement("dt"), value = document.createElement("dd");
|
||||
chip.className = "pr-chip"; label.textContent = t("systemInfoSource"); value.textContent = source;
|
||||
chip.append(label, value); return chip;
|
||||
}));
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
latest = status || {};
|
||||
const runtime = latest.runtime || {}, system = latest.system || {}, memory = latest.memory_accounting || {};
|
||||
record(system);
|
||||
renderHost(latest, runtime, system);
|
||||
renderTiles(system, memory);
|
||||
renderProcess(system, memory);
|
||||
renderNetwork(system);
|
||||
renderToolchain(runtime);
|
||||
setText("runtime-data-directory", runtime.data_directory || na());
|
||||
setText("runtime-database-path", runtime.database_path || na());
|
||||
renderSources(runtime);
|
||||
}
|
||||
|
||||
function diagnostics() {
|
||||
const status = latest || {}, runtime = status.runtime || {}, system = status.system || {}, memory = status.memory_accounting || {};
|
||||
const certificate = runtime.certificate_runtime || {};
|
||||
const load = Array.isArray(system.load_average) ? system.load_average.map(value => fmt(value, 2)).join(" / ") : na();
|
||||
const interfaces = (system.network_interfaces || []).map(item => ` ${item.name}: rx ${size(item.rx_bytes)} (${rate(item.rx_bytes_per_second)}), tx ${size(item.tx_bytes)} (${rate(item.tx_bytes_per_second)})`);
|
||||
return [
|
||||
`RustProxy ${status.version || ""}`.trim(),
|
||||
`Generated: ${new Date().toISOString()}`,
|
||||
"",
|
||||
"[host]",
|
||||
`os: ${runtime.operating_system || na()}`,
|
||||
`platform: ${runtime.platform || na()} · environment: ${system.environment || na()}`,
|
||||
`kernel: ${runtime.kernel_version || na()} · arch: ${runtime.architecture || na()}`,
|
||||
`cpus: ${count(system.logical_cpus)} · cpu: ${percent(system.cpu_percent)} · load: ${load}`,
|
||||
`memory: ${size(system.memory_used_bytes)} / ${size(system.memory_total_bytes)} · swap: ${size(system.system_swap_used_bytes)} / ${size(system.system_swap_total_bytes)}`,
|
||||
`uptime: ${known(system.system_uptime_seconds) ? uptime(Number(system.system_uptime_seconds)) : na()}`,
|
||||
"",
|
||||
"[process]",
|
||||
`cpu: ${percent(system.process_cpu_percent)} · threads: ${count(system.process_threads)} · fds: ${count(system.open_fds)} / ${count(system.max_fds)}`,
|
||||
`rss: ${size(memory.process_rss_bytes ?? system.process_rss_bytes)} (anon ${size(system.process_rss_anon_bytes)}, file ${size(system.process_rss_file_bytes)})`,
|
||||
`hot cache: ${size(memory.cache_hot_bytes)} / ${size(memory.cache_hot_limit_bytes)} · transient: ${size(memory.cache_transient_bytes)} / ${size(memory.cache_transient_limit_bytes)}`,
|
||||
`transforms: ${count(memory.transform_inflight)} / ${count(memory.transform_max_inflight)} · budget ${size(memory.transform_budget_bytes)}`,
|
||||
`cgroup: ${size(system.cgroup_memory_current_bytes)} / ${size(system.cgroup_memory_max_bytes)}`,
|
||||
`started: ${known(system.process_start_time_seconds) ? new Date(Number(system.process_start_time_seconds) * 1000).toISOString() : na()}`,
|
||||
"",
|
||||
"[network]",
|
||||
...(interfaces.length ? interfaces : [` ${na()}`]),
|
||||
"",
|
||||
"[certificates]",
|
||||
`status: ${certificate.status || na()} · mode: ${certificate.mode || na()}`,
|
||||
`python: ${certificate.python_version || na()} · pip: ${certificate.pip_version || na()} · certbot: ${certificate.certbot_version || na()}`,
|
||||
"",
|
||||
"[paths]",
|
||||
`data: ${runtime.data_directory || na()}`,
|
||||
`database: ${runtime.database_path || na()}`,
|
||||
`acme: ${certificate.managed_directory || na()}`,
|
||||
`sources: ${runtime.statistics_source || na()}`
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function copyText(value) {
|
||||
try { await navigator.clipboard.writeText(value); return true; }
|
||||
catch {
|
||||
const area = document.createElement("textarea");
|
||||
area.value = value; area.setAttribute("readonly", ""); area.className = "system-info-clipboard";
|
||||
document.body.append(area); area.select();
|
||||
const copied = document.execCommand("copy"); area.remove(); return copied;
|
||||
}
|
||||
}
|
||||
|
||||
$("system-info-copy")?.addEventListener("click", async () => {
|
||||
if (await copyText(diagnostics())) toast(t("copied")); else toast(t("systemInfoCopyFailed"), true);
|
||||
});
|
||||
document.querySelectorAll("#settings-page-system-info [data-copy-from]").forEach(button => {
|
||||
button.addEventListener("click", async () => {
|
||||
const value = $(button.dataset.copyFrom)?.textContent || "";
|
||||
if (!value || value === na()) return;
|
||||
if (await copyText(value)) toast(t("copied")); else toast(t("systemInfoCopyFailed"), true);
|
||||
});
|
||||
});
|
||||
|
||||
window.rustProxySystemInfo = { render, diagnostics };
|
||||
})();
|
||||
@@ -1,4 +1,5 @@
|
||||
"use strict";
|
||||
let vhostCacheRulesEditor = null;
|
||||
let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null;
|
||||
const chartHistory = new Map();
|
||||
const backendTrafficHistory = new Map();
|
||||
@@ -59,7 +60,7 @@ const defaults = () => ({
|
||||
|
||||
function activateTab(name) { document.querySelectorAll("#vhost-tabs button").forEach(b => { const active = b.dataset.tab === name; b.classList.toggle("active", active); b.setAttribute("aria-pressed", String(active)); b.setAttribute("aria-selected", String(active)); b.tabIndex = active ? 0 : -1; }); container.querySelectorAll(".vh-group").forEach(g => g.hidden = g.dataset.tab !== name); }
|
||||
function initTabs() { const tabs = $("vhost-tabs"); tabs.replaceChildren(); tabs.setAttribute("role", "tablist"); for (const [name, key] of [["details", "vhDetailsTab"], ["backends", "vhBackendPool"], ["health", "vhHealth"], ["locations", "vhLocations"], ["auth", "vhTabAuth"], ["ssl", "vhSsl"], ["cache", "vhCache"], ["compression", "vhCompression"], ["transform", "vhTransform"], ["security", "vhSecurity"], ["pages", "vhPages"], ["advanced", "advanced"]]) { const b = button(key, () => activateTab(name)); b.dataset.tab = name; b.setAttribute("role", "tab"); b.addEventListener("keydown", event => { const buttons = [...tabs.querySelectorAll("button")], index = buttons.indexOf(b); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % buttons.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + buttons.length - 1) % buttons.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = buttons.length - 1; else return; event.preventDefault(); activateTab(buttons[next].dataset.tab); buttons[next].focus(); }); tabs.append(b); } activateTab("details"); }
|
||||
function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) } }; }
|
||||
function collectCache() { const tri = name => str(name) === "" ? null : str(name) === "on", number = (name, mul = 1) => { if (str(name) === "") return null; const value = Number(str(name)) * mul; if (!Number.isSafeInteger(value)) throw new Error(t("vhJsonInvalid")); return value; }; return { enabled: tri("vh-cache-enabled"), max_ttl_seconds: number("vh-cache-ttl"), default_ttl_seconds: number("vh-cache-default"), max_object_bytes: number("vh-cache-object", 1024), bypass_query: tri("vh-cache-query"), static_ignore_cookies: tri("vh-cache-static-cookie"), static_extensions: yes("vh-cache-static-custom") ? lines(str("vh-cache-static-extensions")).map(v => v.replace(/^\./, "").toLowerCase()) : null, expose_status: tri("vh-cache-status"), expose_hits: tri("vh-cache-hits"), expose_cache_status: tri("vh-cache-rfc"), expose_resident_age: tri("vh-cache-resident-age"), expose_only_hits: tri("vh-cache-only-hits"), bypass_prefixes: yes("vh-cache-prefix-custom") ? lines(str("vh-cache-prefixes")) : null, unsafe_force: { enabled: yes("vh-cache-force-enabled"), targets: lines(str("vh-cache-force-targets")) }, rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.read() : [], ignore_global_rules: vhostCacheRulesEditor ? vhostCacheRulesEditor.ignoreGlobal() : false }; }
|
||||
function collectCompression() { const tri = name => str(name) === "" ? null : str(name) === "on"; return { enabled: tri("vh-compression-enabled"), zstd: tri("vh-compression-zstd"), br: tri("vh-compression-br"), gzip: tri("vh-compression-gzip"), deflate: tri("vh-compression-deflate") }; }
|
||||
function collectTransform() {
|
||||
const tri = name => str(name) === "" ? null : str(name) === "on";
|
||||
|
||||
@@ -528,6 +528,10 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
const forceTargets = field(unsafeCacheFields, "vh-cache-force-targets", "vhCacheForceTargets", (cache.unsafe_force?.targets || []).join("\n"), "textarea", { rows: 3, maxLength: 65536 });
|
||||
const syncForceCache = () => { forceTargets.disabled = !forceCache.checked; }; forceCache.addEventListener("change", async () => { if (forceCache.checked && !(await appConfirm(t("vhCacheForceConfirm"), { danger: true }))) forceCache.checked = false; syncForceCache(); }); syncForceCache();
|
||||
note(unsafeCacheFields, "vhCacheForceHelp");
|
||||
const cacheRulesFields = el("div", undefined, "vh-wide vh-cache-rules"); cacheOptions.append(cacheRulesFields);
|
||||
cacheRulesFields.append(el("h4", t("vhCacheRulesTitle")), el("p", t("vhCacheRulesHelp"), "fine"));
|
||||
vhostCacheRulesEditor = window.rustProxyCacheRules.create({ scope: "vhost", vhostId: editing || "", rules: cache.rules || [], ignoreGlobal: cache.ignore_global_rules === true });
|
||||
cacheRulesFields.append(vhostCacheRulesEditor.node);
|
||||
if (editing) cacheOptions.append(button("vhPurgeCache", () => purge(editing)));
|
||||
const syncCacheVisibility = () => {
|
||||
const enabled = envelope?.config.cache?.enabled === true && cacheToggle.value !== "off";
|
||||
|
||||
Vendored
+2
@@ -1,4 +1,6 @@
|
||||
include!("model.rs");
|
||||
include!("rules.rs");
|
||||
include!("vcl.rs");
|
||||
include!("stats.rs");
|
||||
include!("lifecycle.rs");
|
||||
include!("cold.rs");
|
||||
|
||||
Vendored
+16
@@ -1,5 +1,6 @@
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_rules(&self.rules, true)?;
|
||||
ensure!(
|
||||
self.max_bytes >= 65_536,
|
||||
"cache.max_bytes must be at least 64 KiB"
|
||||
@@ -441,10 +442,18 @@ pub struct Overrides {
|
||||
pub expose_resident_age: Option<bool>,
|
||||
pub expose_only_hits: Option<bool>,
|
||||
pub unsafe_force: UnsafeForce,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub rules: Vec<Rule>,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ignore_global_rules: bool,
|
||||
}
|
||||
impl Overrides {
|
||||
pub fn resolve(&self, global: &Settings) -> Result<Settings> {
|
||||
self.resolve_for(global, "")
|
||||
}
|
||||
pub fn resolve_for(&self, global: &Settings, vhost_id: &str) -> Result<Settings> {
|
||||
self.unsafe_force.validate()?;
|
||||
validate_rules(&self.rules, false)?;
|
||||
let mut result = global.clone();
|
||||
result.enabled = global.enabled && self.enabled.unwrap_or(true);
|
||||
if let Some(value) = self.default_ttl_seconds {
|
||||
@@ -488,6 +497,13 @@ impl Overrides {
|
||||
result.expose_only_hits = value;
|
||||
}
|
||||
result.validate()?;
|
||||
let compiled = CompiledRules::compile(
|
||||
vhost_id,
|
||||
&self.rules,
|
||||
&global.rules,
|
||||
self.ignore_global_rules,
|
||||
)?;
|
||||
result.compiled_rules = (!compiled.is_empty()).then(|| Arc::new(compiled));
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+6
@@ -189,6 +189,10 @@ pub struct Settings {
|
||||
pub expose_resident_age: bool,
|
||||
pub expose_only_hits: bool,
|
||||
pub via_header: Option<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub rules: Vec<Rule>,
|
||||
#[serde(skip)]
|
||||
pub compiled_rules: Option<Arc<CompiledRules>>,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
@@ -253,6 +257,8 @@ impl Default for Settings {
|
||||
expose_resident_age: false,
|
||||
expose_only_hits: false,
|
||||
via_header: Some("RustProxy".into()),
|
||||
rules: Vec::new(),
|
||||
compiled_rules: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+43
-8
@@ -1,4 +1,10 @@
|
||||
impl Plan {
|
||||
pub fn ttl(&self) -> u64 {
|
||||
self.ttl
|
||||
}
|
||||
pub fn grace(&self) -> u64 {
|
||||
self.stale_while_revalidate
|
||||
}
|
||||
pub fn remaining_ttl(&self) -> u64 {
|
||||
self.ttl.saturating_sub(self.initial_age.as_secs())
|
||||
}
|
||||
@@ -54,6 +60,26 @@ pub fn plan(
|
||||
settings: &Settings,
|
||||
response_delay: Duration,
|
||||
) -> Option<Plan> {
|
||||
plan_with(
|
||||
status,
|
||||
headers,
|
||||
settings,
|
||||
response_delay,
|
||||
&ResponseOverrides::NONE,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn plan_with(
|
||||
status: StatusCode,
|
||||
headers: &HeaderMap,
|
||||
settings: &Settings,
|
||||
response_delay: Duration,
|
||||
overrides: &ResponseOverrides,
|
||||
) -> Option<Plan> {
|
||||
if overrides.no_store {
|
||||
return None;
|
||||
}
|
||||
let forced = overrides.ignore_cache_control;
|
||||
if ["age", "date", "expires", "content-length"]
|
||||
.iter()
|
||||
.any(|name| headers.get_all(*name).iter().count() > 1)
|
||||
@@ -86,22 +112,24 @@ pub fn plan(
|
||||
}
|
||||
let vary = vary_names(headers)?;
|
||||
let control = directives(headers)?;
|
||||
if ["no-store", "private", "must-understand"]
|
||||
.iter()
|
||||
.any(|name| control.contains_key(*name))
|
||||
if !forced
|
||||
&& ["no-store", "private", "must-understand"]
|
||||
.iter()
|
||||
.any(|name| control.contains_key(*name))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if settings.varnish_compatible && surrogate_no_store(headers) {
|
||||
if !forced && settings.varnish_compatible && surrogate_no_store(headers) {
|
||||
return None;
|
||||
}
|
||||
let override_public_no_cache = settings.varnish_compatible
|
||||
&& control.contains_key("no-cache")
|
||||
&& control.contains_key("public")
|
||||
&& settings.default_ttl_seconds > 0;
|
||||
let requires_revalidation = control.contains_key("no-cache") && !override_public_no_cache;
|
||||
let must_revalidate = control.contains_key("must-revalidate");
|
||||
let proxy_revalidate = control.contains_key("proxy-revalidate");
|
||||
let requires_revalidation =
|
||||
!forced && control.contains_key("no-cache") && !override_public_no_cache;
|
||||
let must_revalidate = !forced && control.contains_key("must-revalidate");
|
||||
let proxy_revalidate = !forced && control.contains_key("proxy-revalidate");
|
||||
let parse_window = |name: &str| -> Option<u64> {
|
||||
match control.get(name) {
|
||||
None => Some(0),
|
||||
@@ -122,7 +150,11 @@ pub fn plan(
|
||||
Some(v) => httpdate::parse_http_date(v.to_str().ok()?).ok()?,
|
||||
None => now,
|
||||
};
|
||||
let declared_ttl = if override_public_no_cache {
|
||||
let declared_ttl = if let Some(ttl) = overrides.ttl {
|
||||
Some(ttl)
|
||||
} else if forced {
|
||||
(settings.default_ttl_seconds > 0).then_some(settings.default_ttl_seconds)
|
||||
} else if override_public_no_cache {
|
||||
Some(settings.default_ttl_seconds)
|
||||
} else if let Some(value) = control.get("s-maxage").or_else(|| control.get("max-age")) {
|
||||
Some(value.as_ref()?.parse::<u64>().ok()?)
|
||||
@@ -163,6 +195,9 @@ pub fn plan(
|
||||
{
|
||||
stale_while_revalidate = settings.varnish_grace_seconds;
|
||||
}
|
||||
if let Some(grace) = overrides.grace {
|
||||
stale_while_revalidate = grace;
|
||||
}
|
||||
if !requires_revalidation
|
||||
&& initial_age.as_secs()
|
||||
>= retention_deadline(
|
||||
|
||||
Vendored
+1192
File diff suppressed because it is too large.
Load diff
Vendored
+324
@@ -0,0 +1,324 @@
|
||||
mod cache_rules_tests {
|
||||
use super::*;
|
||||
|
||||
fn rule(json: serde_json::Value) -> Rule {
|
||||
serde_json::from_value(json).unwrap()
|
||||
}
|
||||
|
||||
fn request(path: &str, query: Option<&str>, headers: &[(&str, &str)]) -> RuleRequest {
|
||||
let mut map = HeaderMap::new();
|
||||
for (name, value) in headers {
|
||||
map.append(
|
||||
http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
|
||||
HeaderValue::from_str(value).unwrap(),
|
||||
);
|
||||
}
|
||||
RuleRequest {
|
||||
host: "shop.example.test".into(),
|
||||
path: path.into(),
|
||||
query: query.map(str::to_owned),
|
||||
method: Method::GET,
|
||||
headers: map,
|
||||
client_ip: Some("10.1.2.3".parse().unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_rules_pass_strip_cookies_query_and_hash() {
|
||||
let global = vec![
|
||||
rule(
|
||||
serde_json::json!({"id": "admin", "conditions": [{"field": "path", "operator": "prefix", "values": ["/wp-admin"]}], "actions": [{"type": "pass"}]}),
|
||||
),
|
||||
rule(
|
||||
serde_json::json!({"id": "utm", "actions": [{"type": "strip_query", "params": ["utm_*", "fbclid"]}]}),
|
||||
),
|
||||
rule(
|
||||
serde_json::json!({"id": "cookies", "conditions": [{"field": "extension", "operator": "equals", "values": ["css", "js"]}], "actions": [{"type": "strip_cookies", "keep": ["lang"]}, {"type": "hash_cookie", "name": "lang"}]}),
|
||||
),
|
||||
];
|
||||
validate_rules(&global, true).unwrap();
|
||||
let rules = CompiledRules::compile("shop", &[], &global, false).unwrap();
|
||||
let admin = rules.evaluate_request(&request("/wp-admin/index.php", None, &[]), false);
|
||||
assert_eq!(admin.pass.as_deref(), Some("admin"));
|
||||
let asset = request(
|
||||
"/app.CSS",
|
||||
Some("v=1&utm_source=x&fbclid=y"),
|
||||
&[("cookie", "sid=1; lang=pl")],
|
||||
);
|
||||
let outcome = rules.evaluate_request(&asset, false);
|
||||
assert!(outcome.pass.is_none());
|
||||
assert_eq!(
|
||||
outcome.rewrite_query(asset.query.as_deref()),
|
||||
Some(Some("v=1".into()))
|
||||
);
|
||||
let mut headers = asset.headers.clone();
|
||||
outcome.rewrite_cookies(&mut headers);
|
||||
assert_eq!(headers.get("cookie").unwrap(), "lang=pl");
|
||||
assert_eq!(outcome.hash, vec!["c:lang=pl".to_owned()]);
|
||||
let only_utm = request("/page", Some("utm_medium=a"), &[]);
|
||||
assert_eq!(
|
||||
rules
|
||||
.evaluate_request(&only_utm, false)
|
||||
.rewrite_query(only_utm.query.as_deref()),
|
||||
Some(None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vhost_rules_win_over_global_and_report_the_override() {
|
||||
let global = vec![rule(
|
||||
serde_json::json!({"id": "ttl", "stage": "response", "actions": [{"type": "ttl", "seconds": 60}]}),
|
||||
)];
|
||||
let vhost = vec![rule(
|
||||
serde_json::json!({"id": "ttl", "stage": "response", "conditions": [{"field": "status", "operator": "equals", "values": ["2xx"]}], "actions": [{"type": "ttl", "seconds": 3600}, {"type": "grace", "seconds": 30}]}),
|
||||
)];
|
||||
let rules = CompiledRules::compile("shop", &vhost, &global, false).unwrap();
|
||||
let outcome = rules.evaluate_response(
|
||||
&request("/", None, &[]),
|
||||
StatusCode::OK,
|
||||
&HeaderMap::new(),
|
||||
false,
|
||||
);
|
||||
assert_eq!(outcome.overrides.ttl, Some(3600));
|
||||
assert_eq!(outcome.overrides.grace, Some(30));
|
||||
assert_eq!(outcome.overridden.len(), 1);
|
||||
assert_eq!(outcome.overridden[0].winner, "vhost:ttl");
|
||||
assert_eq!(outcome.overridden[0].ignored, "global:ttl");
|
||||
let ignored = CompiledRules::compile("shop", &[], &global, true).unwrap();
|
||||
assert!(ignored.is_empty());
|
||||
let scoped = vec![rule(
|
||||
serde_json::json!({"id": "other", "vhosts": ["blog"], "actions": [{"type": "pass"}]}),
|
||||
)];
|
||||
assert!(CompiledRules::compile("shop", &[], &scoped, false)
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_rules_are_rejected() {
|
||||
for json in [
|
||||
serde_json::json!({"id": "x", "actions": [{"type": "ttl", "seconds": 5}]}),
|
||||
serde_json::json!({"id": "x", "conditions": [{"field": "status", "operator": "equals", "values": ["200"]}], "actions": [{"type": "pass"}]}),
|
||||
serde_json::json!({"id": "x", "stage": "deliver", "actions": [{"type": "set_header", "name": "set-cookie", "value": "a"}]}),
|
||||
serde_json::json!({"id": "x", "conditions": [{"field": "path", "operator": "regex", "values": ["("]}], "actions": [{"type": "pass"}]}),
|
||||
serde_json::json!({"id": "x", "conditions": [{"field": "header", "operator": "exists"}], "actions": [{"type": "pass"}]}),
|
||||
serde_json::json!({"id": "bad id", "actions": [{"type": "pass"}]}),
|
||||
serde_json::json!({"id": "x", "actions": []}),
|
||||
] {
|
||||
assert!(
|
||||
validate_rules(&[rule(json.clone())], true).is_err(),
|
||||
"{json}"
|
||||
);
|
||||
}
|
||||
let duplicate = vec![
|
||||
rule(serde_json::json!({"id": "a", "actions": [{"type": "pass"}]})),
|
||||
rule(serde_json::json!({"id": "a", "actions": [{"type": "pass"}]})),
|
||||
];
|
||||
assert!(validate_rules(&duplicate, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_overrides_force_ttl_and_ignore_cache_control() {
|
||||
let settings = Settings::default();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("private, no-cache"),
|
||||
);
|
||||
assert!(plan(StatusCode::OK, &headers, &settings, Duration::ZERO).is_none());
|
||||
let forced = ResponseOverrides {
|
||||
ttl: Some(120),
|
||||
grace: Some(10),
|
||||
ignore_cache_control: true,
|
||||
..ResponseOverrides::NONE
|
||||
};
|
||||
let planned =
|
||||
plan_with(StatusCode::OK, &headers, &settings, Duration::ZERO, &forced).unwrap();
|
||||
assert_eq!(planned.ttl(), 120);
|
||||
assert_eq!(planned.grace(), 10);
|
||||
let no_store = ResponseOverrides {
|
||||
no_store: true,
|
||||
..ResponseOverrides::NONE
|
||||
};
|
||||
let mut public = HeaderMap::new();
|
||||
public.insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("public, max-age=60"),
|
||||
);
|
||||
assert!(plan_with(
|
||||
StatusCode::OK,
|
||||
&public,
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
&no_store
|
||||
)
|
||||
.is_none());
|
||||
let ttl_only = ResponseOverrides {
|
||||
ttl: Some(600),
|
||||
..ResponseOverrides::NONE
|
||||
};
|
||||
assert_eq!(
|
||||
plan_with(
|
||||
StatusCode::OK,
|
||||
&public,
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
&ttl_only
|
||||
)
|
||||
.unwrap()
|
||||
.ttl(),
|
||||
600
|
||||
);
|
||||
assert!(plan_with(
|
||||
StatusCode::OK,
|
||||
&headers,
|
||||
&settings,
|
||||
Duration::ZERO,
|
||||
&ttl_only
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deliver_rules_set_and_remove_headers() {
|
||||
let rules = vec![rule(
|
||||
serde_json::json!({"id": "debug", "stage": "deliver", "conditions": [{"field": "response_header", "name": "x-cache", "operator": "equals", "values": ["HIT"]}], "actions": [{"type": "set_header", "name": "X-Served", "value": "cache"}, {"type": "remove_header", "name": "server"}]}),
|
||||
)];
|
||||
let compiled = CompiledRules::compile("", &[], &rules, false).unwrap();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-cache", HeaderValue::from_static("HIT"));
|
||||
headers.insert("server", HeaderValue::from_static("origin"));
|
||||
let outcome =
|
||||
compiled.evaluate_deliver(&request("/", None, &[]), StatusCode::OK, &headers, false);
|
||||
outcome.apply(&mut headers);
|
||||
assert_eq!(headers.get("x-served").unwrap(), "cache");
|
||||
assert!(headers.get("server").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_variant_changes_the_cache_key_only_when_present() {
|
||||
let cache = Cache::new(1);
|
||||
let headers = HeaderMap::new();
|
||||
let plain = cache
|
||||
.ticket_scoped_for_config_variant(
|
||||
cache_control_revision(&cache),
|
||||
1,
|
||||
"",
|
||||
"https",
|
||||
"a.test",
|
||||
"r",
|
||||
"/x",
|
||||
&headers,
|
||||
"",
|
||||
)
|
||||
.unwrap();
|
||||
let again = cache
|
||||
.ticket_scoped_for_config(
|
||||
cache_control_revision(&cache),
|
||||
1,
|
||||
"",
|
||||
"https",
|
||||
"a.test",
|
||||
"r",
|
||||
"/x",
|
||||
&headers,
|
||||
)
|
||||
.unwrap();
|
||||
let variant = cache
|
||||
.ticket_scoped_for_config_variant(
|
||||
cache_control_revision(&cache),
|
||||
1,
|
||||
"",
|
||||
"https",
|
||||
"a.test",
|
||||
"r",
|
||||
"/x",
|
||||
&headers,
|
||||
"c:lang=pl",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plain.key, again.key);
|
||||
assert_ne!(plain.key, variant.key);
|
||||
}
|
||||
|
||||
fn cache_control_revision(cache: &Cache) -> u64 {
|
||||
cache.store.lock().unwrap().control_revision
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vcl_subset_is_imported_with_warnings() {
|
||||
let source = r#"
|
||||
vcl 4.1;
|
||||
backend default { .host = "127.0.0.1"; }
|
||||
sub vcl_recv {
|
||||
if (req.url ~ "^/wp-(admin|login)" || req.http.Cookie ~ "wordpress_logged_in") {
|
||||
return (pass);
|
||||
}
|
||||
if (req.method != "GET" && req.method != "HEAD") { return (pass); }
|
||||
set req.url = regsuball(req.url, "(\?|&)(utm_[a-z]+|gclid|fbclid)=[^&]+", "\1");
|
||||
if (req.url ~ "\.(css|js|png)$") {
|
||||
unset req.http.Cookie;
|
||||
}
|
||||
if (client.ip ~ purgers) { return (purge); }
|
||||
}
|
||||
sub vcl_hash { hash_data(req.http.X-Lang); }
|
||||
sub vcl_backend_response {
|
||||
if (beresp.status >= 500) {
|
||||
set beresp.ttl = 0s;
|
||||
set beresp.uncacheable = true;
|
||||
} else {
|
||||
set beresp.ttl = 1h;
|
||||
set beresp.grace = 6h;
|
||||
}
|
||||
unset beresp.http.Set-Cookie;
|
||||
}
|
||||
sub vcl_deliver {
|
||||
set resp.http.X-Cache-Engine = "RustProxy";
|
||||
unset resp.http.X-Powered-By;
|
||||
}
|
||||
"#;
|
||||
let imported = import_vcl(source).unwrap();
|
||||
validate_rules(&imported.rules, true).unwrap();
|
||||
let actions: Vec<_> = imported
|
||||
.rules
|
||||
.iter()
|
||||
.flat_map(|rule| rule.actions.clone())
|
||||
.collect();
|
||||
assert!(actions.contains(&RuleAction::Pass));
|
||||
assert!(actions.contains(&RuleAction::StripQuery {
|
||||
params: vec!["utm_*".into(), "gclid".into(), "fbclid".into()],
|
||||
keep_only: false
|
||||
}));
|
||||
assert!(actions.contains(&RuleAction::StripCookies { keep: vec![] }));
|
||||
assert!(actions.contains(&RuleAction::HashHeader {
|
||||
name: "X-Lang".into()
|
||||
}));
|
||||
assert!(actions.contains(&RuleAction::Ttl { seconds: 3600 }));
|
||||
assert!(actions.contains(&RuleAction::Grace { seconds: 21600 }));
|
||||
assert!(actions.contains(&RuleAction::NoStore));
|
||||
assert!(actions.contains(&RuleAction::StripSetCookie));
|
||||
assert!(actions.contains(&RuleAction::SetHeader {
|
||||
name: "X-Cache-Engine".into(),
|
||||
value: "RustProxy".into()
|
||||
}));
|
||||
assert!(actions.contains(&RuleAction::RemoveHeader {
|
||||
name: "X-Powered-By".into()
|
||||
}));
|
||||
let else_rule = imported
|
||||
.rules
|
||||
.iter()
|
||||
.find(|rule| rule.actions.contains(&RuleAction::Ttl { seconds: 3600 }))
|
||||
.unwrap();
|
||||
assert!(else_rule.conditions[0].negate);
|
||||
assert!(imported
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|warning| warning.contains("client.ip")));
|
||||
assert!(imported
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|warning| warning.contains("backend")));
|
||||
assert!(import_vcl("sub vcl_recv { if (").is_err());
|
||||
assert!(import_vcl("vcl 4.1;").is_err());
|
||||
}
|
||||
}
|
||||
Vendored
+3
@@ -21,3 +21,6 @@ include!("lookup/hot_hit_034_tests.rs");
|
||||
|
||||
#[cfg(test)]
|
||||
include!("varnish_compatible_tests.rs");
|
||||
|
||||
#[cfg(test)]
|
||||
include!("rules_tests.rs");
|
||||
Vendored
+49
-1
@@ -49,8 +49,51 @@ impl Cache {
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn ticket_scoped_for_config_variant(
|
||||
&self,
|
||||
control_revision: u64,
|
||||
revision: u64,
|
||||
scope: &str,
|
||||
scheme: &str,
|
||||
authority: &str,
|
||||
route: &str,
|
||||
target: &str,
|
||||
headers: &HeaderMap,
|
||||
variant: &str,
|
||||
) -> Option<Ticket> {
|
||||
self.ticket_variant_impl(
|
||||
Some(control_revision),
|
||||
revision,
|
||||
scope,
|
||||
scheme,
|
||||
authority,
|
||||
route,
|
||||
target,
|
||||
headers,
|
||||
variant,
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn ticket_scoped_impl(
|
||||
&self,
|
||||
expected_control_revision: Option<u64>,
|
||||
revision: u64,
|
||||
scope: &str,
|
||||
scheme: &str,
|
||||
authority: &str,
|
||||
route: &str,
|
||||
target: &str,
|
||||
headers: &HeaderMap,
|
||||
) -> Option<Ticket> {
|
||||
self.ticket_variant_impl(
|
||||
expected_control_revision, revision, scope, scheme, authority, route, target, headers, "",
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn ticket_variant_impl(
|
||||
&self,
|
||||
expected_control_revision: Option<u64>,
|
||||
revision: u64,
|
||||
@@ -60,8 +103,9 @@ impl Cache {
|
||||
_route: &str,
|
||||
target: &str,
|
||||
headers: &HeaderMap,
|
||||
variant: &str,
|
||||
) -> Option<Ticket> {
|
||||
if target.len() > 8192 || scope.len() > 64 {
|
||||
if target.len() > 8192 || scope.len() > 64 || variant.len() > 8192 {
|
||||
return None;
|
||||
}
|
||||
let domain = crate::config::request_host(authority)
|
||||
@@ -83,6 +127,10 @@ impl Cache {
|
||||
] {
|
||||
field(value);
|
||||
}
|
||||
if !variant.is_empty() {
|
||||
field(b"rule-variant");
|
||||
field(variant.as_bytes());
|
||||
}
|
||||
let key: Key = digest.finalize().into();
|
||||
let store = self.store.lock().unwrap_or_else(|e| e.into_inner());
|
||||
(store.revision == revision
|
||||
|
||||
Vendored
+825
@@ -0,0 +1,825 @@
|
||||
const MAX_VCL_BYTES: usize = 256 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum VclToken {
|
||||
Ident(String),
|
||||
Str(String),
|
||||
Num(String),
|
||||
Sym(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct VclImport {
|
||||
pub rules: Vec<Rule>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn vcl_tokens(source: &str) -> Result<Vec<(VclToken, usize)>> {
|
||||
let bytes = source.as_bytes();
|
||||
let mut tokens = Vec::new();
|
||||
let mut index = 0;
|
||||
let mut line = 1;
|
||||
while index < bytes.len() {
|
||||
let byte = bytes[index];
|
||||
if byte == b'\n' {
|
||||
line += 1;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if byte.is_ascii_whitespace() {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if byte == b'#' || (byte == b'/' && bytes.get(index + 1) == Some(&b'/')) {
|
||||
while index < bytes.len() && bytes[index] != b'\n' {
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if byte == b'/' && bytes.get(index + 1) == Some(&b'*') {
|
||||
index += 2;
|
||||
while index + 1 < bytes.len() && !(bytes[index] == b'*' && bytes[index + 1] == b'/') {
|
||||
if bytes[index] == b'\n' {
|
||||
line += 1;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if byte == b'{' && bytes.get(index + 1) == Some(&b'"') {
|
||||
let start = index + 2;
|
||||
let end = source[start..]
|
||||
.find("\"}")
|
||||
.map(|offset| start + offset)
|
||||
.ok_or_else(|| anyhow::anyhow!("line {line}: unterminated long string"))?;
|
||||
line += source[start..end].matches('\n').count();
|
||||
tokens.push((VclToken::Str(source[start..end].to_owned()), line));
|
||||
index = end + 2;
|
||||
continue;
|
||||
}
|
||||
if byte == b'"' {
|
||||
let start = index + 1;
|
||||
let end = source[start..]
|
||||
.find('"')
|
||||
.map(|offset| start + offset)
|
||||
.ok_or_else(|| anyhow::anyhow!("line {line}: unterminated string"))?;
|
||||
tokens.push((VclToken::Str(source[start..end].to_owned()), line));
|
||||
index = end + 1;
|
||||
continue;
|
||||
}
|
||||
if byte.is_ascii_alphabetic() || byte == b'_' {
|
||||
let start = index;
|
||||
while index < bytes.len()
|
||||
&& (bytes[index].is_ascii_alphanumeric()
|
||||
|| matches!(bytes[index], b'_' | b'.' | b'-' | b':'))
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
tokens.push((VclToken::Ident(source[start..index].to_owned()), line));
|
||||
continue;
|
||||
}
|
||||
if byte.is_ascii_digit() {
|
||||
let start = index;
|
||||
while index < bytes.len()
|
||||
&& (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'.')
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
tokens.push((VclToken::Num(source[start..index].to_owned()), line));
|
||||
continue;
|
||||
}
|
||||
let two = source.get(index..index + 2).unwrap_or("");
|
||||
let symbol = match two {
|
||||
"==" => Some("=="),
|
||||
"!=" => Some("!="),
|
||||
"!~" => Some("!~"),
|
||||
"&&" => Some("&&"),
|
||||
"||" => Some("||"),
|
||||
">=" => Some(">="),
|
||||
"<=" => Some("<="),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(symbol) = symbol {
|
||||
tokens.push((VclToken::Sym(symbol), line));
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
let symbol = match byte {
|
||||
b'{' => "{",
|
||||
b'}' => "}",
|
||||
b'(' => "(",
|
||||
b')' => ")",
|
||||
b';' => ";",
|
||||
b'=' => "=",
|
||||
b'~' => "~",
|
||||
b'!' => "!",
|
||||
b',' => ",",
|
||||
b'>' => ">",
|
||||
b'<' => "<",
|
||||
b'+' => "+",
|
||||
b'.' => ".",
|
||||
b'-' => "-",
|
||||
b'*' => "*",
|
||||
b'/' => "/",
|
||||
b'%' => "%",
|
||||
_ => anyhow::bail!("line {line}: unexpected character {:?}", byte as char),
|
||||
};
|
||||
tokens.push((VclToken::Sym(symbol), line));
|
||||
index += 1;
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum VclStatement {
|
||||
If(Vec<(Option<VclExpr>, Vec<VclStatement>)>, usize),
|
||||
Simple(Vec<VclToken>, usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum VclExpr {
|
||||
And(Vec<VclExpr>),
|
||||
Or(Vec<VclExpr>),
|
||||
Not(Box<VclExpr>),
|
||||
Atom(Vec<VclToken>),
|
||||
}
|
||||
|
||||
struct VclParser {
|
||||
tokens: Vec<(VclToken, usize)>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl VclParser {
|
||||
fn peek(&self) -> Option<&VclToken> {
|
||||
self.tokens.get(self.position).map(|(token, _)| token)
|
||||
}
|
||||
fn line(&self) -> usize {
|
||||
self.tokens
|
||||
.get(self.position)
|
||||
.or(self.tokens.last())
|
||||
.map(|(_, line)| *line)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
fn next(&mut self) -> Option<VclToken> {
|
||||
let token = self
|
||||
.tokens
|
||||
.get(self.position)
|
||||
.map(|(token, _)| token.clone());
|
||||
self.position += 1;
|
||||
token
|
||||
}
|
||||
fn is_sym(&self, symbol: &str) -> bool {
|
||||
matches!(self.peek(), Some(VclToken::Sym(value)) if *value == symbol)
|
||||
}
|
||||
fn is_ident(&self, name: &str) -> bool {
|
||||
matches!(self.peek(), Some(VclToken::Ident(value)) if value == name)
|
||||
}
|
||||
fn expect(&mut self, symbol: &str) -> Result<()> {
|
||||
let line = self.line();
|
||||
match self.next() {
|
||||
Some(VclToken::Sym(value)) if value == symbol => Ok(()),
|
||||
other => anyhow::bail!("line {line}: expected {symbol:?}, found {other:?}"),
|
||||
}
|
||||
}
|
||||
fn block(&mut self) -> Result<Vec<VclStatement>> {
|
||||
self.expect("{")?;
|
||||
let mut statements = Vec::new();
|
||||
while !self.is_sym("}") {
|
||||
ensure!(
|
||||
self.peek().is_some(),
|
||||
"unexpected end of VCL inside a block"
|
||||
);
|
||||
statements.push(self.statement()?);
|
||||
}
|
||||
self.expect("}")?;
|
||||
Ok(statements)
|
||||
}
|
||||
fn statement(&mut self) -> Result<VclStatement> {
|
||||
let line = self.line();
|
||||
if self.is_ident("if") {
|
||||
self.next();
|
||||
let mut branches = vec![(Some(self.condition()?), self.block()?)];
|
||||
loop {
|
||||
if self.is_ident("elsif") || self.is_ident("elseif") {
|
||||
self.next();
|
||||
branches.push((Some(self.condition()?), self.block()?));
|
||||
} else if self.is_ident("else") {
|
||||
self.next();
|
||||
if self.is_ident("if") {
|
||||
self.next();
|
||||
branches.push((Some(self.condition()?), self.block()?));
|
||||
} else {
|
||||
branches.push((None, self.block()?));
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Ok(VclStatement::If(branches, line));
|
||||
}
|
||||
let mut tokens = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
loop {
|
||||
match self.next() {
|
||||
None => anyhow::bail!("line {line}: missing ';'"),
|
||||
Some(VclToken::Sym(";")) if depth == 0 => break,
|
||||
Some(token) => {
|
||||
if token == VclToken::Sym("(") {
|
||||
depth += 1;
|
||||
} else if token == VclToken::Sym(")") {
|
||||
depth = depth.saturating_sub(1);
|
||||
}
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(VclStatement::Simple(tokens, line))
|
||||
}
|
||||
fn condition(&mut self) -> Result<VclExpr> {
|
||||
self.expect("(")?;
|
||||
let expr = self.or_expr()?;
|
||||
self.expect(")")?;
|
||||
Ok(expr)
|
||||
}
|
||||
fn or_expr(&mut self) -> Result<VclExpr> {
|
||||
let mut items = vec![self.and_expr()?];
|
||||
while self.is_sym("||") {
|
||||
self.next();
|
||||
items.push(self.and_expr()?);
|
||||
}
|
||||
Ok(if items.len() == 1 {
|
||||
items.remove(0)
|
||||
} else {
|
||||
VclExpr::Or(items)
|
||||
})
|
||||
}
|
||||
fn and_expr(&mut self) -> Result<VclExpr> {
|
||||
let mut items = vec![self.unary()?];
|
||||
while self.is_sym("&&") {
|
||||
self.next();
|
||||
items.push(self.unary()?);
|
||||
}
|
||||
Ok(if items.len() == 1 {
|
||||
items.remove(0)
|
||||
} else {
|
||||
VclExpr::And(items)
|
||||
})
|
||||
}
|
||||
fn unary(&mut self) -> Result<VclExpr> {
|
||||
if self.is_sym("!") {
|
||||
self.next();
|
||||
return Ok(VclExpr::Not(Box::new(self.unary()?)));
|
||||
}
|
||||
if self.is_sym("(") {
|
||||
self.next();
|
||||
let expr = self.or_expr()?;
|
||||
self.expect(")")?;
|
||||
return Ok(expr);
|
||||
}
|
||||
let mut atom = Vec::new();
|
||||
while let Some(token) = self.peek() {
|
||||
if matches!(
|
||||
token,
|
||||
VclToken::Sym("&&") | VclToken::Sym("||") | VclToken::Sym(")")
|
||||
) {
|
||||
break;
|
||||
}
|
||||
atom.push(self.next().unwrap_or(VclToken::Sym(";")));
|
||||
}
|
||||
ensure!(!atom.is_empty(), "line {}: empty condition", self.line());
|
||||
Ok(VclExpr::Atom(atom))
|
||||
}
|
||||
}
|
||||
|
||||
fn vcl_duration(value: &str) -> Option<u64> {
|
||||
let split = value
|
||||
.find(|c: char| c.is_ascii_alphabetic())
|
||||
.unwrap_or(value.len());
|
||||
let (number, unit) = value.split_at(split);
|
||||
let number = number
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|n| n.is_finite() && *n >= 0.0)?;
|
||||
let factor = match unit {
|
||||
"ms" => 0.001,
|
||||
"s" | "" => 1.0,
|
||||
"m" => 60.0,
|
||||
"h" => 3600.0,
|
||||
"d" => 86_400.0,
|
||||
"w" => 604_800.0,
|
||||
"y" => 31_536_000.0,
|
||||
_ => return None,
|
||||
};
|
||||
Some((number * factor).round() as u64)
|
||||
}
|
||||
|
||||
fn header_of<'a>(ident: &'a str, prefixes: &[&str]) -> Option<&'a str> {
|
||||
prefixes
|
||||
.iter()
|
||||
.find_map(|prefix| ident.strip_prefix(prefix))
|
||||
}
|
||||
|
||||
struct VclAtomResult {
|
||||
condition: RuleCondition,
|
||||
}
|
||||
|
||||
fn vcl_atom(
|
||||
tokens: &[VclToken],
|
||||
stage: RuleStage,
|
||||
negate: bool,
|
||||
) -> std::result::Result<VclAtomResult, String> {
|
||||
let ident = match tokens.first() {
|
||||
Some(VclToken::Ident(value)) => value.as_str(),
|
||||
other => return Err(format!("unsupported condition {other:?}")),
|
||||
};
|
||||
let lower = ident.to_ascii_lowercase();
|
||||
let request_prefixes: &[&str] = &["req.http.", "bereq.http."];
|
||||
let response_prefixes: &[&str] = &["beresp.http.", "resp.http.", "obj.http."];
|
||||
let (field, name) = if matches!(lower.as_str(), "req.url" | "bereq.url") {
|
||||
(ConditionField::Url, None)
|
||||
} else if matches!(
|
||||
lower.as_str(),
|
||||
"req.method" | "req.request" | "bereq.method"
|
||||
) {
|
||||
(ConditionField::Method, None)
|
||||
} else if matches!(
|
||||
lower.as_str(),
|
||||
"beresp.status" | "resp.status" | "obj.status"
|
||||
) {
|
||||
(ConditionField::Status, None)
|
||||
} else if matches!(lower.as_str(), "client.ip") {
|
||||
return Err(
|
||||
"client.ip with an ACL is not imported; add a client IP condition with the CIDR list"
|
||||
.into(),
|
||||
);
|
||||
} else if let Some(header) = header_of(ident, request_prefixes) {
|
||||
if header.eq_ignore_ascii_case("host") {
|
||||
(ConditionField::Host, None)
|
||||
} else {
|
||||
(ConditionField::Header, Some(header.to_owned()))
|
||||
}
|
||||
} else if let Some(header) = header_of(ident, response_prefixes) {
|
||||
if stage == RuleStage::Request {
|
||||
return Err(format!("{ident} is not available in vcl_recv"));
|
||||
}
|
||||
if header.eq_ignore_ascii_case("content-type") {
|
||||
(ConditionField::ContentType, None)
|
||||
} else {
|
||||
(ConditionField::ResponseHeader, Some(header.to_owned()))
|
||||
}
|
||||
} else {
|
||||
return Err(format!("unsupported variable {ident}"));
|
||||
};
|
||||
let make = |operator, values: Vec<String>, negated: bool| VclAtomResult {
|
||||
condition: RuleCondition {
|
||||
field,
|
||||
name: name.clone(),
|
||||
operator,
|
||||
values,
|
||||
negate: negated,
|
||||
},
|
||||
};
|
||||
if tokens.len() == 1 {
|
||||
return if name.is_some() {
|
||||
Ok(make(ConditionOperator::Exists, Vec::new(), negate))
|
||||
} else {
|
||||
Err(format!("bare {ident} test is not supported"))
|
||||
};
|
||||
}
|
||||
let value = match tokens.get(2) {
|
||||
Some(VclToken::Str(value)) | Some(VclToken::Num(value)) | Some(VclToken::Ident(value)) => {
|
||||
value.clone()
|
||||
}
|
||||
_ => return Err(format!("unsupported comparison on {ident}")),
|
||||
};
|
||||
if tokens.len() > 3 {
|
||||
return Err(format!("expression on {ident} is too complex"));
|
||||
}
|
||||
let operator = match tokens.get(1) {
|
||||
Some(VclToken::Sym(symbol)) => *symbol,
|
||||
_ => return Err(format!("unsupported comparison on {ident}")),
|
||||
};
|
||||
if field == ConditionField::Status {
|
||||
let code = value
|
||||
.parse::<u16>()
|
||||
.map_err(|_| format!("invalid status {value}"))?;
|
||||
let range = match operator {
|
||||
"==" => format!("{code}"),
|
||||
"!=" => {
|
||||
return Ok(make(
|
||||
ConditionOperator::Equals,
|
||||
vec![format!("{code}")],
|
||||
!negate,
|
||||
))
|
||||
}
|
||||
">=" => format!("{code}-599"),
|
||||
">" => format!("{}-599", code + 1),
|
||||
"<=" => format!("100-{code}"),
|
||||
"<" => format!("100-{}", code.saturating_sub(1)),
|
||||
_ => return Err(format!("unsupported status comparison {operator}")),
|
||||
};
|
||||
return Ok(make(ConditionOperator::Equals, vec![range], negate));
|
||||
}
|
||||
match operator {
|
||||
"~" => Ok(make(ConditionOperator::Regex, vec![value], negate)),
|
||||
"!~" => Ok(make(ConditionOperator::Regex, vec![value], !negate)),
|
||||
"==" => Ok(make(ConditionOperator::Equals, vec![value], negate)),
|
||||
"!=" => Ok(make(ConditionOperator::Equals, vec![value], !negate)),
|
||||
_ => Err(format!("unsupported operator {operator} on {ident}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn vcl_conditions(
|
||||
expr: &VclExpr,
|
||||
stage: RuleStage,
|
||||
) -> std::result::Result<(RuleMatch, Vec<RuleCondition>), String> {
|
||||
let single = |expr: &VclExpr| -> std::result::Result<RuleCondition, String> {
|
||||
match expr {
|
||||
VclExpr::Atom(tokens) => vcl_atom(tokens, stage, false).map(|atom| atom.condition),
|
||||
VclExpr::Not(inner) => match inner.as_ref() {
|
||||
VclExpr::Atom(tokens) => vcl_atom(tokens, stage, true).map(|atom| atom.condition),
|
||||
_ => Err("negated groups are not supported".into()),
|
||||
},
|
||||
_ => Err("nested && / || groups are not supported".into()),
|
||||
}
|
||||
};
|
||||
match expr {
|
||||
VclExpr::And(items) => Ok((
|
||||
RuleMatch::All,
|
||||
items
|
||||
.iter()
|
||||
.map(single)
|
||||
.collect::<std::result::Result<_, _>>()?,
|
||||
)),
|
||||
VclExpr::Or(items) => Ok((
|
||||
RuleMatch::Any,
|
||||
items
|
||||
.iter()
|
||||
.map(single)
|
||||
.collect::<std::result::Result<_, _>>()?,
|
||||
)),
|
||||
other => Ok((RuleMatch::All, vec![single(other)?])),
|
||||
}
|
||||
}
|
||||
|
||||
fn query_params_from_regex(pattern: &str) -> Vec<String> {
|
||||
static CLASS: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
|
||||
regex::Regex::new(r"\[[^\]]*\][+*]?|\.\*|\.\+").expect("static regex")
|
||||
});
|
||||
let simplified = CLASS.replace_all(pattern, "*");
|
||||
let mut params = Vec::new();
|
||||
for token in
|
||||
simplified.split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '*')))
|
||||
{
|
||||
if token.len() > 64
|
||||
|| !token
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let token = token.to_owned();
|
||||
if !params.contains(&token) {
|
||||
params.push(token);
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
fn vcl_actions(
|
||||
tokens: &[VclToken],
|
||||
stage: RuleStage,
|
||||
) -> std::result::Result<Vec<RuleAction>, String> {
|
||||
let words: Vec<String> = tokens
|
||||
.iter()
|
||||
.map(|token| match token {
|
||||
VclToken::Ident(value) | VclToken::Str(value) | VclToken::Num(value) => value.clone(),
|
||||
VclToken::Sym(symbol) => (*symbol).to_owned(),
|
||||
})
|
||||
.collect();
|
||||
let first = words
|
||||
.first()
|
||||
.map(|word| word.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let joined = words.join(" ").to_ascii_lowercase();
|
||||
match (stage, first.as_str()) {
|
||||
(_, "return") => {
|
||||
let target = words
|
||||
.get(2)
|
||||
.map(|word| word.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
match (stage, target.as_str()) {
|
||||
(RuleStage::Request, "pass" | "pipe") => Ok(vec![RuleAction::Pass]),
|
||||
(RuleStage::Request, "hash" | "lookup") => Ok(Vec::new()),
|
||||
(RuleStage::Response, "pass" | "hit_for_pass" | "uncacheable") => {
|
||||
Ok(vec![RuleAction::NoStore])
|
||||
}
|
||||
(RuleStage::Response, "deliver") | (RuleStage::Deliver, "deliver") => {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
_ => Err(format!("return ({target}) is not supported here")),
|
||||
}
|
||||
}
|
||||
(RuleStage::Request, "unset")
|
||||
if words
|
||||
.get(1)
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("req.http.cookie")) =>
|
||||
{
|
||||
Ok(vec![RuleAction::StripCookies { keep: Vec::new() }])
|
||||
}
|
||||
(RuleStage::Request, "set")
|
||||
if words
|
||||
.get(1)
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("req.url"))
|
||||
&& joined.contains("regsub") =>
|
||||
{
|
||||
let pattern = words
|
||||
.iter()
|
||||
.find(|word| word.contains('?') || word.contains('&') || word.contains("utm"))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let params = query_params_from_regex(&pattern);
|
||||
if params.is_empty() {
|
||||
Err("req.url rewrite not recognised as query parameter removal".into())
|
||||
} else {
|
||||
Ok(vec![RuleAction::StripQuery {
|
||||
params,
|
||||
keep_only: false,
|
||||
}])
|
||||
}
|
||||
}
|
||||
(RuleStage::Request, "hash_data") => match words.get(2) {
|
||||
Some(word)
|
||||
if word.to_ascii_lowercase().starts_with("req.http.")
|
||||
&& !word.eq_ignore_ascii_case("req.http.cookie") =>
|
||||
{
|
||||
Ok(vec![RuleAction::HashHeader {
|
||||
name: word[9..].to_owned(),
|
||||
}])
|
||||
}
|
||||
_ => Err("hash_data is only imported for a single request header".into()),
|
||||
},
|
||||
(RuleStage::Response, "set") => {
|
||||
let target = words
|
||||
.get(1)
|
||||
.map(|word| word.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let value = words.get(3).cloned().unwrap_or_default();
|
||||
match target.as_str() {
|
||||
"beresp.ttl" => vcl_duration(&value)
|
||||
.map(|seconds| vec![RuleAction::Ttl { seconds }])
|
||||
.ok_or_else(|| format!("invalid duration {value}")),
|
||||
"beresp.grace" => vcl_duration(&value)
|
||||
.map(|seconds| vec![RuleAction::Grace { seconds }])
|
||||
.ok_or_else(|| format!("invalid duration {value}")),
|
||||
"beresp.uncacheable" if value.eq_ignore_ascii_case("true") => {
|
||||
Ok(vec![RuleAction::NoStore])
|
||||
}
|
||||
_ => Err(format!("set {target} is not supported")),
|
||||
}
|
||||
}
|
||||
(RuleStage::Response, "unset") => {
|
||||
match words.get(1).map(|word| word.to_ascii_lowercase()) {
|
||||
Some(word) if word == "beresp.http.set-cookie" => {
|
||||
Ok(vec![RuleAction::StripSetCookie])
|
||||
}
|
||||
Some(word)
|
||||
if word == "beresp.http.cache-control"
|
||||
|| word == "beresp.http.expires"
|
||||
|| word == "beresp.http.pragma" =>
|
||||
{
|
||||
Ok(vec![RuleAction::IgnoreCacheControl])
|
||||
}
|
||||
Some(word) => Err(format!("unset {word} is not supported")),
|
||||
None => Err("unset without a target".into()),
|
||||
}
|
||||
}
|
||||
(RuleStage::Deliver, "set") => {
|
||||
let target = words.get(1).cloned().unwrap_or_default();
|
||||
let name = target
|
||||
.strip_prefix("resp.http.")
|
||||
.or_else(|| target.strip_prefix("RESP.HTTP."))
|
||||
.ok_or_else(|| format!("set {target} is not supported"))?;
|
||||
match (tokens.get(3), tokens.len()) {
|
||||
(Some(VclToken::Str(value)), 4) => Ok(vec![RuleAction::SetHeader {
|
||||
name: name.to_owned(),
|
||||
value: value.clone(),
|
||||
}]),
|
||||
_ => Err(format!(
|
||||
"set resp.http.{name} only supports a constant string"
|
||||
)),
|
||||
}
|
||||
}
|
||||
(RuleStage::Deliver, "unset") => {
|
||||
let target = words.get(1).cloned().unwrap_or_default();
|
||||
target
|
||||
.strip_prefix("resp.http.")
|
||||
.map(|name| {
|
||||
vec![RuleAction::RemoveHeader {
|
||||
name: name.to_owned(),
|
||||
}]
|
||||
})
|
||||
.ok_or_else(|| format!("unset {target} is not supported"))
|
||||
}
|
||||
_ => Err(format!("statement '{}' is not supported", words.join(" "))),
|
||||
}
|
||||
}
|
||||
|
||||
fn vcl_stage(name: &str) -> Option<RuleStage> {
|
||||
match name {
|
||||
"vcl_recv" | "vcl_hash" => Some(RuleStage::Request),
|
||||
"vcl_backend_response" | "vcl_fetch" => Some(RuleStage::Response),
|
||||
"vcl_deliver" => Some(RuleStage::Deliver),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct VclBuilder {
|
||||
rules: Vec<Rule>,
|
||||
warnings: Vec<String>,
|
||||
ids: HashSet<String>,
|
||||
}
|
||||
|
||||
impl VclBuilder {
|
||||
fn push(
|
||||
&mut self,
|
||||
stage: RuleStage,
|
||||
match_mode: RuleMatch,
|
||||
conditions: Vec<RuleCondition>,
|
||||
actions: Vec<RuleAction>,
|
||||
line: usize,
|
||||
) {
|
||||
if actions.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.rules.len() >= MAX_CACHE_RULES {
|
||||
self.warnings.push(format!(
|
||||
"line {line}: rule limit reached, the rest of the VCL was skipped"
|
||||
));
|
||||
return;
|
||||
}
|
||||
let base = format!("vcl-{}-{line}", stage.label());
|
||||
let mut id = base.clone();
|
||||
let mut index = 2;
|
||||
while !self.ids.insert(id.clone()) {
|
||||
id = format!("{base}-{index}");
|
||||
index += 1;
|
||||
}
|
||||
let rule = Rule {
|
||||
id: id.clone(),
|
||||
name: format!(
|
||||
"VCL {} line {line}",
|
||||
match stage {
|
||||
RuleStage::Request => "vcl_recv",
|
||||
RuleStage::Response => "vcl_backend_response",
|
||||
RuleStage::Deliver => "vcl_deliver",
|
||||
}
|
||||
),
|
||||
enabled: true,
|
||||
stage,
|
||||
match_mode,
|
||||
conditions,
|
||||
actions,
|
||||
stop: false,
|
||||
vhosts: Vec::new(),
|
||||
};
|
||||
match compile_rule(&rule, RuleOrigin::Global, "") {
|
||||
Ok(_) => self.rules.push(rule),
|
||||
Err(error) => self.warnings.push(format!("line {line}: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn statements(
|
||||
&mut self,
|
||||
stage: RuleStage,
|
||||
statements: &[VclStatement],
|
||||
inherited: Option<(RuleMatch, Vec<RuleCondition>)>,
|
||||
) {
|
||||
let mut pending: Vec<RuleAction> = Vec::new();
|
||||
let mut pending_line = 0;
|
||||
let flush = |builder: &mut Self,
|
||||
pending: &mut Vec<RuleAction>,
|
||||
line: usize,
|
||||
inherited: &Option<(RuleMatch, Vec<RuleCondition>)>| {
|
||||
let (mode, conditions) = inherited.clone().unwrap_or((RuleMatch::All, Vec::new()));
|
||||
builder.push(stage, mode, conditions, std::mem::take(pending), line);
|
||||
};
|
||||
for statement in statements {
|
||||
match statement {
|
||||
VclStatement::Simple(tokens, line) => match vcl_actions(tokens, stage) {
|
||||
Ok(actions) => {
|
||||
if pending.is_empty() {
|
||||
pending_line = *line;
|
||||
}
|
||||
pending.extend(actions);
|
||||
}
|
||||
Err(error) => self.warnings.push(format!("line {line}: {error}")),
|
||||
},
|
||||
VclStatement::If(branches, line) => {
|
||||
flush(self, &mut pending, pending_line, &inherited);
|
||||
if inherited.is_some() {
|
||||
self.warnings.push(format!(
|
||||
"line {line}: nested if is not imported; flatten it into one condition"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let mut previous: Vec<RuleCondition> = Vec::new();
|
||||
let mut previous_ok = true;
|
||||
for (index, (condition, body)) in branches.iter().enumerate() {
|
||||
let parsed = match condition {
|
||||
Some(expr) => vcl_conditions(expr, stage),
|
||||
None => {
|
||||
if previous.len() == 1 && previous_ok {
|
||||
let mut negated = previous[0].clone();
|
||||
negated.negate = !negated.negate;
|
||||
Ok((RuleMatch::All, vec![negated]))
|
||||
} else {
|
||||
Err("else branch after a complex condition is not imported"
|
||||
.into())
|
||||
}
|
||||
}
|
||||
};
|
||||
match parsed {
|
||||
Ok((mode, conditions)) => {
|
||||
if index == 0 || condition.is_none() {
|
||||
previous = conditions.clone();
|
||||
} else {
|
||||
previous_ok = false;
|
||||
}
|
||||
self.statements(stage, body, Some((mode, conditions)));
|
||||
}
|
||||
Err(error) => {
|
||||
previous_ok = false;
|
||||
self.warnings.push(format!("line {line}: {error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(self, &mut pending, pending_line, &inherited);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn import_vcl(source: &str) -> Result<VclImport> {
|
||||
ensure!(
|
||||
source.len() <= MAX_VCL_BYTES,
|
||||
"VCL is limited to {} KiB",
|
||||
MAX_VCL_BYTES / 1024
|
||||
);
|
||||
let tokens = vcl_tokens(source)?;
|
||||
let mut parser = VclParser {
|
||||
tokens,
|
||||
position: 0,
|
||||
};
|
||||
let mut builder = VclBuilder {
|
||||
rules: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
ids: HashSet::new(),
|
||||
};
|
||||
let mut found = false;
|
||||
while let Some(token) = parser.next() {
|
||||
match token {
|
||||
VclToken::Ident(word) if word == "sub" => {
|
||||
let line = parser.line();
|
||||
let name = match parser.next() {
|
||||
Some(VclToken::Ident(name)) => name,
|
||||
other => {
|
||||
anyhow::bail!("line {line}: expected subroutine name, found {other:?}")
|
||||
}
|
||||
};
|
||||
let body = parser.block()?;
|
||||
match vcl_stage(&name) {
|
||||
Some(stage) => {
|
||||
found = true;
|
||||
builder.statements(stage, &body, None);
|
||||
}
|
||||
None => builder
|
||||
.warnings
|
||||
.push(format!("line {line}: sub {name} is not imported")),
|
||||
}
|
||||
}
|
||||
VclToken::Ident(word) if matches!(word.as_str(), "vcl" | "import" | "include") => {
|
||||
while !matches!(parser.next(), Some(VclToken::Sym(";")) | None) {}
|
||||
}
|
||||
VclToken::Ident(word) if matches!(word.as_str(), "backend" | "acl" | "probe") => {
|
||||
let line = parser.line();
|
||||
parser.next();
|
||||
parser.block()?;
|
||||
builder.warnings.push(format!("line {line}: {word} definitions are not imported; configure backends and ACLs in RustProxy"));
|
||||
}
|
||||
other => anyhow::bail!("line {}: unexpected {other:?} at top level", parser.line()),
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
found,
|
||||
"no vcl_recv, vcl_backend_response or vcl_deliver subroutine found"
|
||||
);
|
||||
Ok(VclImport {
|
||||
rules: builder.rules,
|
||||
warnings: builder.warnings,
|
||||
})
|
||||
}
|
||||
@@ -262,7 +262,7 @@ fn compile_routing(
|
||||
headers: host.headers.compile()?,
|
||||
security: host.security_headers.compile()?,
|
||||
compression: host.compression.clone(),
|
||||
cache: host.cache.resolve(&config.cache)?,
|
||||
cache: host.cache.resolve_for(&config.cache, &host.id)?,
|
||||
force_cache: host.cache.unsafe_force.clone(),
|
||||
transform: host.transform.resolve(&config.transform)?,
|
||||
pages: host.pages.clone(),
|
||||
|
||||
@@ -159,6 +159,21 @@ fn render_misc(app: &App, snapshot: &crate::config::Snapshot, f: &mut Families)
|
||||
);
|
||||
}
|
||||
if settings.include_cache_domains {
|
||||
for (key, count) in crate::cache::rule_hit_counts() {
|
||||
let (origin, rest) = key.split_once(':').unwrap_or(("global", key.as_str()));
|
||||
let (vhost, rule) = if origin == "vhost" {
|
||||
rest.split_once(':').unwrap_or(("", rest))
|
||||
} else {
|
||||
("", rest)
|
||||
};
|
||||
f.add(
|
||||
"rust_proxy_cache_rule_matches_total",
|
||||
"counter",
|
||||
"Cache rule matches since process start.",
|
||||
&labels(&[("origin", origin), ("vhost", vhost), ("rule", rule)]),
|
||||
count,
|
||||
);
|
||||
}
|
||||
let dashboard = app.cache.dashboard(None, 0, 1);
|
||||
f.add(
|
||||
"rust_proxy_cache_statistics_revision",
|
||||
|
||||
@@ -51,6 +51,7 @@ if let Some(ticket) = &cache_ticket {
|
||||
local: local.0,
|
||||
tls,
|
||||
base_headers: request.headers().clone(),
|
||||
rule_context: cache_rule_context.clone(),
|
||||
};
|
||||
let refresh_ticket = ticket.clone();
|
||||
tokio::spawn(async move {
|
||||
@@ -89,6 +90,7 @@ if let Some(ticket) = &cache_ticket {
|
||||
local: local.0,
|
||||
tls,
|
||||
base_headers: request.headers().clone(),
|
||||
rule_context: cache_rule_context.clone(),
|
||||
},
|
||||
ticket.clone(),
|
||||
hit.remaining_ttl,
|
||||
@@ -256,6 +258,7 @@ if handshake.is_none()
|
||||
local: local.0,
|
||||
tls,
|
||||
base_headers: request.headers().clone(),
|
||||
rule_context: cache_rule_context.clone(),
|
||||
},
|
||||
ticket.clone(),
|
||||
hit.remaining_ttl,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
).await {
|
||||
return fallback;
|
||||
}
|
||||
let (origin_validation_headers, origin_plan, origin_reason, mut response) =
|
||||
let (origin_validation_headers, origin_plan, origin_reason, mut response, cache_rule_overrides) =
|
||||
include!("success_prepare.rs");
|
||||
include!("success_finish.rs")
|
||||
}
|
||||
|
||||
@@ -123,6 +123,51 @@ if let Some(exchange) = request.extensions().get::<Arc<Exchange>>() {
|
||||
exchange.set_cache_enabled(cache_settings.active_for(route.cache));
|
||||
exchange.set_transform_enabled(transform_settings.is_some_and(|settings| settings.enabled));
|
||||
}
|
||||
let mut cache_rule_context: Option<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() {
|
||||
let mut rule_request = crate::cache::RuleRequest {
|
||||
host: host.clone(),
|
||||
path: path.to_string(),
|
||||
query: request.uri().query().map(str::to_owned),
|
||||
method: request.method().clone(),
|
||||
headers: request.headers().clone(),
|
||||
client_ip: Some(context.client_ip),
|
||||
};
|
||||
let outcome = rules.evaluate_request(&rule_request, true);
|
||||
if !outcome.matched.is_empty() {
|
||||
outcome.rewrite_cookies(request.headers_mut());
|
||||
cache_rule_query = outcome.rewrite_query(request.uri().query());
|
||||
if let Some(query) = &cache_rule_query {
|
||||
let target = match query {
|
||||
Some(query) => format!("{}?{}", request.uri().path(), query),
|
||||
None => request.uri().path().to_owned(),
|
||||
};
|
||||
let mut parts = request.uri().clone().into_parts();
|
||||
if let Ok(value) = http::uri::PathAndQuery::try_from(target) {
|
||||
parts.path_and_query = Some(value);
|
||||
if let Ok(uri) = Uri::from_parts(parts) {
|
||||
*request.uri_mut() = uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
cache_rule_variant = outcome.hash_variant();
|
||||
cache_rule_pass = outcome.pass.is_some();
|
||||
rule_request.headers = request.headers().clone();
|
||||
rule_request.query = request.uri().query().map(str::to_owned);
|
||||
}
|
||||
if rules.has_late_rules() {
|
||||
let rule_context = Arc::new(crate::cache::RuleContext { rules, request: rule_request });
|
||||
if let Some(sink) = request.extensions().get::<crate::cache::RuleSink>() {
|
||||
sink.set(rule_context.clone());
|
||||
}
|
||||
cache_rule_context = Some(rule_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
let policy_reason = if admin_control_plane {
|
||||
Some("admin_control_plane")
|
||||
} else if frontend.is_some_and(|f| f.basic_auth.is_some()) {
|
||||
@@ -141,6 +186,8 @@ let policy_reason = if admin_control_plane {
|
||||
Some("route_disabled")
|
||||
} else if handshake.is_some() {
|
||||
Some("request_upgrade")
|
||||
} else if cache_rule_pass {
|
||||
Some("cache_rule")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -161,9 +208,13 @@ let body_empty = if cache_enabled
|
||||
} else {
|
||||
cache_enabled && request.body().is_end_stream()
|
||||
};
|
||||
let public_suffix: std::borrow::Cow<'_, str> = std::borrow::Cow::Borrowed(
|
||||
routing_uri.path_and_query().map(|v| v.as_str()).unwrap_or("/")
|
||||
);
|
||||
let public_suffix: std::borrow::Cow<'_, str> = match &cache_rule_query {
|
||||
Some(query) => std::borrow::Cow::Owned(match query {
|
||||
Some(query) => format!("{}?{}", routing_uri.path(), query),
|
||||
None => routing_uri.path().to_owned(),
|
||||
}),
|
||||
None => std::borrow::Cow::Borrowed(routing_uri.path_and_query().map(|v| v.as_str()).unwrap_or("/")),
|
||||
};
|
||||
let cache_plan = cache_plan::CachePlan::new(policy_reason, cache_settings, &path, || {
|
||||
cache_settings.active_for(route.cache) && route
|
||||
.frontend
|
||||
@@ -287,7 +338,7 @@ let key_headers = cache_key_headers
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| request.headers());
|
||||
let cache_ticket = if effective_cacheable {
|
||||
state.cache.ticket_scoped_for_config(
|
||||
state.cache.ticket_scoped_for_config_variant(
|
||||
snapshot.envelope.revision,
|
||||
state.cache.revision(),
|
||||
route.frontend.as_ref().map(|f| f.id.as_str()).unwrap_or(""),
|
||||
@@ -296,6 +347,7 @@ let cache_ticket = if effective_cacheable {
|
||||
cache_route,
|
||||
&public_suffix,
|
||||
key_headers,
|
||||
&cache_rule_variant,
|
||||
).map(|ticket| ticket.with_varnish_compatible(cache_settings.varnish_compatible))
|
||||
} else {
|
||||
None
|
||||
@@ -327,6 +379,6 @@ let miss_recorded = false;
|
||||
origin_suffix, uri, exchange, lease, stop, downstream, h2_downstream,
|
||||
range_selection, if_range, range_requested, effective_reason, revalidation_reason,
|
||||
cache_ticket, client_conditionals, cached_revalidation, freshness_revalidation_reason,
|
||||
pending_revalidation, miss_recorded,
|
||||
pending_revalidation, miss_recorded, cache_rule_context,
|
||||
)
|
||||
}
|
||||
@@ -96,11 +96,12 @@ let transformed_plan =
|
||||
|| (ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie")) {
|
||||
None
|
||||
} else {
|
||||
crate::cache::plan(
|
||||
crate::cache::plan_with(
|
||||
response.status(),
|
||||
response.headers(),
|
||||
cache_settings,
|
||||
upstream_started.elapsed(),
|
||||
&cache_rule_overrides,
|
||||
)
|
||||
};
|
||||
let outcome = if cache_ticket.is_some() {
|
||||
@@ -181,6 +182,7 @@ if let (Some(ticket), Some(plan), Some(transformed)) =
|
||||
local: local.0,
|
||||
tls,
|
||||
base_headers: proactive_base_headers.clone(),
|
||||
rule_context: cache_rule_context.clone(),
|
||||
},
|
||||
proactive_ticket,
|
||||
proactive_remaining_ttl,
|
||||
|
||||
@@ -112,14 +112,22 @@ if handshake.as_ref().is_some_and(|handshake| {
|
||||
"RustProxy: HTTP/1.1 WebSocket upstream returned 2xx without switching protocols\n",
|
||||
);
|
||||
}
|
||||
let cache_rule_overrides = match (&cache_rule_context, cache_ticket.is_some()) {
|
||||
(Some(rule_context), true) => rule_context.response_overrides(response.status(), response.headers()),
|
||||
_ => crate::cache::ResponseOverrides::NONE,
|
||||
};
|
||||
if cache_rule_overrides.strip_set_cookie {
|
||||
response.headers_mut().remove(::http::header::SET_COOKIE);
|
||||
}
|
||||
let origin_plan = if cache_ticket.is_some()
|
||||
&& !(ignore_static_cookie && crate::cache::varies_on(response.headers(), "cookie"))
|
||||
{
|
||||
crate::cache::plan(
|
||||
crate::cache::plan_with(
|
||||
response.status(),
|
||||
response.headers(),
|
||||
cache_settings,
|
||||
upstream_started.elapsed(),
|
||||
&cache_rule_overrides,
|
||||
).map(|plan| {
|
||||
let plan = if force_vary_cookie { plan.with_vary("cookie") } else { plan };
|
||||
if force_vary_authorization { plan.with_vary("authorization") } else { plan }
|
||||
@@ -392,5 +400,5 @@ if !range_requested && handshake.is_none() {
|
||||
};
|
||||
}
|
||||
}
|
||||
(origin_validation_headers, origin_plan, origin_reason, response)
|
||||
(origin_validation_headers, origin_plan, origin_reason, response, cache_rule_overrides)
|
||||
}
|
||||
@@ -6,8 +6,11 @@ async fn forward(
|
||||
) -> Response {
|
||||
let cookies = crate::auth_provider::CookieSink::default();
|
||||
request.extensions_mut().insert(cookies.clone());
|
||||
let cache_rules = crate::cache::RuleSink::default();
|
||||
request.extensions_mut().insert(cache_rules.clone());
|
||||
let mut response = forward_request(state, peer, local, request).await;
|
||||
cookies.apply(&mut response);
|
||||
cache_rules.apply(&mut response);
|
||||
response
|
||||
}
|
||||
|
||||
@@ -593,6 +596,7 @@ async fn forward_request(
|
||||
freshness_revalidation_reason,
|
||||
pending_revalidation,
|
||||
mut miss_recorded,
|
||||
cache_rule_context,
|
||||
) = include!("forward/route_cache.rs");
|
||||
|
||||
let (serve_stale, mut fill_leader) = include!("forward/cache_lookup.rs");
|
||||
|
||||
+14
-2
@@ -299,6 +299,7 @@ struct CacheRefreshContext {
|
||||
local: std::net::SocketAddr,
|
||||
tls: bool,
|
||||
base_headers: http::HeaderMap,
|
||||
rule_context: Option<Arc<crate::cache::RuleContext>>,
|
||||
}
|
||||
|
||||
async fn refresh_cache_once(
|
||||
@@ -379,11 +380,21 @@ async fn refresh_cache_once(
|
||||
if origin.status() != StatusCode::OK {
|
||||
return false;
|
||||
}
|
||||
let Some(origin_plan) = crate::cache::plan(
|
||||
let rule_overrides = context
|
||||
.rule_context
|
||||
.as_ref()
|
||||
.map(|rules| rules.response_overrides(origin.status(), origin.headers()))
|
||||
.unwrap_or(crate::cache::ResponseOverrides::NONE);
|
||||
let mut origin = origin;
|
||||
if rule_overrides.strip_set_cookie {
|
||||
origin.headers_mut().remove(::http::header::SET_COOKIE);
|
||||
}
|
||||
let Some(origin_plan) = crate::cache::plan_with(
|
||||
origin.status(),
|
||||
origin.headers(),
|
||||
&context.cache_settings,
|
||||
started.elapsed(),
|
||||
&rule_overrides,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
@@ -446,11 +457,12 @@ async fn refresh_cache_once(
|
||||
.extensions()
|
||||
.get::<crate::transform::CanonicalIdentity>()
|
||||
.is_some();
|
||||
let Some(transformed_plan) = crate::cache::plan(
|
||||
let Some(transformed_plan) = crate::cache::plan_with(
|
||||
refreshed.status(),
|
||||
refreshed.headers(),
|
||||
&context.cache_settings,
|
||||
started.elapsed(),
|
||||
&rule_overrides,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -2,8 +2,10 @@ fn certificate_dns_names(certificate: &[u8]) -> Result<Vec<String>> {
|
||||
let mut reader = certificate;
|
||||
let certs = rustls_pemfile::certs(&mut reader).collect::<io::Result<Vec<_>>>()?;
|
||||
let leaf = certs.first().context("certificate chain is empty")?;
|
||||
let der = leaf.as_ref();
|
||||
certificate_der_dns_names(leaf.as_ref())
|
||||
}
|
||||
|
||||
fn certificate_der_dns_names(der: &[u8]) -> Result<Vec<String>> {
|
||||
let mut root_offset = 0;
|
||||
let (tag, certificate_sequence) = der_tlv(der, &mut root_offset)?;
|
||||
ensure!(
|
||||
@@ -346,6 +348,7 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result<Option<A
|
||||
return Ok(None);
|
||||
};
|
||||
let mut names = HashMap::<String, Arc<CertifiedKey>>::new();
|
||||
let mut covered = HashMap::<String, (usize, Arc<CertifiedKey>)>::new();
|
||||
let mut ids = HashSet::new();
|
||||
let mut hosts = HashSet::new();
|
||||
let mut default = None;
|
||||
@@ -353,6 +356,27 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result<Option<A
|
||||
safe_name(&cert.id)?;
|
||||
ensure!(ids.insert(cert.id.clone()), "duplicate certificate id");
|
||||
let key = load_pair(directory, &cert.cert_file, &cert.key_file)?;
|
||||
let shared = Arc::new(key.clone());
|
||||
let mut san = key
|
||||
.cert
|
||||
.first()
|
||||
.and_then(|leaf| certificate_der_dns_names(leaf.as_ref()).ok())
|
||||
.unwrap_or_default();
|
||||
san.extend(cert.covered_hosts.iter().cloned());
|
||||
san.sort();
|
||||
san.dedup();
|
||||
let size = san.len();
|
||||
for name in &san {
|
||||
let Ok(name) = normalize_host_pattern(name) else {
|
||||
continue;
|
||||
};
|
||||
if covered
|
||||
.get(&name)
|
||||
.is_none_or(|(current, _)| size < *current)
|
||||
{
|
||||
covered.insert(name, (size, shared.clone()));
|
||||
}
|
||||
}
|
||||
for host in &cert.hosts {
|
||||
let host = normalize_host_pattern(host)?;
|
||||
ensure!(hosts.insert(host.clone()), "duplicate TLS hostname binding");
|
||||
@@ -389,7 +413,14 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result<Option<A
|
||||
None => Arc::new(load_pair(directory, "default.pem", "default.key")?),
|
||||
};
|
||||
Ok(Some(server_config(
|
||||
Arc::new(Resolver { names, fallback }),
|
||||
Arc::new(Resolver {
|
||||
names,
|
||||
covered: covered
|
||||
.into_iter()
|
||||
.map(|(name, (_, key))| (name, key))
|
||||
.collect(),
|
||||
fallback,
|
||||
}),
|
||||
&settings.policy,
|
||||
true,
|
||||
)?))
|
||||
|
||||
@@ -384,6 +384,29 @@ mod tests {
|
||||
assert!(compile(&settings, Some(dir.path())).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn sni_wildcards_cover_one_label_and_san_names_are_used_before_the_default() {
|
||||
let dir = private_tempdir();
|
||||
generate(dir.path(), "parent", vec!["*.h.example.test".into()]).unwrap();
|
||||
generate(dir.path(), "apps", vec!["*.apps.h.example.test".into()]).unwrap();
|
||||
let parent = Arc::new(load_pair(dir.path(), "parent.pem", "parent.key").unwrap());
|
||||
let apps = Arc::new(load_pair(dir.path(), "apps.pem", "apps.key").unwrap());
|
||||
let resolver = Resolver {
|
||||
names: HashMap::from([("*.h.example.test".to_string(), parent.clone())]),
|
||||
covered: HashMap::from([("*.apps.h.example.test".to_string(), apps.clone())]),
|
||||
fallback: parent.clone(),
|
||||
};
|
||||
assert!(Arc::ptr_eq(&resolver.named("x.h.example.test").unwrap(), &parent));
|
||||
assert!(Arc::ptr_eq(&resolver.named("x.apps.h.example.test").unwrap(), &apps));
|
||||
assert!(resolver.named("deep.x.h.example.test").is_none());
|
||||
assert_eq!(single_label_wildcard("a.b.c").as_deref(), Some("*.b.c"));
|
||||
assert_eq!(single_label_wildcard("a.b"), None);
|
||||
let leaf = apps.cert.first().unwrap();
|
||||
assert_eq!(
|
||||
certificate_der_dns_names(leaf.as_ref()).unwrap(),
|
||||
["*.apps.h.example.test"]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn named_generation_never_overwrites_keys() {
|
||||
let dir = private_tempdir();
|
||||
generate(dir.path(), "app", vec!["app.localhost".into()]).unwrap();
|
||||
|
||||
+11
-11
@@ -266,22 +266,22 @@ pub struct Certificate {
|
||||
#[derive(Debug)]
|
||||
struct Resolver {
|
||||
names: HashMap<String, Arc<CertifiedKey>>,
|
||||
covered: HashMap<String, Arc<CertifiedKey>>,
|
||||
fallback: Arc<CertifiedKey>,
|
||||
}
|
||||
fn single_label_wildcard(host: &str) -> Option<String> {
|
||||
let (first, rest) = host.split_once('.')?;
|
||||
(!first.is_empty() && rest.contains('.')).then(|| format!("*.{rest}"))
|
||||
}
|
||||
fn lookup(map: &HashMap<String, Arc<CertifiedKey>>, host: &str) -> Option<Arc<CertifiedKey>> {
|
||||
map.get(host)
|
||||
.or_else(|| single_label_wildcard(host).and_then(|wildcard| map.get(&wildcard)))
|
||||
.cloned()
|
||||
}
|
||||
impl Resolver {
|
||||
fn named(&self, server_name: &str) -> Option<Arc<CertifiedKey>> {
|
||||
let host = normalize_host(server_name).ok()?;
|
||||
if let Some(key) = self.names.get(&host) {
|
||||
return Some(key.clone());
|
||||
}
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
for index in 1..labels.len().saturating_sub(1) {
|
||||
let wildcard = format!("*.{}", labels[index..].join("."));
|
||||
if let Some(key) = self.names.get(&wildcard) {
|
||||
return Some(key.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
lookup(&self.names, &host).or_else(|| lookup(&self.covered, &host))
|
||||
}
|
||||
}
|
||||
impl ResolvesServerCert for Resolver {
|
||||
|
||||
Reference in new issue
Block a user