UNPKG

vite-plugin-cpanel-ssl

Version:

Automatically use your cPanel SSL certs and keys for the Vite dev server

71 lines 2.8 kB
// src/index.ts import { readFile, readdir } from "fs/promises"; import { join, basename } from "path"; function parseUserConfig(userConfig) { userConfig.enable ?? (userConfig.enable = true); return userConfig; } function extractFilenameHash(filename) { const name = basename(filename, ".crt"); const parts = name.split("_"); let boundaryIndex = parts.findIndex((part) => /[0-9a-f]{4,}/i.test(part)); if (boundaryIndex === -1) return null; const uniqueParts = parts.slice(boundaryIndex, boundaryIndex + 2).join("_"); return uniqueParts; } function vitePluginCPanelSsl(userConfig = {}) { userConfig = parseUserConfig(userConfig); return { name: "vite-plugin-cpanel-ssl", config: async (config, env) => { if (env.mode === "production") return; else if (typeof userConfig.enable === "function" && userConfig.enable() !== true) return; else if (userConfig.enable !== true) return; const homeDir = process.env.HOME; if (!homeDir) { console.log("[cPanelSSL]: Couldn't find home directory from process"); return; } const certsDir = join(homeDir, "ssl", "certs"); const keysDir = join(homeDir, "ssl", "keys"); const certsList = (await readdir(certsDir)).filter((filename) => filename.endsWith(".crt.cache")); const certFile = await Promise.all( certsList.map((cert) => { return readFile(join(certsDir, cert), "utf-8").then((contents) => ({ path: join(certsDir, cert.replace(/\.cache$/, "")), contents: JSON.parse(contents) })); }) ).then((certFiles) => { return certFiles.filter(({ contents }) => { const expires = contents.parsed.not_after * 1e3; const isSelfSigned = Boolean(contents.parsed.is_self_signed); return expires >= Date.now() && !isSelfSigned && (!userConfig.domain || contents.parsed.domains.includes(userConfig.domain)); }); }).then((certFiles) => certFiles[0]?.path); const hash = extractFilenameHash(certFile); if (!hash) { console.log("[cPanelSSL]: Couldn't extract hash from certificate filename"); return; } const keyFile = (await readdir(keysDir)).find((keyfile) => keyfile.startsWith(hash)); if (!keyFile) { console.log("[cPanelSSL]: Couldn't find key file"); return; } config.server ?? (config.server = {}); const files = await Promise.all([readFile(certFile, "utf-8"), readFile(join(keysDir, keyFile), "utf-8")]); config.server.https = { cert: files[0], key: files[1] }; if (!config.server.host) { config.server.host = userConfig.domain; } } }; } export { vitePluginCPanelSsl as default }; //# sourceMappingURL=index.js.map