Skip to content

feat: persist and reuse generated https certificates #136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 52 additions & 2 deletions src/_cert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@
import { promisify } from "node:util";
import nodeOS from "node:os";
import { promises as fs } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import type nodeForge from "node-forge";
import forge from "node-forge";
import ipRegex from "ip-regex";
import { defu } from "defu";
import { resolve } from "pathe";
import type { Certificate, HTTPSOptions } from "./types";

const certificateDirectory = "node_modules/.listhen/certs/";

export interface CertificateOptions {
validityDays: number;
subject: nodeForge.pki.CertificateField[];
Expand Down Expand Up @@ -40,10 +44,36 @@ export interface TLSCertOptions
passphrase?: string;
}

function pathExists(path: string) {
return new Promise((resolve) => {
fs.access(path, fs.constants.F_OK)
.then(() => resolve(true))
.catch(() => resolve(false));
});
}

export async function resolveCertificate(
options: HTTPSOptions,
): Promise<Certificate> {
let https: Certificate;

if (typeof options === "object" && options.reuse) {
// Reuse previously autogenerated certificates if exists
const certsExists = await pathExists(certificateDirectory + "certs.json");

if (certsExists) {
const certs = JSON.parse(
(await fs.readFile(certificateDirectory + "certs.json")).toString(
"utf8",
),
);
return {
cert: certs.cert + certs.caCert,
key: certs.key,
};
}
}

if (typeof options === "object" && options.key && options.cert) {
// Resolve actual certificate and cert
https = await resolveCert(options);
Expand All @@ -70,7 +100,8 @@ export async function resolveCertificate(
cert: forge.pki.certificateToPem(_cert!),
};
} else {
const { cert } = await generateCertificates(options);
const { cert, ca } = await generateCertificates(options);
cert.cert += ca.cert;
https = cert;
}

Expand All @@ -95,6 +126,8 @@ async function generateCertificates(
caOptions.passphrase = options.signingKeyPassphrase;
const ca = await generateCACert(caOptions);

await mkdir(resolve(certificateDirectory), { recursive: true });

const domains = Array.isArray(options.domains)
? options.domains
: ["localhost", "127.0.0.1", "::1"];
Expand All @@ -106,7 +139,24 @@ async function generateCertificates(
signingKey: ca.key,
domains,
});
return { ca, cert };

await writeFile(
resolve(certificateDirectory + "certs.json"),
JSON.stringify({
cert: cert.cert,
key: cert.key,
caCert: ca.cert,
caKey: ca.key,
}),
);

return {
ca,
cert: {
cert: cert.cert,
key: cert.key,
},
};
}

async function resolveCert(options: HTTPSOptions): Promise<Certificate> {
Expand Down
6 changes: 6 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ export function getArgs() {
type: "boolean",
description: "Enable HTTPS",
},
"https.reuse": {
type: "boolean",
description: "Reuse previously autogenerated certificate",
default: false,
},
"https.cert": {
type: "string",
description: "Path to TLS certificate used with HTTPS in PEM format",
Expand Down Expand Up @@ -160,6 +165,7 @@ export function parseArgs(args: ParsedListhenArgs): Partial<ListenOptions> {
tunnel: args.tunnel,
https: args.https
? <HTTPSOptions>{
reuse: args["https.reuse"],
cert: args["https.cert"],
key: args["https.key"],
pfx: args["https.pfx"],
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface Certificate {
}

export interface HTTPSOptions {
reuse?: boolean;
cert?: string;
key?: string;
pfx?: string;
Expand Down