UNPKG

@azure/static-web-apps-cli

Version:
49 lines 2 kB
import { promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; import pem from "pem"; import { logger } from "./utils/logger.js"; const ONE_MONTH = 1000 * 60 * 60 * 24 * 30; /** * Generate a new SSL certificate. This will create a new key and certificate and cache them in the * `~/.swa/certificates/ssl` directory, for one month. * * @param options PEM options (passed to the "`pem`" npm library) * @returns The abosulte filepath to the PEM file from cache. */ export async function getCertificate(options) { const cacheDir = path.join(os.homedir(), ".swa", "certificates", "ssl"); const cachePath = path.join(cacheDir, "swa-cli-UNSIGNED.pem"); try { logger.silly(`Checking for cached certificate at ${cachePath}`); const [stat, unsignedCertificate] = await Promise.all([fs.stat(cachePath), fs.readFile(cachePath, "utf8")]); if (Date.now() - stat.ctime.valueOf() > ONE_MONTH) { throw new Error("Certificate is too old, a new one will be generated."); } logger.silly("Certificate is valid, using it."); return unsignedCertificate; } catch { logger.silly("No cached certificate found."); logger.silly("Creating new certificate..."); const unsignedCertificate = await createCertificate(options); logger.silly("Writing certificate to cache..."); const pemContent = [unsignedCertificate.csr, unsignedCertificate.serviceKey, unsignedCertificate.certificate].join("\n"); await fs.mkdir(cacheDir, { recursive: true }); await fs.writeFile(cachePath, pemContent); return cachePath; } } async function createCertificate(options) { return new Promise((resolve, reject) => { pem.createCertificate(options, (err, keys) => { if (err) { reject(err); } else { resolve(keys); } }); }); } //# sourceMappingURL=ssl.js.map