@@ -3,6 +3,7 @@ import * as path from 'path';
33import * as fs from 'fs' ;
44import * as envPaths from 'env-paths' ;
55import { getStandalone , generateCACertificate } from 'mockttp' ;
6+ import * as forge from 'node-forge' ;
67import { Mutex } from 'async-mutex' ;
78
89import updateCommand from '@oclif/plugin-update/lib/commands/update' ;
@@ -15,6 +16,7 @@ import { registerShutdownHandler } from './shutdown';
1516
1617const canAccess = util . promisify ( fs . access ) ;
1718const mkDir = util . promisify ( fs . mkdir ) ;
19+ const readFile = util . promisify ( fs . readFile ) ;
1820const writeFile = util . promisify ( fs . writeFile ) ;
1921
2022const 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+
4863export async function runHTK ( options : {
4964 configPath ?: string
5065} = { } ) {
0 commit comments