Skip to content

Commit b58286d

Browse files
feat: Add cert validation (#5588)
1 parent 65f277f commit b58286d

1 file changed

Lines changed: 27 additions & 4 deletions

File tree

drizzle-kit/src/utils/certs.ts

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,27 @@ import { mkdirSync } from 'fs';
33
import { access, readFile } from 'fs/promises';
44
import type { ExecOptions } from 'node:child_process';
55
import { exec } from 'node:child_process';
6+
import { X509Certificate } from 'node:crypto';
67
import { join } from 'path';
78

8-
export function runCommand(command: string, options: ExecOptions = {}) {
9+
function runCommand(command: string, options: ExecOptions = {}) {
910
return new Promise<{ exitCode: number }>((resolve) => {
1011
exec(command, options, (error) => {
1112
return resolve({ exitCode: error?.code ?? 0 });
1213
});
1314
});
1415
}
1516

17+
function isCertValid(certPem: string): boolean {
18+
try {
19+
const cert = new X509Certificate(certPem);
20+
const now = new Date();
21+
return now >= new Date(cert.validFrom) && now <= new Date(cert.validTo);
22+
} catch {
23+
return false;
24+
}
25+
}
26+
1627
export const certs = async () => {
1728
const res = await runCommand('mkcert --help');
1829

@@ -21,20 +32,32 @@ export const certs = async () => {
2132
suffix: '',
2233
});
2334

24-
// create ~/.local/share/drizzle-studio
35+
// create the directory if it doesn't exist
36+
// linux: ~/.local/share/drizzle-studio
37+
// macos: ~/Library/Application\ Support/drizzle-studio
38+
// windows: %LOCALAPPDATA%\drizzle-studio\Data
2539
mkdirSync(p.data, { recursive: true });
2640

27-
// ~/.local/share/drizzle-studio
2841
const keyPath = join(p.data, 'localhost-key.pem');
2942
const certPath = join(p.data, 'localhost.pem');
3043

44+
let needsCreate = false;
3145
try {
3246
// check if the files exist
3347
await Promise.all([access(keyPath), access(certPath)]);
48+
// check if the cert is still valid
49+
const certPem = await readFile(certPath, { encoding: 'utf-8' });
50+
if (!isCertValid(certPem)) {
51+
needsCreate = true;
52+
}
3453
} catch {
35-
// if not create them
54+
needsCreate = true;
55+
}
56+
57+
if (needsCreate) {
3658
await runCommand(`mkcert localhost`, { cwd: p.data });
3759
}
60+
3861
const [key, cert] = await Promise.all([
3962
readFile(keyPath, { encoding: 'utf-8' }),
4063
readFile(certPath, { encoding: 'utf-8' }),

0 commit comments

Comments
 (0)