automated mode
This commit is contained in:
@@ -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