Skip to content

Commit e430e5a

Browse files
committed
Refresh the local CA on startup if it expires soon
1 parent 0ac17fc commit e430e5a

File tree

3 files changed

+25
-4
lines changed

3 files changed

+25
-4
lines changed

package-lock.json

Lines changed: 8 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"graphql-yoga": "^1.18.1",
4545
"lodash": "^4.17.13",
4646
"mockttp": "^0.19.0",
47+
"node-forge": "^0.9.0",
4748
"node-gsettings-wrapper": "^0.5.0",
4849
"registry-js": "^1.4.0",
4950
"rimraf": "^2.6.2",

src/index.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as path from 'path';
33
import * as fs from 'fs';
44
import * as envPaths from 'env-paths';
55
import { getStandalone, generateCACertificate } from 'mockttp';
6+
import * as forge from 'node-forge';
67
import { Mutex } from 'async-mutex';
78

89
import updateCommand from '@oclif/plugin-update/lib/commands/update';
@@ -15,6 +16,7 @@ import { registerShutdownHandler } from './shutdown';
1516

1617
const canAccess = util.promisify(fs.access);
1718
const mkDir = util.promisify(fs.mkdir);
19+
const readFile = util.promisify(fs.readFile);
1820
const writeFile = util.promisify(fs.writeFile);
1921

2022
const ensureDirectoryExists = (path: string) =>
@@ -26,8 +28,10 @@ async function generateHTTPSConfig(configPath: string) {
2628

2729
await Promise.all([
2830
canAccess(keyPath, fs.constants.R_OK),
29-
canAccess(certPath, fs.constants.R_OK)
31+
readFile(certPath, 'utf8').then(checkCertExpiry)
3032
]).catch(async () => {
33+
// Cert doesn't exist, or is too close/past expiry. Generate a new one:
34+
3135
const newCertPair = await generateCACertificate({
3236
commonName: 'HTTP Toolkit CA'
3337
});
@@ -45,6 +49,17 @@ async function generateHTTPSConfig(configPath: string) {
4549
};
4650
}
4751

52+
function checkCertExpiry(contents: string): void {
53+
const cert = forge.pki.certificateFromPem(contents);
54+
const expiry = cert.validity.notAfter.valueOf();
55+
const remainingLifetime = expiry - Date.now();
56+
57+
if (remainingLifetime < 1000 * 60 * 60 * 48) { // Next two days
58+
console.warn('Certificate expires soon - it must be regenerated');
59+
throw new Error('Certificate regeneration required');
60+
}
61+
}
62+
4863
export async function runHTK(options: {
4964
configPath?: string
5065
} = {}) {

0 commit comments

Comments
 (0)