Skip to content
Closed
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
23 changes: 17 additions & 6 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { X509Certificate } from 'node:crypto';
import { X509Certificate, createPrivateKey } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
Expand All @@ -19,10 +19,16 @@ async function ensureDir(dir: string) {
}
}

function isCertValid(content: string) {
function isCertValid(content: string, passphrase?: string) {
try {
const { validTo } = new X509Certificate(content);
return new Date(validTo).getTime() > Date.now();
const cert = new X509Certificate(content);
const privateKey = createPrivateKey({ key: content, passphrase });
const now = Date.now();
return (
new Date(cert.validFrom).getTime() <= now &&
new Date(cert.validTo).getTime() > now &&
cert.checkPrivateKey(privateKey)
);
} catch {
return false;
}
Expand Down Expand Up @@ -57,8 +63,13 @@ export const resolveHttpsConfig = async (
encoding: 'utf-8',
});

// Reuse the cached certificate until it expires
if (isCertValid(content)) {
// Reuse only a currently valid certificate with a matching private key.
if (
isCertValid(
content,
config?.passphrase ?? options.selfsignedOptions?.passphrase,
)
) {
return {
key: content,
cert: content,
Expand Down
Loading