Files
RustProxy/src/admin/web/app/runtime.js
T
2026-11-28 17:36:53 +01:00

936 lines
71 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
function verifyAdminModules() {
const required = [
["rustProxyIntegrations", "bindings"],
["rustProxyVhosts", "render"],
["rustProxySettings", "render"],
["rustProxyCachePanel", "refresh"],
["rustProxyTrafficPanel", "refresh"],
["rustProxyPreferences", "load"],
["rustProxyRefresh", "start"],
["rustProxyPermissions", "render"],
["rustProxyCertificateInspection", "read"],
];
const missing = required.find(([module, method]) => typeof window[module]?.[method] !== "function");
if (missing) throw new Error(`Panel resources incomplete (${missing[0]}). Reload to retry.`);
}
async function startAdminPanel() {
try {
verifyAdminModules();
const info = await api("/api/auth/session");
await loadLanguages();
setupRequired = false;
translate();
syncAuthForm();
if (await activate(info)) clearInvalidOriginRecovery();
} catch (e) {
if (recoverInvalidOrigin(e)) return;
if (e.status === 401) {
location.replace(`${location.pathname}${location.search}`);
return;
}
showStartupFailure(e);
}
}
if (document.readyState === "complete") startAdminPanel();
else document.addEventListener("DOMContentLoaded", startAdminPanel, { once: true });
function certificateUsesExternalFiles(cert) {
return String(cert?.cert_file || "").startsWith("/") && String(cert?.key_file || "").startsWith("/");
}
function syncCertificatePermissions() {
window.rustProxyPermissions?.render($("certificate-external-acl-example"), {
kind: "certificate", paths: [$("certificate-file").value, $("certificate-key").value],
enabled: $("certificate-file-source").value === "external",
});
}
function syncCertificateFileSource() {
const external = $("certificate-file-source").value === "external";
const cert = $("certificate-file"), key = $("certificate-key");
for (const input of [cert, key]) {
input.maxLength = external ? 4096 : 96;
if (external) input.removeAttribute("pattern");
else input.pattern = "[A-Za-z0-9_.\\-]+";
}
cert.placeholder = external ? "/etc/letsencrypt/live/example.com/fullchain.pem" : "app.pem";
key.placeholder = external ? "/etc/letsencrypt/live/example.com/privkey.pem" : "app.key";
const helpKey = external ? "certificateSourceExternalHelp" : "certificateSourceManagedHelp";
$("certificate-file-source-help").dataset.i18n = helpKey;
$("certificate-file-source-help").textContent = t(helpKey);
syncCertificatePermissions();
window.rustProxyCertificateInspection?.refresh();
}
$("certificate-file-source").addEventListener("change", syncCertificateFileSource);
for (const id of ["certificate-file", "certificate-key"]) {
$(id).addEventListener("input", syncCertificatePermissions);
$(id).addEventListener("change", syncCertificatePermissions);
}
function certificateUsage(cert) {
const config = envelope?.config || {}, settings = config.tls || {};
const hostsOf = item => item?.frontend?.hosts || [];
const groups = {
vhosts: (config.vhosts || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), mismatch: item.allow_certificate_mismatch === true, open: () => { setPanel("vhosts"); window.rustProxyVhosts?.edit(item.id); } })),
redirects: (config.redirects || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), open: () => { setPanel("redirects"); window.rustProxyRedirects?.edit(item.id); } })),
notfound: (config.not_found_hosts || []).filter(item => item.certificate_id === cert.id).map(item => ({ id: item.id, hosts: hostsOf(item), open: () => { setPanel("notfound"); window.rustProxyNotFound?.edit(item.id); } })),
docker: (config.docker_agents?.agents || []).filter(agent => [agent.certificate_id, ...(agent.certificate_ids || [])].includes(cert.id)).map(agent => ({ id: agent.id, hosts: agent.domains || [], open: () => setPanel("settings") }))
};
const legacy = [];
for (const item of config.vhosts || []) if (item.certificate_id === cert.id) legacy.push(`vhost:${item.id}`);
for (const item of config.redirects || []) if (item.certificate_id === cert.id) legacy.push(`redirect:${item.id}`);
for (const item of config.not_found_hosts || []) if (item.certificate_id === cert.id) legacy.push(`404:${item.id}`);
const admin = config.administration?.certificate_id === cert.id, isDefault = settings.default_certificate === cert.id;
if (admin) legacy.push(t("administration"));
if (isDefault) legacy.push(t("defaultLabel"));
const count = groups.vhosts.length + groups.redirects.length + groups.notfound.length + (admin ? 1 : 0) + (isDefault ? 1 : 0);
return { groups, admin, isDefault, legacy, count, inUse: legacy.length > 0 };
}
function certificateCoverage(cert) {
const inventory = certificateInventory.get(cert.id);
return inventory?.covered_hosts?.length ? inventory.covered_hosts : (cert.covered_hosts || []);
}
function certificateCovers(coverage, host) { return coverage.some(pattern => window.rustProxyAutoCertificate.covers(pattern, host)); }
function certificateCoverageState(coverage, hosts) {
if (!hosts.length || !coverage.length) return { state: "unknown", missing: [] };
const missing = hosts.filter(host => !certificateCovers(coverage, host));
return { state: missing.length === 0 ? "full" : missing.length === hosts.length ? "none" : "partial", missing };
}
let certificateFilter = "all";
const certificateOpenRows = new Set();
function certificateTimeline(inventory) {
const days = inventory?.days_remaining, to = Number(inventory?.not_after_unix);
const box = el("div", undefined, "certificate-validity");
const tone = inventory?.expiry_status === "expired" ? "bad" : inventory?.expiry_status === "warning" ? "warn" : "ok";
box.dataset.tone = days == null ? "unknown" : tone;
const text = days == null ? t("certificateValidityUnknown") : `${t("certificateDaysLeft").replace("{days}", days)} · ${t("certificateUntil")} ${formatDate(to * 1000)}`;
const bar = el("span", undefined, "certificate-validity-bar"), fill = el("i");
const ratio = days == null ? 0 : Math.max(0, Math.min(1, Number(days) / 90));
fill.style.width = `${Math.round(ratio * 100)}%`; bar.append(fill);
box.append(el("span", text, "certificate-validity-text"), bar);
return box;
}
function formatDate(ms) { try { return new Date(ms).toLocaleDateString(typeof language !== "undefined" ? language.replace("_", "-") : undefined); } catch { return new Date(ms).toISOString().slice(0, 10); } }
function renderCertificateSummary(certificates) {
const box = $("certificate-summary"); if (!box) return;
const settings = envelope?.config.tls || {};
let acme = 0, external = 0, managedFiles = 0, expiring = [], assignments = 0, vhostCount = 0, redirectCount = 0, notfoundCount = 0;
for (const cert of certificates) {
if (cert.issuer) acme++; else if (certificateUsesExternalFiles(cert)) external++; else managedFiles++;
const inventory = certificateInventory.get(cert.id);
if (["warning", "expired"].includes(inventory?.expiry_status)) expiring.push(`${cert.id} · ${inventory?.days_remaining ?? "-"} ${t("certificateDaysShort")}`);
const usage = certificateUsage(cert); assignments += usage.count; vhostCount += usage.groups.vhosts.length; redirectCount += usage.groups.redirects.length; notfoundCount += usage.groups.notfound.length;
}
const tile = (value, titleKey, line, tone, filter) => {
const node = el(filter ? "button" : "div", undefined, `cert-summary-tile${tone ? ` is-${tone}` : ""}`);
if (filter) { node.type = "button"; node.dataset.uiIconName = "none"; node.addEventListener("click", () => { window.rustProxyAcme?.select("installed"); setCertificateFilter(filter); }); }
const title = el("span", t(titleKey)); title.dataset.i18n = titleKey;
node.append(el("b", value), title, el("small", line)); return node;
};
const runtime = $("acme-runtime-state")?.textContent || "";
box.replaceChildren(
tile(String(certificates.length), "certificateSummaryCount", `${acme} ACME · ${external} ${t("certificateSummaryExternal")} · ${managedFiles} ${t("certificateSummaryManaged")}`, certificates.length ? "ok" : "", "all"),
tile(String(expiring.length), "certificateSummaryExpiring", expiring.length ? expiring.slice(0, 2).join(", ") : t("certificateSummaryNothingExpiring"), expiring.length ? "warn" : "ok", "expiring"),
tile(String(assignments), "certificateSummaryAssignments", `${vhostCount} vhost · ${redirectCount} ${t("certificateSummaryRedirects")} · ${notfoundCount} 404${settings.default_certificate ? ` · ${t("defaultLabel")}: ${settings.default_certificate}` : ""}`, "", "unassigned"),
tile(runtime || "-", "certificateSummaryRuntime", $("acme-runtime-components")?.textContent || "", $("acme-runtime-card")?.dataset.state === "ready" ? "ok" : $("acme-runtime-card")?.dataset.state === "unavailable" ? "bad" : "")
);
}
function setCertificateFilter(value) {
certificateFilter = value;
for (const button of document.querySelectorAll("[data-certificate-filter]")) button.setAttribute("aria-pressed", String(button.dataset.certificateFilter === value));
applyCertificateFilter();
}
function applyCertificateFilter() {
const query = ($("certificate-search")?.value || "").trim().toLowerCase();
let shown = 0;
for (const row of document.querySelectorAll("#certificate-list > .certificate-row")) {
const matchesQuery = !query || row.dataset.search.includes(query);
const matchesFilter = certificateFilter === "all" || (certificateFilter === "expiring" && row.dataset.expiring === "true") || (certificateFilter === "unassigned" && row.dataset.assigned === "false");
row.hidden = !(matchesQuery && matchesFilter); if (!row.hidden) shown++;
}
const empty = $("certificate-list-filtered-empty");
if (empty) empty.hidden = shown > 0 || !document.querySelector("#certificate-list > .certificate-row");
}
function renderCertificates() {
if (!envelope) return;
const settings = envelope.config.tls || {};
const certificates = settings.certificates || [];
const entries = certificates.map(cert => {
const inventory = certificateInventory.get(cert.id);
const coverage = certificateCoverage(cert);
const bindings = cert.hosts || [];
const usage = certificateUsage(cert), used = usage.legacy;
const managed = !!cert.issuer, inUse = usage.inUse;
const box = el("details", undefined, "entity certificate-card certificate-row");
box.dataset.certificateId = cert.id;
box.dataset.expiring = String(["warning", "expired"].includes(inventory?.expiry_status));
box.dataset.assigned = String(usage.count > 0);
box.dataset.search = [cert.id, ...coverage, ...bindings, ...usage.groups.vhosts.map(item => item.id), ...usage.groups.redirects.map(item => item.id), ...usage.groups.notfound.map(item => item.id)].join(" ").toLowerCase();
box.open = certificateOpenRows.has(cert.id);
box.addEventListener("toggle", () => { if (box.open) certificateOpenRows.add(cert.id); else certificateOpenRows.delete(cert.id); });
const summary = el("summary", undefined, "certificate-row-summary");
const dot = el("span", undefined, "certificate-state-dot"); dot.dataset.tone = inventory?.expiry_status === "expired" ? "bad" : inventory?.expiry_status === "warning" ? "warn" : inventory ? "ok" : "unknown";
const identity = el("div", undefined, "certificate-card-identity");
identity.append(el("span", cert.id, "entity-title"));
const statePills = el("div", undefined, "vhost-policy-pills certificate-state-pills");
if (managed) statePills.append(el("small", `${t("certificateManaged")} · ${cert.issuer.provider} / ${cert.issuer.environment}`, "pill live"));
else if (certificateUsesExternalFiles(cert)) statePills.append(el("small", t("certificateExternalFiles"), "pill"));
else statePills.append(el("small", t("certificateManagedFiles"), "pill"));
if (settings.default_certificate === cert.id) statePills.append(el("small", t("defaultLabel"), "pill live"));
if (inventory?.expiry_status === "expired") statePills.append(el("small", t("certificateExpired"), "pill status-error"));
else if (inventory?.expiry_status === "warning") statePills.append(el("small", t("certificateExpiresSoon"), "pill status-error"));
identity.append(statePills);
const coverageBlock = el("div", undefined, "certificate-coverage");
const domainPills = el("div", undefined, "vhost-policy-pills certificate-domain-pills");
if (coverage.length) {
for (const host of coverage.slice(0, 3)) domainPills.append(el("small", host, "pill"));
if (coverage.length > 3) domainPills.append(el("small", `+${coverage.length - 3}`, "pill"));
} else domainPills.append(el("small", t("certificateCoverageUnknown"), "certificate-coverage-unknown"));
coverageBlock.append(domainPills);
const usageCell = el("div", undefined, "certificate-usage-cell");
const usageParts = [];
if (usage.groups.vhosts.length) usageParts.push(`${usage.groups.vhosts.length} vhost`);
if (usage.groups.redirects.length) usageParts.push(`${usage.groups.redirects.length} ${t("certificateSummaryRedirects")}`);
if (usage.groups.notfound.length) usageParts.push(`${usage.groups.notfound.length} 404`);
if (usage.admin) usageParts.push(t("administration"));
if (usage.isDefault) usageParts.push(t("defaultLabel"));
usageCell.append(el("b", String(usage.count)), el("span", usageParts.join(" · ") || t("certUnassigned"), "fine"));
summary.append(dot, identity, coverageBlock, certificateTimeline(inventory), usageCell, el("span", "", "certificate-row-chevron"));
box.append(summary);
const body = el("div", undefined, "certificate-row-body");
const usageSection = el("section", undefined, "certificate-section certificate-usage");
const usageHead = el("h4"); usageHead.append(el("span", t("certificateWhereUsed")), el("span", String(usage.count), "pill"));
usageSection.append(usageHead);
const groupDefs = [["vhosts", "certificateGroupVhosts"], ["redirects", "certificateGroupRedirects"], ["notfound", "certificateGroupNotFound"], ["docker", "certificateGroupDocker"]];
let anyUsage = false;
for (const [key, labelKey] of groupDefs) {
const items = usage.groups[key]; if (!items.length) continue; anyUsage = true;
const group = el("div", undefined, "certificate-usage-group");
group.append(el("span", `${t(labelKey)} · ${items.length}`, "small-label"));
for (const item of items) {
const row = el("div", undefined, "certificate-usage-row");
const cover = certificateCoverageState(coverage, item.hosts);
const pillText = cover.state === "full" ? t("certificateCovered") : cover.state === "unknown" ? t("certificateCoverageUnknownShort") : `${t("certificateNotCovered")}: ${cover.missing.join(", ")}${item.mismatch ? ` · ${t("certificateMismatchAccepted")}` : ""}`;
const open = el("button", t("certificateOpen"), "quiet certificate-usage-open"); open.type = "button"; open.dataset.uiIconName = "none"; open.addEventListener("click", item.open);
row.append(el("span", item.id, "mono"), el("span", item.hosts.join(", ") || "-", "fine"), el("span", pillText, `pill${cover.state === "full" ? " live" : cover.state === "unknown" ? "" : " warn"}`), open);
group.append(row);
}
usageSection.append(group);
}
const extra = [];
if (usage.admin) extra.push(t("administration"));
if (usage.isDefault) extra.push(t("certificateDefaultSni"));
if (extra.length) { anyUsage = true; usageSection.append(el("p", `${t("certificateAlsoUsedBy")}: ${extra.join(", ")}`, "fine")); }
if (!anyUsage) usageSection.append(el("p", t("certUnassigned"), "fine"));
usageSection.append(el("p", t("certificateUsageHelp"), "fine certificate-usage-help"));
const side = el("div", undefined, "certificate-row-side");
const stamp = value => Number(value) ? formatDateTime(Number(value) * 1000) : "-";
const kv = (rows) => { const list = el("dl", undefined, "certificate-kv"); for (const [key, value] of rows) list.append(el("dt", t(key)), el("dd", value)); return list; };
const details = el("section", undefined, "certificate-section certificate-details");
details.append(el("h4", t("certificateDetails")), kv([
["certificateIssuerName", inventory?.certificate_issuer || "-"],
["certificateValidFrom", stamp(inventory?.not_before_unix)],
["renewalExpires", stamp(inventory?.not_after_unix)],
["certificateDaysRemaining", String(inventory?.days_remaining ?? "-")],
["certificateBindings", bindings.join(", ") || "-"],
["certAssigned", used.join(", ") || t("certUnassigned")]
]));
const renewal = el("section", undefined, "certificate-section certificate-renewal-summary");
renewal.append(el("h4", t("certificateRenewalStatus")), kv([
["certificateRenewalStatus", inventory?.renewal_status || "-"],
["renewalLast", stamp(inventory?.last_renewal_attempt)],
["certificateRenewalError", inventory?.last_renewal_error ? t(inventory.last_renewal_error) : "-"]
]));
if (managed) { const link = el("button", t("certificateRenewalActionsLink"), "quiet"); link.type = "button"; link.dataset.uiIconName = "none"; link.addEventListener("click", () => window.rustProxyAcme?.select("renewal")); renewal.append(link); }
const files = el("section", undefined, "certificate-section certificate-files");
files.append(el("h4", t("certificateFiles")), el("p", `${cert.cert_file}\n${cert.key_file}`, "mono certificate-file-paths"));
const buttons = el("div", undefined, "entity-actions");
const assignButton = action(t("certAssignVhosts"), () => openCertificateAssign(cert));
assignButton.disabled = !(envelope.config.vhosts || []).length;
buttons.append(assignButton);
if (!managed) {
buttons.append(action(t("reloadCertificate"), async () => {
if (busy) return;
try {
busy = true;
const result = await api(`/api/certificates/${encodeURIComponent(cert.id)}/reload`, { method: "POST", body: "{}" });
await refreshCertificateInventory();
renderCertificates();
toast(`${t("reloadCertificate")}: ${result.reloaded ? "OK" : "-"}`);
if (result.administration_restart_required) toast(t("certificateAdminRestartRequired"), true);
} catch (error) { toast(error.message, true); } finally { busy = false; }
}));
buttons.append(action(t("edit"), () => {
window.rustProxyCertificates?.open("existing"); $("certificate-advanced").open = true;
$("certificate-id").value = cert.id; $("certificate-hosts").value = (cert.hosts || []).join(", ");
$("certificate-file-source").value = certificateUsesExternalFiles(cert) ? "external" : "managed";
$("certificate-file").value = cert.cert_file; $("certificate-key").value = cert.key_file;
$("certificate-default").checked = settings.default_certificate === cert.id;
window.rustProxyCertificateInspection?.reset({ preserveNames: true });
syncCertificateFileSource(); window.rustProxyCertificateInspection?.schedule();
}));
}
const remove = action(t("remove"), async () => { if (inUse) { toast(t("certInUse"), true); return; } if (!(await appConfirm(t("confirmDelete"), { danger: true }))) return; const next = structuredClone(envelope.config); next.tls.certificates = next.tls.certificates.filter(v => v.id !== cert.id); await saveSection("tls", next.tls); });
remove.disabled = inUse; remove.title = inUse ? t("certInUse") : ""; buttons.append(remove);
side.append(details, renewal, files, buttons);
body.append(usageSection, side);
box.append(body);
return box;
});
const filteredEmpty = el("p", t("certificateFilterEmpty"), "empty"); filteredEmpty.id = "certificate-list-filtered-empty"; filteredEmpty.hidden = true;
$("certificate-list").replaceChildren(...entries, filteredEmpty);
if (!entries.length) $("certificate-list").append(el("p", t("emptyCertificates"), "empty"));
renderCertificateSummary(certificates);
applyCertificateFilter();
window.rustProxyCertificates?.syncSource?.();
syncCertificatePermissions();
}
let certificateAssignState = null;
function openCertificateAssign(cert) {
const dialog = $("certificate-assign-dialog"); if (!dialog || !envelope) return;
const coverage = certificateCoverage(cert);
const rows = (envelope.config.vhosts || []).map(host => {
const hosts = host.frontend?.hosts || [], cover = certificateCoverageState(coverage, hosts);
const selectable = cover.state === "full" || cover.state === "unknown" || host.allow_certificate_mismatch === true || host.certificate_id === cert.id;
return { host, hosts, cover, selectable, initial: host.certificate_id === cert.id, checked: host.certificate_id === cert.id };
});
certificateAssignState = { cert, rows, filter: "matching", query: "" };
$("certificate-assign-title").textContent = `${t("certAssignVhosts")} · ${cert.id}`;
$("certificate-assign-domains").replaceChildren(...coverage.slice(0, 4).map(host => el("span", host, "pill")), ...(coverage.length > 4 ? [el("span", `+${coverage.length - 4}`, "pill")] : []));
$("certificate-assign-search").value = "";
renderCertificateAssign();
if (!dialog.open) dialog.showModal();
}
function renderCertificateAssign() {
const state = certificateAssignState; if (!state) return;
const counts = { matching: state.rows.filter(row => row.cover.state === "full").length, assigned: state.rows.filter(row => row.checked).length, all: state.rows.length };
const filters = $("certificate-assign-filters");
filters.replaceChildren(...[["matching", "certificateAssignMatching"], ["assigned", "certificateAssignAssigned"], ["all", "certificateFilterAll"]].map(([key, labelKey]) => {
const button = el("button", `${t(labelKey)} · ${counts[key]}`); button.type = "button"; button.dataset.uiIconName = "none";
button.setAttribute("aria-pressed", String(state.filter === key));
button.addEventListener("click", () => { state.filter = key; renderCertificateAssign(); });
return button;
}));
const query = state.query.toLowerCase(), list = $("certificate-assign-list");
const head = el("div", undefined, "certificate-assign-row certificate-assign-head");
for (const key of ["", "certificateAssignColVhost", "certificateAssignColHosts", "certificateAssignColCoverage", "certificateAssignColNow"]) head.append(el("span", key ? t(key) : ""));
const visible = state.rows.filter(row => (state.filter === "all" || (state.filter === "matching" && row.cover.state === "full") || (state.filter === "assigned" && row.checked))
&& (!query || `${row.host.id} ${row.hosts.join(" ")}`.toLowerCase().includes(query)));
const items = visible.map(row => {
const line = el("label", undefined, "certificate-assign-row");
const check = document.createElement("input"); check.type = "checkbox"; check.checked = row.checked; check.disabled = !row.selectable && !row.checked;
check.addEventListener("change", () => { row.checked = check.checked; renderCertificateAssign(); });
const coverText = row.cover.state === "full" ? t("certificateCoveredAll") : row.cover.state === "unknown" ? t("certificateCoverageUnknownShort") : row.cover.state === "none" ? t("certificateCoverageNone") : `${t("certificateCoveragePartial").replace("{covered}", row.hosts.length - row.cover.missing.length).replace("{total}", row.hosts.length)}`;
const coverExtra = row.cover.state !== "full" && row.cover.state !== "unknown" ? (row.host.allow_certificate_mismatch ? ` · ${t("certificateMismatchAccepted")}` : ` · ${t("certificateMismatchRequired")}`) : "";
const now = el("span", undefined, "certificate-assign-now");
if (row.checked !== row.initial) now.append(el("span", t(row.checked ? "certificateAssignAdd" : "certificateAssignRemove"), `pill ${row.checked ? "warn" : "status-error"}`), " ");
now.append(el("span", row.host.certificate_id ? (row.host.certificate_id === state.cert.id ? t("certificateAssignThis") : row.host.certificate_id) : t("certificateAssignDefault"), "fine"));
line.classList.toggle("is-changed", row.checked !== row.initial);
line.classList.toggle("is-disabled", check.disabled);
line.append(check, el("b", row.host.id, "mono"), el("span", row.hosts.join(", ") || "-", "fine"), el("span", coverText + coverExtra, `pill${row.cover.state === "full" ? " live" : row.cover.state === "unknown" ? "" : " warn"}`), now);
return line;
});
list.replaceChildren(head, ...(items.length ? items : [el("p", t("certificateFilterEmpty"), "empty")]));
const added = state.rows.filter(row => row.checked && !row.initial).length, removed = state.rows.filter(row => !row.checked && row.initial).length;
const changes = $("certificate-assign-changes"); changes.replaceChildren();
if (added || removed) {
changes.append(el("b", `${t("certificateAssignChanges")}: `));
if (added) changes.append(el("span", `+${added} ${t("certificateAssignAdded")}`, "pill live"), " ");
if (removed) changes.append(el("span", `−${removed} ${t("certificateAssignRemoved")}`, "pill status-error"));
} else changes.append(el("span", t("certificateAssignNoChanges"), "fine"));
$("certificate-assign-apply").disabled = !(added || removed);
}
$("certificate-assign-search")?.addEventListener("input", event => { if (certificateAssignState) { certificateAssignState.query = event.target.value; renderCertificateAssign(); } });
$("certificate-assign-all")?.addEventListener("click", () => { if (!certificateAssignState) return; for (const row of certificateAssignState.rows) if (row.cover.state === "full") row.checked = true; renderCertificateAssign(); });
$("certificate-assign-none")?.addEventListener("click", () => { if (!certificateAssignState) return; for (const row of certificateAssignState.rows) row.checked = false; renderCertificateAssign(); });
for (const id of ["certificate-assign-close", "certificate-assign-cancel"]) $(id)?.addEventListener("click", () => { $("certificate-assign-dialog").close(); });
$("certificate-assign-dialog")?.addEventListener("close", () => { certificateAssignState = null; });
$("certificate-assign-apply")?.addEventListener("click", async () => {
const state = certificateAssignState; if (!state || busy || !envelope) return;
const selected = new Set(state.rows.filter(row => row.checked).map(row => row.host.id));
const next = structuredClone(envelope.config);
for (const host of next.vhosts) {
if (selected.has(host.id)) host.certificate_id = state.cert.id;
else if (host.certificate_id === state.cert.id) host.certificate_id = null;
}
if (await saveSection("vhosts", next.vhosts)) $("certificate-assign-dialog").close();
});
$("certificate-search")?.addEventListener("input", applyCertificateFilter);
for (const button of document.querySelectorAll("[data-certificate-filter]")) button.addEventListener("click", () => setCertificateFilter(button.dataset.certificateFilter));
$("certificate-form").addEventListener("submit", async event => {
event.preventDefault(); const form = event.currentTarget;
if (!envelope || busy) return;
try {
await withFormSubmitState(form, event.submitter, async () => {
const epoch = authEpoch;
if (await window.rustProxyCertificateInspection?.beforeSave() === false) return;
if (!authenticated || epoch !== authEpoch || !envelope || busy) return;
const next = structuredClone(envelope.config);
next.tls ||= {}; next.tls.certificates ||= [];
const cert = {
id: $("certificate-id").value.trim(),
hosts: $("certificate-hosts").value.split(",").map(v => v.trim()).filter(Boolean),
cert_file: $("certificate-file").value.trim(), key_file: $("certificate-key").value.trim(),
};
const index = next.tls.certificates.findIndex(v => v.id === cert.id);
if (index >= 0 && next.tls.certificates[index].issuer) throw fieldError($("certificate-id"), t("certManagedReadOnly"));
if (index < 0) next.tls.certificates.push(cert);
else {
const old = next.tls.certificates[index], sameFiles = old.cert_file === cert.cert_file && old.key_file === cert.key_file;
next.tls.certificates[index] = { ...old, ...cert, covered_hosts: sameFiles ? (old.covered_hosts || []) : [], issuer: sameFiles ? old.issuer : null };
}
if ($("certificate-default").checked) next.tls.default_certificate = cert.id;
else if (next.tls.default_certificate === cert.id) delete next.tls.default_certificate;
if (await saveSection("tls", next.tls)) {
form.reset(); syncCertificateFileSource(); window.rustProxyCertificates?.close();
}
});
} catch (error) { toast(error.message, true); }
});
$("reload-certificates").addEventListener("click", async () => {
if (!envelope || busy) return;
try {
busy = true;
const result = await api("/api/certificates/reload", { method: "POST", body: "{}" });
await refreshCertificateInventory();
renderCertificates();
toast(`${t("reloadCertificates")}: ${result.reloaded ? "OK" : "-"}`);
if (result.administration_restart_required) toast(t("certificateAdminRestartRequired"), true);
} catch (error) { toast(error.message, true); }
finally { busy = false; }
});
$("reset-certificate").addEventListener("click", () => { $("certificate-form").reset(); $("certificate-file-source").value = "managed"; syncCertificateFileSource(); });
syncCertificateFileSource();
let systemSamples = [], connectionOpenSamples = [], connectionExchangeSamples = [], cacheMemorySamples = [], cacheTransientSamples = [], cacheFillSamples = [], cacheColdQueueSamples = [], cacheColdIoSamples = [], cacheColdStorageSamples = [], cacheHitSamples = [], cacheMissSamples = [], cacheBypassSamples = [], lastCacheCounters = null, lastCacheOutcomeRates = null,
processCpuSamples = [], processRssSamples = [], processFdSamples = [], processThreadSamples = [], networkRxSamples = [], networkTxSamples = [], responseLatencySamples = [], networkInterfaceSamples = new Map(), settingsDirty = new Set();
const hiddenNetworkInterfaces = (() => {
try {
const parsed = JSON.parse(localStorage.getItem("rp-hidden-network-interfaces") || "[]");
return new Set(Array.isArray(parsed) ? parsed.filter(value => typeof value === "string") : []);
} catch { return new Set(); }
})();
function saveHiddenNetworkInterfaces() {
try { localStorage.setItem("rp-hidden-network-interfaces", JSON.stringify([...hiddenNetworkInterfaces].sort())); } catch { }
}
function syncSettingsDirtyIndicators() {
const dirtyTabs = new Set();
for (const id of settingsDirty) {
const page = $(id)?.closest?.("[data-settings-page]"); if (page?.dataset.settingsPage) dirtyTabs.add(page.dataset.settingsPage);
}
document.querySelectorAll("[data-settings-tab]").forEach(button => {
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?.();
}
function setSettingsDirty(id, dirty = true) { if (dirty) settingsDirty.add(id); else settingsDirty.delete(id); syncSettingsDirtyIndicators(); }
function clearSettingsDirty() { settingsDirty.clear(); syncSettingsDirtyIndicators(); }
const fmt = (value, digits = 0) => value == null ? t("unavailable") : formatNumber(value, digits);
const fmtBytes = value => value == null ? t("unavailable") : bytes(value);
function setOptionalMetric(id, supported, text) {
const node = $(id); if (!node) return;
const row = node.closest("div"); if (row) row.hidden = !supported;
if (supported) node.textContent = text;
}
function setProcessMeter(id, used, limit) {
const meter = $(id)?.closest("div")?.querySelector(".pr-meter"); if (!meter) return;
const usedNumber = Number(used), limitNumber = Number(limit);
const ok = used != null && limit != null && Number.isFinite(usedNumber) && Number.isFinite(limitNumber) && limitNumber > 0;
meter.hidden = !ok; if (!ok) return;
const percent = Math.max(0, Math.min(100, usedNumber / limitNumber * 100));
const bar = meter.firstElementChild; bar.style.width = `${percent}%`; bar.classList.toggle("is-high", percent >= 85);
}
function renderProcessOverview(d, status, live, systemSample) {
if (!$("po-cpu")) return;
if (systemSample) {
const memory = status.memory_accounting || {};
const platform = [d.platform, d.environment].filter(Boolean).join(" / ");
setOptionalMetric("po-platform", !!d.platform && d.platform !== "Unsupported", platform);
setOptionalMetric("po-threads", d.process_threads != null, fmt(d.process_threads));
setOptionalMetric("po-start", d.process_start_time_seconds != null, d.process_start_time_seconds == null ? "" : formatDateTime(Number(d.process_start_time_seconds) * 1000));
setOptionalMetric("po-uptime", status.uptime_seconds != null, status.uptime_seconds == null ? "" : uptime(status.uptime_seconds));
setOptionalMetric("po-cpu", d.process_cpu_percent != null, `${fmt(d.process_cpu_percent, 1)}%`);
setProcessMeter("po-cpu", d.process_cpu_percent, 100);
setOptionalMetric("po-rss-total", d.process_rss_bytes != null, fmtBytes(d.process_rss_bytes));
setProcessMeter("po-rss-total", d.process_rss_bytes, d.cgroup_memory_max_bytes);
const fds = knownPair(d.open_fds, d.max_fds, value => fmt(value), t("unlimited"));
setOptionalMetric("po-fds", fds != null, fds);
setProcessMeter("po-fds", d.open_fds, d.max_fds);
const cgroupMemory = knownPair(d.cgroup_memory_current_bytes, d.cgroup_memory_max_bytes, value => fmtBytes(value), t("unlimited"));
setOptionalMetric("po-cgroup", cgroupMemory != null, cgroupMemory);
setProcessMeter("po-cgroup", d.cgroup_memory_current_bytes, d.cgroup_memory_max_bytes);
setOptionalMetric("po-rss-anon", d.process_rss_anon_bytes != null, fmtBytes(d.process_rss_anon_bytes));
const rssFile = knownPair(d.process_rss_file_bytes, d.process_rss_shmem_bytes, value => fmtBytes(value));
setOptionalMetric("po-rss-file", rssFile != null, rssFile);
setOptionalMetric("po-non-cache", memory.non_cache_rss_bytes != null, fmtBytes(memory.non_cache_rss_bytes));
const virtualMemory = knownPair(d.process_virtual_memory_bytes, d.process_virtual_memory_max_bytes, value => fmtBytes(value), t("unlimited"));
setOptionalMetric("po-virtual", virtualMemory != null, virtualMemory);
const dataSwap = knownPair(d.process_data_bytes, d.process_swap_bytes, value => fmtBytes(value));
setOptionalMetric("po-data-swap", dataSwap != null, dataSwap);
const split = $("po-rss-split"), anon = Number(d.process_rss_anon_bytes), file = Number(d.process_rss_file_bytes);
const known = d.process_rss_anon_bytes != null && d.process_rss_file_bytes != null && anon + file > 0;
split.hidden = !known;
if (known) { split.firstElementChild.style.width = `${anon / (anon + file) * 100}%`; split.lastElementChild.style.width = `${file / (anon + file) * 100}%`; }
}
$("po-cpu-sparkline").setAttribute("points", sparklinePoints(processCpuSamples));
window.rustProxyChartScale.axes("po-cpu-sparkline", Math.max(1, ...processCpuSamples), "percent",
processCpuSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("po-cpu-chart-value"), live.process_cpu_percent == null ? "" : `${fmt(live.process_cpu_percent, 1)}%`);
$("po-rss-sparkline").setAttribute("points", sparklinePoints(processRssSamples));
window.rustProxyChartScale.axes("po-rss-sparkline", Math.max(1, ...processRssSamples), "bytes",
processRssSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("po-rss-chart-value"), live.process_rss_bytes == null ? "" : fmtBytes(live.process_rss_bytes));
$("po-cpu-sparkline").closest(".mini-live-chart").hidden = live.process_cpu_percent == null;
$("po-rss-sparkline").closest(".mini-live-chart").hidden = live.process_rss_bytes == null;
const openFdsNow = live.open_fds ?? d.open_fds, threadsNow = live.process_threads ?? d.process_threads;
$("po-fd-sparkline").setAttribute("points", sparklinePoints(processFdSamples));
window.rustProxyChartScale.axes("po-fd-sparkline", Math.max(1, ...processFdSamples), "count",
processFdSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("po-fd-chart-value"), openFdsNow == null ? "" : fmt(openFdsNow));
$("po-fd-sparkline").closest(".mini-live-chart").hidden = openFdsNow == null;
$("po-thread-sparkline").setAttribute("points", sparklinePoints(processThreadSamples));
window.rustProxyChartScale.axes("po-thread-sparkline", Math.max(1, ...processThreadSamples), "count",
processThreadSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("po-thread-chart-value"), threadsNow == null ? "" : fmt(threadsNow));
$("po-thread-sparkline").closest(".mini-live-chart").hidden = threadsNow == null;
}
function knownPair(left, right, format, zeroRight = null) {
if (left == null && right == null) return null;
if (left == null) return format(right);
if (right == null) return format(left);
const rightText = right === 0 && zeroRight ? zeroRight : format(right);
return `${format(left)} / ${rightText}`;
}
function occupancyText(used, limit) {
if (used == null) return "-";
const usedNumber = Number(used), limitNumber = Number(limit);
if (!Number.isFinite(limitNumber) || limitNumber <= 0) return fmtBytes(usedNumber);
return `${fmtBytes(usedNumber)} / ${fmtBytes(limitNumber)} · ${fmt(usedNumber / limitNumber * 100, 1)}%`;
}
function sparklinePoints(values, width = 300, height = 60, padding = 5, peakOverride = null) {
const peak = Math.max(1, peakOverride ?? Math.max(0, ...values));
return values.map((value, index) => `${index * width / Math.max(1, values.length - 1)},${height - padding - Math.max(0, value) / peak * (height - padding * 2)}`).join(" ");
}
function svgNode(tag, attrs = {}) {
const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value);
return node;
}
function setChartText(node, value) {
const text = String(value);
const icon = node.querySelector(":scope > svg.ui-icon");
if (icon) {
const last = node.lastChild;
if (last?.nodeType === 3) { if (last.data !== text) last.data = text; }
else node.append(text);
return;
}
if (node.firstChild?.nodeType === 3 && node.firstChild === node.lastChild) {
if (node.firstChild.data !== text) node.firstChild.data = text;
} else if (node.textContent !== text) {
node.textContent = text;
}
}
let latestNetworkInterfaceSnapshot = [];
function renderNetworkInterfaceCharts(interfaces, appendSample) {
const current = Array.isArray(interfaces) ? interfaces.slice().sort((a, b) => String(a.name || "").localeCompare(String(b.name || ""))) : [];
latestNetworkInterfaceSnapshot = current;
const names = new Set(current.map(item => item.name));
for (const name of [...networkInterfaceSamples.keys()]) if (!names.has(name)) networkInterfaceSamples.delete(name);
if (appendSample) {
for (const item of current) {
if (!item?.name) continue;
const history = networkInterfaceSamples.get(item.name) || { rx: [], tx: [] };
const rx = Number(item.rx_bytes_per_second), tx = Number(item.tx_bytes_per_second);
if (Number.isFinite(rx)) { history.rx.push(rx); history.rx = history.rx.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (Number.isFinite(tx)) { history.tx.push(tx); history.tx = history.tx.slice(-window.rustProxyOverviewSamples.getLimit()); }
networkInterfaceSamples.set(item.name, history);
}
}
const target = $("network-interface-charts");
if (!target) return;
const visible = current.filter(item => item?.name && !hiddenNetworkInterfaces.has(item.name));
setChartText($("network-interface-chart-value"), t("networkInterfacesVisibleCount").replace("{visible}", visible.length).replace("{total}", current.length));
const existing = new Map([...target.children].filter(node => node.classList.contains("network-interface-row"))
.map(node => [node.dataset.interfaceName, node]));
const children = [];
if (!current.length) {
const empty = target.querySelector(":scope > .network-interface-empty") || el("p", undefined, "empty network-interface-empty");
empty.textContent = t("networkNoInterfaces");
children.push(empty);
} else {
for (const item of visible) {
const name = item.name;
let row = existing.get(name);
if (!row) {
row = el("div", undefined, "network-interface-row");
row.dataset.interfaceName = name;
const head = el("div", undefined, "mini-live-chart-head network-interface-row-head");
const rate = el("span", undefined, "fine network-interface-rate");
const hide = action(t("hideMetric"), () => {
hiddenNetworkInterfaces.add(name);
saveHiddenNetworkInterfaces();
renderNetworkInterfaceCharts(latestNetworkInterfaceSnapshot, false);
});
hide.classList.add("network-interface-hide");
const actions = el("span", undefined, "network-interface-head-actions");
actions.append(rate, hide);
head.append(el("b", name, "mono"), actions);
const svg = svgNode("svg", { viewBox: "0 0 300 60", preserveAspectRatio: "none", role: "img", "aria-label": `${name} ${t("networkInterfacesHistory")}` });
svg.append(svgNode("path", { class: "chart-grid", d: "M0 15H300 M0 30H300 M0 45H300" }));
svg.append(svgNode("polyline", { class: "diagnostic-line network-rx-line", points: "0,55 300,55" }));
svg.append(svgNode("polyline", { class: "diagnostic-line network-tx-line", points: "0,55 300,55" }));
row.append(head, svg);
}
const history = networkInterfaceSamples.get(name) || { rx: [], tx: [] };
const peak = Math.max(1, ...history.rx, ...history.tx);
setChartText(row.querySelector(".network-interface-rate"), `${t("networkInterfaceRate")}: ${fmtBytes(item.rx_bytes_per_second)} / ${fmtBytes(item.tx_bytes_per_second)}`);
setChartText(row.querySelector(".network-interface-hide"), t("hideMetric"));
row.querySelector(".network-rx-line").setAttribute("points", sparklinePoints(history.rx, 300, 60, 5, peak) || "0,55 300,55");
row.querySelector(".network-tx-line").setAttribute("points", sparklinePoints(history.tx, 300, 60, 5, peak) || "0,55 300,55");
const chart = row.querySelector("svg:not(.ui-icon)");
window.rustProxyChartScale.axes(chart, peak, "bytes/s", history.rx.length,
{ top: 5 / 60, bottom: 55 / 60 });
chart.setAttribute("aria-label", `${name} ${t("networkInterfacesHistory")}`);
children.push(row);
}
const hidden = current.filter(item => item?.name && hiddenNetworkInterfaces.has(item.name));
if (hidden.length) {
const shelf = target.querySelector(":scope > .network-interface-hidden") || el("div", undefined, "network-interface-hidden");
const previous = [...shelf.querySelectorAll("button[data-interface-name]")].map(node => node.dataset.interfaceName);
const changed = previous.length !== hidden.length || previous.some((name, i) => name !== hidden[i].name);
if (changed) {
shelf.replaceChildren(el("span", t("hiddenInterfaces"), "fine"));
for (const item of hidden) {
const show = action(`${t("showMetric")} ${item.name}`, () => {
hiddenNetworkInterfaces.delete(item.name);
saveHiddenNetworkInterfaces();
renderNetworkInterfaceCharts(latestNetworkInterfaceSnapshot, false);
});
show.dataset.interfaceName = item.name;
shelf.append(show);
}
} else {
setChartText(shelf.querySelector(".fine"), t("hiddenInterfaces"));
for (const button of shelf.querySelectorAll("button[data-interface-name]")) setChartText(button, `${t("showMetric")} ${button.dataset.interfaceName}`);
}
children.push(shelf);
} else if (!visible.length) {
const empty = target.querySelector(":scope > .network-interface-empty") || el("p", undefined, "empty network-interface-empty");
empty.textContent = t("networkNoVisibleInterfaces");
children.push(empty);
}
}
if (children.length !== target.children.length || children.some((node, index) => node !== target.children[index])) {
target.replaceChildren(...children);
if (document.documentElement.dataset.chartAxes === "true" || document.documentElement.dataset.chartTooltips === "true") window.rustProxyChartScale.refreshAxes();
}
}
function cacheOutcomeMix(outcomes) {
const counts = [outcomes?.hits, outcomes?.misses, outcomes?.bypasses, outcomes?.other];
if (counts.some(value => !Number.isSafeInteger(value) || value < 0)) return null;
const requests = counts.reduce((sum, value) => sum + value, 0);
if (!Number.isSafeInteger(requests)) return null;
return { counts, percentages: counts.map(value => requests ? value / requests * 100 : 0), requests };
}
function fitCacheMixLabels() {
const bar = $("cache-mix-bar");
if (!bar) return;
bar.querySelectorAll(":scope > span").forEach(segment => {
segment.classList.remove("is-tight");
segment.classList.toggle("is-tight", segment.textContent !== "" && segment.scrollWidth > segment.clientWidth);
});
if (!bar.dataset.fitObserved && typeof ResizeObserver === "function") {
bar.dataset.fitObserved = "1";
new ResizeObserver(() => fitCacheMixLabels()).observe(bar);
}
}
function renderCacheMix(mix, totalRequests) {
const names = ["hit", "miss", "bypass", "other"];
const unavailable = t(totalRequests === 0 ? "cacheMixWaiting" : "cacheMixInvalid");
names.forEach((name, i) => {
const pct = mix ? mix.percentages[i] : 0;
const segment = $(`cache-mix-${name}`);
segment.style.width = `${pct}%`;
segment.textContent = mix && pct > 0 ? `${fmt(pct, pct < 10 ? 1 : 0)}%` : "";
const detail = mix ? `${name.toUpperCase()}: ${fmt(mix.counts[i])} (${fmt(pct, 1)}%)` : "";
$(`cache-mix-${name}-count`).textContent = mix ? fmt(mix.counts[i]) : "-";
segment.title = detail; $(`cache-mix-${name}-key`).title = detail;
});
fitCacheMixLabels();
$("cache-mix-headline").textContent = mix ? `${fmt(mix.percentages[0], 1)}% HIT` : "-";
const caption = $("cache-mix-caption");
const validTotal = Number.isSafeInteger(totalRequests) && totalRequests >= 0;
const total = validTotal ? fmt(totalRequests) : "-";
const totalLabel = validTotal
? t("cacheMixSample").replace("{count}", total)
: t("cacheMixInvalid");
caption.textContent = total;
caption.setAttribute("title", totalLabel);
caption.setAttribute("aria-label", totalLabel);
$("cache-mix-bar").setAttribute("aria-label", mix
? t("cacheMixAria").replace("{hit}", fmt(mix.counts[0]))
.replace("{miss}", fmt(mix.counts[1]))
.replace("{bypass}", fmt(mix.counts[2]))
.replace("{other}", fmt(mix.counts[3]))
: unavailable);
}
function renderDiagnostics(status, appendSample = true, systemSample = appendSample) {
const d = status.system || {}, live = status.live_system || d, c = status.cache || {}, m = status.metrics || {};
$("metric-h3").textContent = fmt(m.http3_requests);
$("metric-h3-active").textContent = fmt(m.http3_active_connections || 0);
const outcomes = m.cache_request_outcomes;
const cacheHits = outcomes?.hits ?? null, cacheMisses = outcomes?.misses ?? null;
const cacheEvents = cacheHits !== null && cacheMisses !== null ? cacheHits + cacheMisses : 0;
$("metric-cache-ratio").textContent = cacheEvents > 0 ? `${fmt(cacheHits / cacheEvents * 100, 1)}%` : "-";
window.rustProxyExtraOverview?.donut?.("cache-ratio", cacheHits, cacheMisses);
const mix = cacheOutcomeMix(outcomes);
renderCacheMix(mix?.requests ? mix : null, mix?.requests ?? null);
if (systemSample) {
if (d.process_rss_bytes != null) $("metric-rss").textContent = fmtBytes(d.process_rss_bytes);
$("process-summary").hidden = d.process_threads == null;
if (d.process_threads != null) $("process-summary").textContent = `${fmt(d.process_threads)} ${t("threads")}`;
setOptionalMetric("system-cpu", d.cpu_percent != null, `${fmt(d.cpu_percent, 1)}%`);
const systemMemory = knownPair(d.memory_used_bytes, d.memory_total_bytes, value => fmtBytes(value));
setOptionalMetric("system-memory", systemMemory != null, systemMemory);
const ramMeter = $("memory-meter"), ramFill = $("memory-meter-fill");
ramMeter.hidden = systemMemory == null;
const ramUsed = Number(d.memory_used_bytes), ramTotal = Number(d.memory_total_bytes);
const ramPercent = d.memory_used_bytes != null && d.memory_total_bytes != null &&
Number.isFinite(ramUsed) && Number.isFinite(ramTotal) && ramTotal > 0
? Math.max(0, Math.min(100, ramUsed / ramTotal * 100)) : null;
ramFill.style.width = `${ramPercent ?? 0}%`;
if (ramPercent == null) {
ramMeter.removeAttribute("aria-valuenow");
ramMeter.setAttribute("aria-valuetext", "-");
} else {
ramMeter.setAttribute("aria-valuenow", String(ramPercent));
ramMeter.setAttribute("aria-valuetext", `${fmt(ramPercent, 1)}%`);
}
const systemSwap = knownPair(d.system_swap_used_bytes, d.system_swap_total_bytes, value => fmtBytes(value));
setOptionalMetric("system-swap", systemSwap != null, systemSwap);
const loadSupported = Array.isArray(d.load_average) && d.load_average.length > 0;
setOptionalMetric("system-load", loadSupported, loadSupported ? d.load_average.map(n => fmt(n, 2)).join(" / ") : "");
const systemUptime = $("system-uptime"), systemUptimeMeta = systemUptime?.closest(".system-uptime-meta");
if (systemUptimeMeta) systemUptimeMeta.hidden = d.system_uptime_seconds == null;
if (systemUptime && d.system_uptime_seconds != null) systemUptime.textContent = uptime(d.system_uptime_seconds);
}
$("system-chart").hidden = live.cpu_percent == null; if (appendSample && live.cpu_percent != null) { systemSamples.push(Number(live.cpu_percent)); systemSamples = systemSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
$("system-sparkline").setAttribute("points", systemSamples.map((n, i) => `${i * 300 / Math.max(1, systemSamples.length - 1)},${95 - Math.max(0, Math.min(100, n)) * .9}`).join(" "));
window.rustProxyChartScale.axes("system-chart", 100, "percent", systemSamples.length,
{ top: 5 / 100, bottom: 95 / 100 });
$("cache-state").textContent = t(envelope?.config.cache?.enabled ? "enabled" : "notEnabled");
$("cache-counters").textContent = [outcomes?.hits, outcomes?.misses, outcomes?.bypasses].map(n => n == null ? "-" : fmt(n)).join(" / ");
$("cache-objects").textContent = `${fmt(c.entries)} / ${fmtBytes(c.resident_bytes)}`;
$("cache-memory-breakdown").textContent = `${fmtBytes(c.resident_bytes)} / ${fmtBytes(c.transient_bytes)}`;
$("cache-transient-breakdown").textContent = `${fmtBytes(c.fill_bytes_active)} / ${fmtBytes(c.cold_queue_bytes)} / ${fmtBytes((Number(c.cold_write_bytes_active) || 0) + (Number(c.cold_read_bytes_active) || 0))}`;
const coldStorage = knownPair(c.cold_bytes, c.cold_limit_bytes, value => fmtBytes(value));
const coldObjects = knownPair(c.cold_entries, c.cold_limit_entries, value => fmt(value));
$("cache-cold-storage").textContent = envelope?.config.cache?.cold_enabled === true
? `${coldStorage ?? "-"}${coldObjects == null ? "" : ` · ${coldObjects} ${t("cacheColdStorageObjects")}`}`
: t("notEnabled");
$("cache-evictions").textContent = `${fmt(c.evictions)} / ${fmt(c.expired)}`;
if (appendSample) {
if (c.resident_bytes != null) { cacheMemorySamples.push(Number(c.resident_bytes)); cacheMemorySamples = cacheMemorySamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (c.transient_bytes != null) { cacheTransientSamples.push(Number(c.transient_bytes)); cacheTransientSamples = cacheTransientSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (c.fill_bytes_active != null) { cacheFillSamples.push(Number(c.fill_bytes_active)); cacheFillSamples = cacheFillSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (c.cold_queue_bytes != null) { cacheColdQueueSamples.push(Number(c.cold_queue_bytes)); cacheColdQueueSamples = cacheColdQueueSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
const coldIoBytes = (Number(c.cold_write_bytes_active) || 0) + (Number(c.cold_read_bytes_active) || 0);
if (c.cold_write_bytes_active != null || c.cold_read_bytes_active != null) { cacheColdIoSamples.push(coldIoBytes); cacheColdIoSamples = cacheColdIoSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (c.cold_bytes != null) { cacheColdStorageSamples.push(Number(c.cold_bytes)); cacheColdStorageSamples = cacheColdStorageSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
const currentCounters = [c.hits, c.misses, c.bypasses].map(Number);
if (currentCounters.every(Number.isFinite)) {
const delta = rustProxyRateSampling.difference(lastCacheCounters, currentCounters, performance.now(), rustProxyRateSampling.cadence("overview_seconds"));
const values = delta.deltas || lastCacheOutcomeRates || (!lastCacheCounters ? [0, 0, 0] : null);
if (values) {
cacheHitSamples.push(values[0]); cacheMissSamples.push(values[1]); cacheBypassSamples.push(values[2]);
cacheHitSamples = cacheHitSamples.slice(-window.rustProxyOverviewSamples.getLimit()); cacheMissSamples = cacheMissSamples.slice(-window.rustProxyOverviewSamples.getLimit()); cacheBypassSamples = cacheBypassSamples.slice(-window.rustProxyOverviewSamples.getLimit());
lastCacheOutcomeRates = [...values];
}
lastCacheCounters = delta.next;
}
}
if (appendSample) {
if (live.process_cpu_percent != null) { processCpuSamples.push(Number(live.process_cpu_percent)); processCpuSamples = processCpuSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (live.process_rss_bytes != null) { processRssSamples.push(Number(live.process_rss_bytes)); processRssSamples = processRssSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
const openFds = live.open_fds ?? d.open_fds, threadCount = live.process_threads ?? d.process_threads;
if (openFds != null) { processFdSamples.push(Number(openFds)); processFdSamples = processFdSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
if (threadCount != null) { processThreadSamples.push(Number(threadCount)); processThreadSamples = processThreadSamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
}
const cacheOutcomePeak = Math.max(1, ...cacheHitSamples, ...cacheMissSamples, ...cacheBypassSamples);
$("cache-hit-sparkline").setAttribute("points", sparklinePoints(cacheHitSamples, 300, 60, 5, cacheOutcomePeak));
$("cache-miss-sparkline").setAttribute("points", sparklinePoints(cacheMissSamples, 300, 60, 5, cacheOutcomePeak));
$("cache-bypass-sparkline").setAttribute("points", sparklinePoints(cacheBypassSamples, 300, 60, 5, cacheOutcomePeak));
window.rustProxyChartScale.axes("cache-hit-sparkline", cacheOutcomePeak, "count", cacheHitSamples.length,
{ top: 5 / 60, bottom: 55 / 60 });
const latestCacheDelta = [cacheHitSamples.at(-1), cacheMissSamples.at(-1), cacheBypassSamples.at(-1)];
setChartText($("cache-outcome-chart-value"), latestCacheDelta.every(value => value != null) ? latestCacheDelta.map(value => fmt(value)).join(" / ") : "-");
const hotLimit = Number(c.hot_limit_bytes), hotPeak = Number.isFinite(hotLimit) && hotLimit > 0 ? Math.max(hotLimit, ...cacheMemorySamples) : null;
$("cache-memory-sparkline").setAttribute("points", sparklinePoints(cacheMemorySamples, 300, 60, 5, hotPeak));
window.rustProxyChartScale.axes("cache-memory-sparkline", Math.max(1, hotPeak ?? Math.max(0, ...cacheMemorySamples)),
"bytes", cacheMemorySamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("cache-chart-value"), occupancyText(c.resident_bytes, c.hot_limit_bytes));
const transientLimit = Number(c.transient_limit_bytes);
const transientPeak = Number.isFinite(transientLimit) && transientLimit > 0
? Math.max(transientLimit, ...cacheTransientSamples, ...cacheFillSamples, ...cacheColdQueueSamples, ...cacheColdIoSamples)
: Math.max(1, ...cacheTransientSamples, ...cacheFillSamples, ...cacheColdQueueSamples, ...cacheColdIoSamples);
$("cache-transient-sparkline").setAttribute("points", sparklinePoints(cacheTransientSamples, 300, 60, 5, transientPeak));
$("cache-fill-sparkline").setAttribute("points", sparklinePoints(cacheFillSamples, 300, 60, 5, transientPeak));
$("cache-queue-sparkline").setAttribute("points", sparklinePoints(cacheColdQueueSamples, 300, 60, 5, transientPeak));
$("cache-io-sparkline").setAttribute("points", sparklinePoints(cacheColdIoSamples, 300, 60, 5, transientPeak));
window.rustProxyChartScale.axes("cache-transient-sparkline", transientPeak, "bytes", cacheTransientSamples.length,
{ top: 5 / 60, bottom: 55 / 60 });
setChartText($("cache-transient-chart-value"), occupancyText(c.transient_bytes, c.transient_limit_bytes));
const coldEnabled = envelope?.config.cache?.cold_enabled === true;
const coldLimit = Number(c.cold_limit_bytes), coldPeak = Number.isFinite(coldLimit) && coldLimit > 0 ? Math.max(coldLimit, ...cacheColdStorageSamples) : null;
$("cache-cold-sparkline").setAttribute("points", sparklinePoints(cacheColdStorageSamples, 300, 60, 5, coldPeak));
window.rustProxyChartScale.axes("cache-cold-sparkline", Math.max(1, coldPeak ?? Math.max(0, ...cacheColdStorageSamples)),
"bytes", cacheColdStorageSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("cache-cold-chart-value"), coldEnabled ? occupancyText(c.cold_bytes, c.cold_limit_bytes) : t("notEnabled"));
if (systemSample) {
const processPlatform = [d.platform, d.environment].filter(Boolean).join(" / ");
setOptionalMetric("process-platform", !!d.platform && d.platform !== "Unsupported", processPlatform);
setOptionalMetric("process-cpu", d.process_cpu_percent != null, `${fmt(d.process_cpu_percent, 1)}%`);
const fds = knownPair(d.open_fds, d.max_fds, value => fmt(value), t("unlimited"));
setOptionalMetric("process-fds", fds != null, fds);
setOptionalMetric("process-threads", d.process_threads != null, fmt(d.process_threads));
const virtualMemory = knownPair(d.process_virtual_memory_bytes, d.process_virtual_memory_max_bytes, value => fmtBytes(value), t("unlimited"));
setOptionalMetric("process-virtual-memory", virtualMemory != null, virtualMemory);
setOptionalMetric("process-start-time", d.process_start_time_seconds != null, d.process_start_time_seconds == null ? "" : formatDateTime(Number(d.process_start_time_seconds) * 1000));
setOptionalMetric("process-uptime", status.uptime_seconds != null, status.uptime_seconds == null ? "" : uptime(status.uptime_seconds));
setOptionalMetric("process-rss-total", d.process_rss_bytes != null, fmtBytes(d.process_rss_bytes));
const memory = status.memory_accounting || {};
const hotMemory = knownPair(memory.cache_hot_bytes, memory.cache_hot_limit_bytes, value => fmtBytes(value));
const transientMemory = knownPair(memory.cache_transient_bytes, memory.cache_transient_limit_bytes, value => fmtBytes(value));
const transformMemory = knownPair(memory.transform_reserved_bytes, memory.transform_budget_bytes, value => fmtBytes(value));
const transformInflight = knownPair(memory.transform_inflight, memory.transform_max_inflight, value => fmt(value));
setOptionalMetric("memory-cache-hot", hotMemory != null, hotMemory);
setOptionalMetric("memory-cache-transient", transientMemory != null, transientMemory);
setOptionalMetric("memory-transform", transformMemory != null, transformMemory);
setOptionalMetric("memory-transform-inflight", transformInflight != null, transformInflight);
setOptionalMetric("memory-non-cache-rss", memory.non_cache_rss_bytes != null, fmtBytes(memory.non_cache_rss_bytes));
setOptionalMetric("process-rss-anon", d.process_rss_anon_bytes != null, fmtBytes(d.process_rss_anon_bytes));
const rssFile = knownPair(d.process_rss_file_bytes, d.process_rss_shmem_bytes, value => fmtBytes(value));
setOptionalMetric("process-rss-file", rssFile != null, rssFile);
const dataSwap = knownPair(d.process_data_bytes, d.process_swap_bytes, value => fmtBytes(value));
setOptionalMetric("process-data-swap", dataSwap != null, dataSwap);
const cgroupMemory = knownPair(d.cgroup_memory_current_bytes, d.cgroup_memory_max_bytes, value => fmtBytes(value), t("unlimited"));
setOptionalMetric("cgroup-memory", cgroupMemory != null, cgroupMemory);
}
$("process-cpu-sparkline").setAttribute("points", sparklinePoints(processCpuSamples));
window.rustProxyChartScale.axes("process-cpu-sparkline", Math.max(1, ...processCpuSamples), "percent",
processCpuSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("process-cpu-chart-value"), live.process_cpu_percent == null ? "" : `${fmt(live.process_cpu_percent, 1)}%`);
$("process-rss-sparkline").setAttribute("points", sparklinePoints(processRssSamples));
window.rustProxyChartScale.axes("process-rss-sparkline", Math.max(1, ...processRssSamples), "bytes",
processRssSamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("process-rss-chart-value"), live.process_rss_bytes == null ? "" : fmtBytes(live.process_rss_bytes));
$("process-cpu-sparkline").closest(".mini-live-chart").hidden = live.process_cpu_percent == null;
$("process-rss-sparkline").closest(".mini-live-chart").hidden = live.process_rss_bytes == null;
renderProcessOverview(d, status, live, systemSample);
window.rustProxyMemoryBreakdown?.render(status, appendSample);
window.rustProxyOverviewRows?.schedule();
window.rustProxyOverviewRows?.dataReady?.();
updateCacheMemorySizing();
const networkRateSupported = live.network_rx_bytes_per_second != null && live.network_tx_bytes_per_second != null;
if (systemSample) setOptionalMetric("system-network", d.network_rx_bytes_per_second != null && d.network_tx_bytes_per_second != null, `${fmtBytes(d.network_rx_bytes_per_second)} / ${fmtBytes(d.network_tx_bytes_per_second)}`);
setOptionalMetric("mean-latency", m.mean_duration_ms != null, m.mean_duration_ms == null ? "" : `${fmt(m.mean_duration_ms, 2)} ms`);
if (appendSample) {
if (networkRateSupported) {
networkRxSamples.push(Number(live.network_rx_bytes_per_second)); networkTxSamples.push(Number(live.network_tx_bytes_per_second));
networkRxSamples = networkRxSamples.slice(-window.rustProxyOverviewSamples.getLimit()); networkTxSamples = networkTxSamples.slice(-window.rustProxyOverviewSamples.getLimit());
}
if (m.mean_duration_ms != null) { responseLatencySamples.push(Number(m.mean_duration_ms)); responseLatencySamples = responseLatencySamples.slice(-window.rustProxyOverviewSamples.getLimit()); }
}
const networkPeak = Math.max(1, ...networkRxSamples, ...networkTxSamples);
$("network-rx-sparkline").setAttribute("points", sparklinePoints(networkRxSamples, 300, 60, 5, networkPeak));
$("network-tx-sparkline").setAttribute("points", sparklinePoints(networkTxSamples, 300, 60, 5, networkPeak));
window.rustProxyChartScale.axes("network-rx-sparkline", networkPeak, "bytes/s", networkRxSamples.length,
{ top: 5 / 60, bottom: 55 / 60 });
setChartText($("network-chart-value"), networkRateSupported ? `${fmtBytes(live.network_rx_bytes_per_second)} / ${fmtBytes(live.network_tx_bytes_per_second)}` : "");
$("network-rx-sparkline").closest(".mini-live-chart").hidden = !networkRateSupported;
renderNetworkInterfaceCharts(live.network_interfaces || [], appendSample);
$("latency-sparkline").setAttribute("points", sparklinePoints(responseLatencySamples));
window.rustProxyChartScale.axes("latency-sparkline", Math.max(1, ...responseLatencySamples), "ms",
responseLatencySamples.length, { top: 5 / 60, bottom: 55 / 60 });
setChartText($("latency-chart-value"), m.mean_duration_ms == null ? "" : `${fmt(m.mean_duration_ms, 2)} ms`);
$("latency-sparkline").closest(".mini-live-chart").hidden = m.mean_duration_ms == null;
$("compression-counters").textContent = [m.compression_gzip, m.compression_br, m.compression_zstd, m.compression_deflate].map(n => fmt(n)).join(" / ");
const age = d.sampled_at_ms ? Math.max(0, Math.floor((Date.now() - d.sampled_at_ms) / 1000)) : null;
$("system-sample-age").hidden = age == null;
if (age != null) $("system-sample-age").textContent = `${fmt(age)} s`;
$("system-sample-age").classList.toggle("status-error", age != null && age > 10);
if ($("po-sample-age")) { $("po-sample-age").hidden = age == null; if (age != null) $("po-sample-age").textContent = `${fmt(age)} s`; $("po-sample-age").classList.toggle("status-error", age != null && age > 10); }
const l = status.listeners || {};
$("listener-pending").hidden = !l.restart_required;
$("listener-pending").textContent = t("restartPending");
const activeListeners = $("listener-active"), listenerItems = el("div", undefined, "listener-active-items");
let endpoints = Array.isArray(l.active_endpoints) ? l.active_endpoints : [];
if (!endpoints.length) {
endpoints = [];
if (status.proxy_listen) endpoints.push({ tls: false, address: status.proxy_listen, http3: false });
if (status.tls_listen) endpoints.push({ tls: true, address: status.tls_listen, http3: false });
}
for (const endpoint of endpoints) {
const item = el("div", undefined, "listener-active-item");
item.append(el("strong", endpoint.tls ? "HTTPS" : "HTTP", "listener-active-protocol"), el("code", endpoint.address || "-", "listener-active-address"));
const protocols = ["H1"];
if (endpoint.tls) {
if (endpoint.http2) protocols.push("H2");
if (endpoint.http3) protocols.push("H3/UDP");
} else if (endpoint.h2c) {
protocols.push("H2C");
}
for (const protocol of protocols) item.append(el("span", protocol, "listener-active-feature"));
listenerItems.append(item);
}
if (!endpoints.length) listenerItems.append(el("span", t("notEnabled"), "fine"));
activeListeners.replaceChildren(el("strong", t("activeListeners"), "listener-active-title"), listenerItems);
}
function renderHeaderRules(direction, rules) {
const target = $(`${direction}-header-rules`); target.replaceChildren();
for (const rule of rules) appendHeaderRule(direction, rule, false);
}
function appendHeaderRule(direction, rule = { op: "set", name: "", value: "" }, mark = true) {
const target = $(`${direction}-header-rules`); if (target.children.length >= 32) { toast(t("headerLimit"), true); return; }
const row = el("div", undefined, "header-rule");
const op = el("select"); op.className = "header-op"; op.setAttribute("aria-label", t("headerOperation"));
for (const value of ["set", "append", "remove"]) { const option = el("option", t(`header_${value}`)); option.value = value; op.append(option); } op.value = rule.op;
const name = el("input"); name.className = "header-name"; name.value = rule.name; name.required = true; name.maxLength = 128; name.placeholder = t("headerName"); name.setAttribute("aria-label", t("headerName")); name.autocomplete = "off"; name.spellcheck = false;
const value = el("input"); value.className = "header-value"; value.value = rule.value ?? ""; value.maxLength = 8192; value.placeholder = t("headerValue"); value.setAttribute("aria-label", t("headerValue")); value.autocomplete = "off"; value.spellcheck = false;
function sync() { value.disabled = op.value === "remove"; } sync(); op.addEventListener("change", sync);
const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("headers-form"); });
row.append(op, name, value, remove); target.append(row); if (mark) setSettingsDirty("headers-form");
}
function collectHeaderRules(direction) {
return [...$(`${direction}-header-rules`).children].map(row => {
const op = row.querySelector(".header-op").value, name = row.querySelector(".header-name").value.trim(), value = row.querySelector(".header-value").value;
return op === "remove" ? { op, name } : { op, name, value };
});
}
window.rustProxyOverviewSamples.onChange(() => {
for (const history of [systemSamples, cacheMemorySamples, cacheTransientSamples,
cacheFillSamples, cacheColdQueueSamples, cacheColdIoSamples, cacheColdStorageSamples,
cacheHitSamples, cacheMissSamples, cacheBypassSamples, processCpuSamples,
processRssSamples, networkRxSamples, networkTxSamples, responseLatencySamples]) {
window.rustProxyOverviewSamples.trim(history);
}
for (const history of networkInterfaceSamples.values()) {
window.rustProxyOverviewSamples.trim(history.rx);
window.rustProxyOverviewSamples.trim(history.tx);
}
if (typeof latestStatus !== "undefined" && latestStatus && currentPanel === "overview") {
renderDiagnostics(latestStatus, false, false);
}
});