automated mode
This commit is contained in:
@@ -39,6 +39,8 @@ const securityRequireSymbolInput = document.getElementById("security-require-sym
|
||||
const tlsForm = document.getElementById("tls-form");
|
||||
const tlsPermissionNote = document.getElementById("tls-permission-note");
|
||||
const tlsSaveBtn = document.getElementById("tls-save-btn");
|
||||
const tlsCertbotAutoBtn = document.getElementById("tls-certbot-auto-btn");
|
||||
const tlsCertbotEmailInput = document.getElementById("tls-certbot-email");
|
||||
const tlsCertbotEnabledInput = document.getElementById("tls-certbot-enabled");
|
||||
const tlsCertbotLivePathInput = document.getElementById("tls-certbot-live-path");
|
||||
const tlsCertbotDomainInput = document.getElementById("tls-certbot-domain");
|
||||
@@ -136,6 +138,7 @@ function setSecurityFormDisabled(disabled) {
|
||||
|
||||
function setTlsFormDisabled(disabled) {
|
||||
const controls = [
|
||||
tlsCertbotEmailInput,
|
||||
tlsCertbotEnabledInput,
|
||||
tlsCertbotLivePathInput,
|
||||
tlsCertbotDomainInput,
|
||||
@@ -143,6 +146,7 @@ function setTlsFormDisabled(disabled) {
|
||||
tlsCertbotKeyFileInput,
|
||||
tlsCertbotCaFileInput,
|
||||
tlsSaveBtn,
|
||||
tlsCertbotAutoBtn,
|
||||
];
|
||||
|
||||
for (const control of controls) {
|
||||
@@ -151,6 +155,14 @@ function setTlsFormDisabled(disabled) {
|
||||
}
|
||||
}
|
||||
|
||||
function setTlsAutoSetupRunning(running) {
|
||||
if (!tlsCertbotAutoBtn) return;
|
||||
tlsCertbotAutoBtn.disabled = running;
|
||||
tlsCertbotAutoBtn.innerHTML = running
|
||||
? '<i class="fa-solid fa-spinner fa-spin mr-2"></i>Running Certbot Setup...'
|
||||
: '<i class="fa-solid fa-wand-magic-sparkles mr-2"></i>Auto Setup Free SSL (Let\'s Encrypt)';
|
||||
}
|
||||
|
||||
function applySecurityForm() {
|
||||
if (!securityConfig) return;
|
||||
securitySessionTtlInput.value = String(securityConfig.sessionTtlHours || 168);
|
||||
@@ -200,6 +212,7 @@ async function loadSecurityPolicy() {
|
||||
function applyTlsForm() {
|
||||
const certbot = tlsConfig?.certbot || {};
|
||||
tlsCertbotEnabledInput.checked = Boolean(certbot.enabled);
|
||||
tlsCertbotEmailInput.value = "";
|
||||
tlsCertbotLivePathInput.value = certbot.livePath || "/etc/letsencrypt/live";
|
||||
tlsCertbotDomainInput.value = certbot.domain || "";
|
||||
tlsCertbotCertFileInput.value = certbot.certFileName || "fullchain.pem";
|
||||
@@ -385,6 +398,55 @@ async function saveTlsSettings(event) {
|
||||
showMessage("TLS settings updated. Restart server to apply.");
|
||||
}
|
||||
|
||||
async function runCertbotAutoSetup() {
|
||||
if (!isAdmin(currentUser?.role)) {
|
||||
showMessage("Admin role required.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const domain = String(tlsCertbotDomainInput.value || "").trim();
|
||||
const email = String(tlsCertbotEmailInput.value || "").trim();
|
||||
const livePath = String(tlsCertbotLivePathInput.value || "").trim() || "/etc/letsencrypt/live";
|
||||
|
||||
if (!domain) {
|
||||
showMessage("Please enter a domain first.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
showMessage("Please enter an email first.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
setTlsAutoSetupRunning(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/settings/tls/certbot/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ domain, email, livePath }),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
showMessage(data.error || "Certbot setup failed.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
tlsConfig = data.tls || tlsConfig;
|
||||
applyTlsForm();
|
||||
const details = data?.certbot?.certPath
|
||||
? ` Cert: ${data.certbot.certPath}`
|
||||
: "";
|
||||
showMessage(`${data.message || "Certbot setup complete."}${details}`);
|
||||
} catch (error) {
|
||||
showMessage(`Certbot setup failed: ${String(error?.message || error)}`, "error");
|
||||
} finally {
|
||||
setTlsAutoSetupRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBannedIps() {
|
||||
if (!currentUser) return;
|
||||
|
||||
@@ -483,6 +545,7 @@ async function init() {
|
||||
prefsForm.addEventListener("submit", savePrefs);
|
||||
securityForm.addEventListener("submit", saveSecurityPolicy);
|
||||
tlsForm.addEventListener("submit", saveTlsSettings);
|
||||
tlsCertbotAutoBtn.addEventListener("click", runCertbotAutoSetup);
|
||||
refreshBansBtn.addEventListener("click", loadBannedIps);
|
||||
bansTableBody.addEventListener("click", handleUnbanClick);
|
||||
} catch (error) {
|
||||
|
||||
@@ -211,6 +211,15 @@
|
||||
</label>
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<label class="block">
|
||||
<span class="text-sm text-slate-300">Let's Encrypt account email</span>
|
||||
<input
|
||||
id="tls-certbot-email"
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
class="mt-1 w-full px-3 py-2 rounded-lg bg-slate-900 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-sky-500"
|
||||
/>
|
||||
</label>
|
||||
<label class="block sm:col-span-2">
|
||||
<span class="text-sm text-slate-300">Certbot live base path</span>
|
||||
<input
|
||||
@@ -258,6 +267,19 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg border border-slate-800 bg-slate-900/70 p-3 space-y-2">
|
||||
<div class="text-xs text-slate-300">
|
||||
One-click setup requirements: DNS for the domain must point to this server and inbound port 80 must be reachable.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
id="tls-certbot-auto-btn"
|
||||
class="px-4 py-2 rounded-lg bg-emerald-700 hover:bg-emerald-600 transition-colors text-white font-medium"
|
||||
>
|
||||
<i class="fa-solid fa-wand-magic-sparkles mr-2"></i>Auto Setup Free SSL (Let's Encrypt)
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
id="tls-save-btn"
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { spawn } from "child_process";
|
||||
import { existsSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
export type CertbotSetupParams = {
|
||||
domain: string;
|
||||
email: string;
|
||||
livePath: string;
|
||||
};
|
||||
|
||||
export type CertbotSetupResult = {
|
||||
certPath: string;
|
||||
keyPath: string;
|
||||
caPath: string;
|
||||
output: string;
|
||||
};
|
||||
|
||||
function runCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
timeoutMs = 12 * 60 * 1000,
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGTERM");
|
||||
reject(new Error(`Command timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on("close", (exitCode) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ stdout, stderr, exitCode: exitCode ?? -1 });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isValidDomain(domain: string): boolean {
|
||||
const value = domain.trim().toLowerCase();
|
||||
if (!value || value.length > 253) return false;
|
||||
return /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(value);
|
||||
}
|
||||
|
||||
function isValidEmail(email: string): boolean {
|
||||
const value = email.trim();
|
||||
if (!value || value.length > 254) return false;
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
||||
}
|
||||
|
||||
export async function runCertbotSetup(
|
||||
params: CertbotSetupParams,
|
||||
): Promise<CertbotSetupResult> {
|
||||
const domain = params.domain.trim().toLowerCase();
|
||||
const email = params.email.trim();
|
||||
const livePath = params.livePath.trim() || "/etc/letsencrypt/live";
|
||||
|
||||
if (!isValidDomain(domain)) {
|
||||
throw new Error("Invalid domain. Use a real FQDN like example.com");
|
||||
}
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
throw new Error("Invalid email address");
|
||||
}
|
||||
|
||||
const versionCheck = await runCommand("certbot", ["--version"], 30_000).catch(
|
||||
(error) => {
|
||||
throw new Error(
|
||||
`certbot is not available on this server. Install certbot first. Details: ${String(error?.message || error)}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (versionCheck.exitCode !== 0) {
|
||||
throw new Error(`certbot --version failed: ${versionCheck.stderr || versionCheck.stdout}`);
|
||||
}
|
||||
|
||||
const certbotArgs = [
|
||||
"certonly",
|
||||
"--non-interactive",
|
||||
"--agree-tos",
|
||||
"--standalone",
|
||||
"--preferred-challenges",
|
||||
"http",
|
||||
"--keep-until-expiring",
|
||||
"--email",
|
||||
email,
|
||||
"-d",
|
||||
domain,
|
||||
];
|
||||
|
||||
const certbotResult = await runCommand("certbot", certbotArgs);
|
||||
|
||||
const output = `${certbotResult.stdout}\n${certbotResult.stderr}`.trim();
|
||||
if (certbotResult.exitCode !== 0) {
|
||||
throw new Error(
|
||||
`certbot failed (exit ${certbotResult.exitCode}). Ensure DNS points to this server and port 80 is reachable.\n${output}`,
|
||||
);
|
||||
}
|
||||
|
||||
const certPath = path.join(livePath, domain, "fullchain.pem");
|
||||
const keyPath = path.join(livePath, domain, "privkey.pem");
|
||||
const caPath = path.join(livePath, domain, "chain.pem");
|
||||
|
||||
if (!existsSync(certPath) || !existsSync(keyPath)) {
|
||||
throw new Error(
|
||||
`certbot completed but expected files were not found. cert=${certPath} key=${keyPath}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
certPath,
|
||||
keyPath,
|
||||
caPath,
|
||||
output,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { listClients } from "../../db";
|
||||
import { logger } from "../../logger";
|
||||
import { metrics } from "../../metrics";
|
||||
import { requirePermission } from "../../rbac";
|
||||
import { runCertbotSetup } from "../certbot-setup";
|
||||
|
||||
type MiscRouteDeps = {
|
||||
CORS_HEADERS: Record<string, string>;
|
||||
@@ -194,6 +195,88 @@ export async function handleMiscRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/settings/tls/certbot/setup") {
|
||||
const user = await authenticateRequest(req);
|
||||
if (!user) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
if (user.role !== "admin") {
|
||||
return new Response("Forbidden: Admin access required", { status: 403 });
|
||||
}
|
||||
|
||||
let body: any = {};
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return Response.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const domain = String(body?.domain || "").trim();
|
||||
const email = String(body?.email || "").trim();
|
||||
const livePath = String(body?.livePath || "/etc/letsencrypt/live").trim() || "/etc/letsencrypt/live";
|
||||
|
||||
try {
|
||||
const result = await runCertbotSetup({ domain, email, livePath });
|
||||
|
||||
const updated = await updateTlsConfig({
|
||||
certbot: {
|
||||
enabled: true,
|
||||
livePath,
|
||||
domain,
|
||||
certFileName: "fullchain.pem",
|
||||
keyFileName: "privkey.pem",
|
||||
caFileName: "chain.pem",
|
||||
},
|
||||
});
|
||||
|
||||
logAudit({
|
||||
timestamp: Date.now(),
|
||||
username: user.username,
|
||||
ip: deps.requestIP?.(req)?.address || "unknown",
|
||||
action: AuditAction.COMMAND,
|
||||
details: `Ran certbot setup for domain ${domain}`,
|
||||
success: true,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
ok: true,
|
||||
tls: updated,
|
||||
certbot: {
|
||||
certPath: result.certPath,
|
||||
keyPath: result.keyPath,
|
||||
caPath: result.caPath,
|
||||
output: result.output,
|
||||
},
|
||||
message:
|
||||
"Certificate issued and certbot TLS mode enabled. Restart the server/container to load the new certificate.",
|
||||
},
|
||||
{ headers: deps.CORS_HEADERS },
|
||||
);
|
||||
} catch (error: any) {
|
||||
logger.error("[TLS] certbot auto-setup failed", error);
|
||||
|
||||
logAudit({
|
||||
timestamp: Date.now(),
|
||||
username: user.username,
|
||||
ip: deps.requestIP?.(req)?.address || "unknown",
|
||||
action: AuditAction.COMMAND,
|
||||
details: `Certbot setup failed for domain ${domain}`,
|
||||
success: false,
|
||||
errorMessage: String(error?.message || error),
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
ok: false,
|
||||
error: String(error?.message || "Certbot setup failed"),
|
||||
},
|
||||
{ status: 400, headers: deps.CORS_HEADERS },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/api/audit-logs") {
|
||||
const user = await authenticateRequest(req);
|
||||
if (!user) {
|
||||
|
||||
Reference in New Issue
Block a user