223 lines
16 KiB
JavaScript
223 lines
16 KiB
JavaScript
"use strict";
|
|
(() => {
|
|
let job = null, pending = false, loading = false, renewalLogs = {}, resetIssueFormJob = null, runtimeAvailable = true;
|
|
const picker = $("certificate-provider");
|
|
const secrets = ["acme-secret", "acme-cf-token", "acme-ovh-application-key", "acme-ovh-application-secret", "acme-ovh-consumer-key"];
|
|
const tabs = [...document.querySelectorAll("[data-certificate-tab]")];
|
|
const requested = typeof location !== "undefined" && location.pathname === "/tls" ? new URLSearchParams(location.search).get("tab") : null;
|
|
let activeTab = tabs.some(button => button.dataset.certificateTab === requested) ? requested : "installed";
|
|
|
|
function syncLocation() {
|
|
if (typeof location === "undefined" || location.pathname !== "/tls" || !["http:", "https:"].includes(location.protocol)) return;
|
|
const url = new URL(location.href); url.search = ""; url.searchParams.set("tab", activeTab);
|
|
history.replaceState({ ...(history.state || {}), panel: "tls", certificateTab: activeTab }, "", `${url.pathname}${url.search}${url.hash}`);
|
|
}
|
|
function selectTab(name, focus = false, persist = true) {
|
|
if (!tabs.some(button => button.dataset.certificateTab === name)) return;
|
|
activeTab = name;
|
|
for (const button of tabs) {
|
|
const selected = button.dataset.certificateTab === name;
|
|
button.setAttribute("aria-selected", String(selected)); button.tabIndex = selected ? 0 : -1;
|
|
if (selected && focus) button.focus();
|
|
}
|
|
document.querySelectorAll("[data-certificate-page]").forEach(page => { page.hidden = page.dataset.certificatePage !== name; });
|
|
if (persist) syncLocation();
|
|
}
|
|
for (const button of tabs) {
|
|
button.addEventListener("click", () => selectTab(button.dataset.certificateTab));
|
|
button.addEventListener("keydown", event => {
|
|
const index = tabs.indexOf(button); let next;
|
|
if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % tabs.length;
|
|
else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + tabs.length - 1) % tabs.length;
|
|
else if (event.key === "Home") next = 0;
|
|
else if (event.key === "End") next = tabs.length - 1;
|
|
else return;
|
|
event.preventDefault(); selectTab(tabs[next].dataset.certificateTab, true);
|
|
});
|
|
}
|
|
|
|
const clearSecrets = () => { for (const id of secrets) $(id).value = ""; };
|
|
function resetIssueForm() {
|
|
$("acme-form").reset();
|
|
$("acme-environment").value = "production";
|
|
$("acme-confirm-production").required = true;
|
|
clearSecrets();
|
|
syncProvider();
|
|
}
|
|
function syncSubmitState() {
|
|
$("acme-submit").disabled = pending || job?.status === "running" || !runtimeAvailable;
|
|
}
|
|
function syncProvider() {
|
|
const provider = picker.value, acme = !["import", "existing"].includes(provider);
|
|
$("certificate-acme-editor").hidden = !acme;
|
|
$("certificate-upload-form").hidden = provider !== "import";
|
|
$("certificate-advanced").hidden = provider !== "existing";
|
|
$("certificate-provider-hint").textContent = t(`providerHint_${provider}`);
|
|
for (const node of document.querySelectorAll("[data-acme-provider]")) {
|
|
const visible = acme && (node.dataset.acmeProvider === provider || (node.dataset.acmeProvider === "dns" && provider !== "http01"));
|
|
node.hidden = !visible;
|
|
for (const input of node.querySelectorAll("input,select")) input.disabled = !visible;
|
|
}
|
|
$("acme-domains").placeholder = provider === "http01" ? "example.org, www.example.org" : "example.org, *.example.org";
|
|
syncSubmitState();
|
|
}
|
|
function open(provider = "http01") {
|
|
selectTab("generate"); picker.value = provider;
|
|
if (provider !== "existing") { $("acme-environment").value = "production"; $("acme-confirm-production").required = true; }
|
|
syncProvider();
|
|
}
|
|
function close() { clearSecrets(); selectTab("installed"); }
|
|
picker.addEventListener("change", () => { clearSecrets(); syncProvider(); });
|
|
$("certificate-new").addEventListener("click", () => open());
|
|
|
|
const stateKey = value => ({ running: "certificateStateRunning", ready: "certificateStateReady", complete: "certificateStateComplete", failed: "certificateStateFailed" }[value?.status] || "certificateStateIdle");
|
|
function renderRuntime(value) {
|
|
const status = value?.status || "checking", mode = value?.mode || "none";
|
|
runtimeAvailable = status !== "unavailable";
|
|
$("acme-runtime-card").dataset.state = status;
|
|
$("acme-runtime-message").textContent = t(value?.message || "acme.runtime_checking");
|
|
$("acme-runtime-state").textContent = t(status === "unavailable" ? "certificateRuntimeUnavailable" : status === "ready" && mode === "managed" ? "certificateRuntimeManaged" : status === "ready" && mode === "system" ? "certificateRuntimeSystem" : "certificateRuntimePreparing");
|
|
const path = value?.managed_directory;
|
|
$("acme-runtime-path").hidden = !path;
|
|
$("acme-runtime-path").textContent = path ? `${t("certificateRuntimePath")}: ${path}` : "";
|
|
const availability = flag => t(flag === true ? "runtimeAvailable" : flag === false ? "runtimeUnavailable" : "certificateRuntimePreparing");
|
|
$("acme-runtime-components").textContent = `${t("runtimePython")}: ${availability(value?.python)} · ${t("runtimePip")}: ${availability(value?.pip)} · ${t("runtimeCertbot")}: ${availability(value?.certbot)}`;
|
|
syncSubmitState();
|
|
}
|
|
function renderOperation(cardId, messageId, stateId, logId, value, idleKey) {
|
|
const card = $(cardId), message = $(messageId), state = $(stateId), log = $(logId);
|
|
card.dataset.state = value?.status || "idle";
|
|
state.textContent = t(stateKey(value));
|
|
if (!value) message.textContent = t(idleKey);
|
|
else message.textContent = `${value.certificate_id} · ${value.provider} / ${value.environment} · ${t(value.message)}`;
|
|
const showLog = value?.status === "failed" && !!value.log_directory;
|
|
log.hidden = !showLog;
|
|
log.textContent = showLog ? `${t("certbotLogs")}: ${value.log_directory}` : "";
|
|
}
|
|
function render(value) {
|
|
job = value;
|
|
if (resetIssueFormJob && value?.kind === "issue" && value.id === resetIssueFormJob) {
|
|
if (value.status === "ready") { resetIssueForm(); resetIssueFormJob = null; }
|
|
else if (value.status === "failed") resetIssueFormJob = null;
|
|
}
|
|
syncSubmitState();
|
|
const issue = value?.kind === "issue" ? value : null;
|
|
const renewal = value?.kind?.startsWith("renewal") ? value : null;
|
|
renderOperation("acme-issue-status-card", "acme-job", "acme-issue-state", "acme-log-path", issue, "acmeIdle");
|
|
renderOperation("acme-renewal-status-card", "acme-renewal-job", "acme-renewal-state", "acme-renewal-log", renewal, "certificateNoRenewalOperation");
|
|
const installed = issue?.certificate && envelope?.config.tls?.certificates?.some(c => c.id === issue.certificate.id && c.cert_file === issue.certificate.cert_file && c.key_file === issue.certificate.key_file);
|
|
$("acme-import").hidden = issue?.status !== "ready" || !issue.certificate || !!installed;
|
|
}
|
|
function renewalMeta(parent, key, value) {
|
|
const item = el("div", undefined, "renewal-meta-item");
|
|
item.append(el("span", t(key), "small-label"), el("strong", value)); parent.append(item);
|
|
}
|
|
function renderRenewals(values = {}, logs = {}) {
|
|
renewalLogs = logs || {};
|
|
const list = $("renewal-list"); list.replaceChildren();
|
|
const certificates = envelope?.config.tls?.certificates || [];
|
|
const stamp = value => value ? formatDateTime(value * 1000) : "-";
|
|
for (const cert of certificates.filter(c => c.issuer)) {
|
|
const state = values[cert.id], enabled = cert.issuer.auto_renew !== false;
|
|
const entry = el("div", undefined, "renewal-entry"); entry.dataset.state = state?.status || "idle";
|
|
const head = el("div", undefined, "renewal-entry-head"), identity = el("div", undefined, "renewal-entry-identity");
|
|
identity.append(el("strong", cert.id), el("span", `${cert.issuer.provider} / ${cert.issuer.environment}`, "fine"));
|
|
const mode = el("span", t(enabled ? "renewalEnabled" : "renewalDisabled"), "pill"); head.append(identity, mode); entry.append(head);
|
|
const meta = el("div", undefined, "renewal-meta");
|
|
renewalMeta(meta, "renewalLast", stamp(state?.last_checked));
|
|
renewalMeta(meta, "renewalNext", enabled ? stamp(state?.next_check) : "-");
|
|
renewalMeta(meta, "renewalExpires", stamp(state?.not_after));
|
|
entry.append(meta);
|
|
if (state?.message) {
|
|
const note = el("p", t(state.message), `fine renewal-message${state.status === "failed" ? " status-error" : ""}`); entry.append(note);
|
|
if (state.status === "failed" && renewalLogs[cert.id]) entry.append(el("p", `${t("certbotLogs")}: ${renewalLogs[cert.id]}`, "fine certificate-log-path"));
|
|
}
|
|
const controls = el("div", undefined, "renewal-actions");
|
|
const b = (key, handler) => { const node = el("button", t(key), "quiet"); node.type = "button"; node.dataset.action = key; node.addEventListener("click", handler); controls.append(node); return node; };
|
|
b(enabled ? "renewalDisable" : "renewalEnable", async () => {
|
|
if (!envelope) return; const next = structuredClone(envelope.config), target = next.tls.certificates.find(c => c.id === cert.id); if (!target?.issuer) return;
|
|
target.issuer.auto_renew = !enabled; if (await saveSection("tls", next.tls || {})) void refresh();
|
|
});
|
|
for (const [key, dry_run, force] of [["renewalNow", false, false], ["renewalForce", false, true], ["renewalDryRun", true, false]]) {
|
|
const node = b(key, async () => {
|
|
if (force && !(await appConfirm(t("renewalForceConfirm"), { danger: true }))) return;
|
|
node.disabled = true; const epoch = authEpoch;
|
|
try {
|
|
const data = await api("/api/acme/renew", { method: "POST", body: JSON.stringify({ certificate_id: cert.id, dry_run, force }) });
|
|
if (epoch === authEpoch && authenticated) { render(data.job); selectTab("renewal"); toast(t(force ? "acme.renewing_forced" : "acme.renewing")); }
|
|
} catch (error) {
|
|
if (epoch === authEpoch) toast(error.message, true);
|
|
} finally { node.disabled = false; }
|
|
});
|
|
node.disabled = job?.status === "running" || !runtimeAvailable;
|
|
}
|
|
entry.append(controls); list.append(entry);
|
|
}
|
|
if (!list.children.length) list.append(el("p", t("renewalNone"), "empty"));
|
|
}
|
|
|
|
async function loadAcme({ signal, isCurrent }) {
|
|
if (!authenticated || currentPanel !== "tls" || loading) return;
|
|
loading = true;
|
|
const epoch = authEpoch;
|
|
try {
|
|
const data = await api("/api/acme", { signal });
|
|
if (isCurrent() && epoch === authEpoch) { renderRuntime(data.runtime); render(data.job); renderRenewals(data.renewals, data.log_directories); }
|
|
} catch (error) {
|
|
if (error?.name !== "AbortError" && epoch === authEpoch && isCurrent()) {
|
|
toast(error.message, true);
|
|
if (error.status === 401) lock();
|
|
}
|
|
} finally { loading = false; }
|
|
}
|
|
function refresh() { return rustProxyRefresh.manual("acme"); }
|
|
$("acme-environment").addEventListener("change", () => { $("acme-confirm-production").required = $("acme-environment").value === "production"; });
|
|
$("acme-form").addEventListener("submit", async event => {
|
|
event.preventDefault(); if (!authenticated || pending || job?.status === "running" || !runtimeAvailable) return;
|
|
const provider = picker.value, input = {
|
|
provider, certificate_id: $("acme-name").value.trim(), email: $("acme-email").value.trim(), domains: $("acme-domains").value.split(/[,\n]/).map(v => v.trim()).filter(Boolean), environment: $("acme-environment").value,
|
|
agree_tos: $("acme-tos").checked, confirm_production: $("acme-confirm-production").checked
|
|
};
|
|
if (provider === "rfc2136") Object.assign(input, { dns_server: $("acme-dns").value.trim(), dns_port: Number($("acme-port").value), key_name: $("acme-key-name").value.trim(), key_secret: $("acme-secret").value, key_algorithm: $("acme-algorithm").value, sign_query: $("acme-sign-query").checked });
|
|
else if (provider === "cloudflare") input.api_token = $("acme-cf-token").value;
|
|
else if (provider === "ovh") Object.assign(input, { endpoint: $("acme-ovh-endpoint").value, application_key: $("acme-ovh-application-key").value, application_secret: $("acme-ovh-application-secret").value, consumer_key: $("acme-ovh-consumer-key").value });
|
|
else if (provider !== "http01") return;
|
|
if (provider !== "http01") input.propagation_seconds = Number($("acme-propagation").value);
|
|
if (provider === "http01" && input.domains.some(d => d.startsWith("*."))) { toast(t("acme.http01_no_wildcard"), true); return; }
|
|
if (input.environment === "production" && !input.confirm_production) { toast(t("acme.production_confirmation"), true); return; }
|
|
pending = true; $("acme-submit").disabled = true; const epoch = authEpoch;
|
|
try {
|
|
const value = await api("/api/acme/issue", { method: "POST", body: JSON.stringify(input) });
|
|
if (epoch === authEpoch && authenticated) { resetIssueFormJob = value.job?.id || null; render(value.job); selectTab("generate"); toast(t("acme.working")); }
|
|
} catch (error) { if (epoch === authEpoch) toast(error.message, true); }
|
|
finally {
|
|
for (const key of ["key_secret", "api_token", "application_key", "application_secret", "consumer_key"]) delete input[key];
|
|
clearSecrets(); pending = false; syncSubmitState();
|
|
}
|
|
});
|
|
$("acme-refresh").addEventListener("click", () => void refresh());
|
|
$("acme-import").addEventListener("click", async () => {
|
|
if (!envelope || !authenticated || !job?.certificate) return;
|
|
const cert = structuredClone(job.certificate), next = structuredClone(envelope.config); next.tls ||= {}; next.tls.certificates ||= [];
|
|
const index = next.tls.certificates.findIndex(c => c.id === cert.id);
|
|
if (index >= 0) { if (!(await appConfirm(t("acmeReplace"), { danger: true }))) return; cert.hosts = next.tls.certificates[index].hosts || []; next.tls.certificates[index] = cert; }
|
|
else next.tls.certificates.push(cert);
|
|
if (await saveSection("tls", next.tls || {})) { toast(t("acmeImported")); $("acme-import").hidden = true; selectTab("installed"); }
|
|
});
|
|
rustProxyRefresh.register("acme", {
|
|
interval: () => 3, active: () => currentPanel === "tls", run: loadAcme
|
|
});
|
|
window.rustProxyAcme = {
|
|
refresh,
|
|
select: selectTab,
|
|
syncLocation,
|
|
current: () => activeTab,
|
|
reset() {
|
|
job = null; renewalLogs = {}; resetIssueFormJob = null; runtimeAvailable = true; $("renewal-list").replaceChildren(); resetIssueForm();
|
|
renderRuntime(null); render(null); selectTab("installed", false, false);
|
|
}
|
|
};
|
|
window.rustProxyCertificates = { open, close, select: selectTab, reset() { clearSecrets(); picker.value = "http01"; syncProvider(); selectTab("installed", false, false); } };
|
|
syncProvider(); selectTab(activeTab, false, false);
|
|
})();
|