Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Subash committed Jun 21, 2020
1 parent 36126c3 commit 698b441
Show file tree
Hide file tree
Showing 7 changed files with 2,305 additions and 2,465 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.DS_Store
node_modules
coverage
coverage
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
coverage
node_modules
tests
.editorconfig
.editorconfig
4,657 changes: 2,261 additions & 2,396 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@
},
"homepage": "https://github.com/Subash/mkcert#readme",
"dependencies": {
"commander": "^2.19.0",
"is-ip": "^2.0.0",
"node-forge": "^0.7.6",
"random-int": "^1.0.0"
"commander": "^5.1.0",
"is-ip": "^3.1.0",
"node-forge": "^0.9.1",
"random-int": "^2.0.1"
},
"devDependencies": {
"jest": "^24.0.0"
"jest": "^26.0.1"
}
}
33 changes: 9 additions & 24 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,41 +43,26 @@ $ mkcert create-cert --help

## API

### Create a Certificate Authority
```js
import * as mkcert from 'mkcert';

//Create a Certificate Authority
mkcert.createCA({
// create a certificate authority
const ca = await mkcert.createCA({
organization: 'Hello CA',
countryCode: 'NP',
state: 'Bagmati',
locality: 'Kathmandu',
validityDays: 365
})
.then((ca)=> {
console.log(ca.key, ca.cert);
})
.catch(err=> console.error(err));
```
});

### Create a Certificate
```js
import * as mkcert from 'mkcert';
//Create a CA first

//Then create the certificate
mkcert.createCert({
// then create the certificate
const cert = await mkcert.createCert({
domains: ['127.0.0.1', 'localhost'],
validityDays: 365,
caKey: ca.key,
caCert: ca.cert
})
.then((cert)=> {
console.log(cert.key, cert.cert);
});

//Create a full chain certificate by merging CA and domain certificates
console.log(`${cert.cert}\n${ca.cert}`);
})
.catch(err=> console.error(err));
```
console.log(cert.key, cert.cert); // certificate info
console.log(`${cert.cert}\n${ca.cert}`); // create a full chain certificate by merging CA and domain certificates
```
24 changes: 12 additions & 12 deletions src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ const fs = require('fs');
const mkcert = require('./mkcert');

async function createCA({ organization, countryCode, state, locality, validity, key, cert }) {
//Validate days
// validate days
validity = Number.parseInt(validity, 10);
if(!validity || validity < 0) return console.error('`--validity` must be at least 1 day.');

//Create the certificate
// create the certificate
let ca;
try {
ca = await mkcert.createCA({ organization, countryCode, state, locality, validityDays: validity });
} catch (err) {
return console.error(`Failed to create the certificate. Error: ${err.message}`);
}

//Write certificates
// write certificates
key = path.resolve(key);
fs.writeFileSync(key, ca.key);
console.log(`CA Private Key: ${key}`);
Expand All @@ -29,45 +29,45 @@ async function createCA({ organization, countryCode, state, locality, validity,
}

async function createCert({ domains, caKey, caCert, validity, key, cert }) {
//Validate days
// validate days
validity = Number.parseInt(validity, 10);
if(!validity || validity < 0) return console.error('`--validity` must be at least 1 day.');

//Validate addresses
// validate addresses
domains = domains.split(',').map( str=> str.trim()); //Split comma separated list of addresses
if(!domains.length) return console.error('`--domains` must be a comma separated list of ip/domains.');

//Read CA data
// read CA data
const ca = {};

//Read CA key
// read CA key
try {
ca.key = fs.readFileSync(path.resolve(caKey), 'utf-8');
} catch(err) {
return console.error(`Unable to read \`${caKey}\`. Please run \`mkcert create-ca\` to create a new certificate authority.`);
}

//Read CA certificate
// read CA certificate
try {
ca.cert = fs.readFileSync(path.resolve(caCert), 'utf-8');
} catch(err) {
return console.error(`Unable to read \`${caCert}\`. Please run \`mkcert create-ca\` to create a new certificate authority.`);
}

//Create the certificate
// create the certificate
let tls;
try {
tls = await mkcert.createCert({ domains, validityDays: validity, caKey: ca.key, caCert: ca.cert });
} catch (err) {
return console.error(`Failed to create the certificate. Error: ${err.message}`);
}

//Write certificates
// write certificates
key = path.resolve(key);
fs.writeFileSync(key, tls.key);
console.log(`Private Key: ${key}`);
cert = path.resolve(cert);
fs.writeFileSync(cert, `${tls.cert}\n${ca.cert}`); //Create full chain by combining ca and domain certificate
fs.writeFileSync(cert, `${tls.cert}\n${ca.cert}`); // create full chain by combining ca and domain certificate
console.log(`Certificate: ${cert}`);
}

Expand Down Expand Up @@ -102,5 +102,5 @@ program
.version(pkg.version)
.parse(process.argv);

//Show help by default
// show help by default
if(process.argv.length < 3) program.outputHelp();
42 changes: 16 additions & 26 deletions src/mkcert.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,24 @@ const generateKeyPair = promisify(pki.rsa.generateKeyPair.bind(pki.rsa));
async function generateCert({ subject, issuer, extensions, validityDays, signWith }) {
const keyPair = await generateKeyPair({ bits: 2048, workers: 4 });
const cert = pki.createCertificate();
const serial = randomInt(50000, 99999).toString(); //Generate a random number between 50K and 100K
const serial = randomInt(50000, 99999).toString(); // generate a random number between 50K and 100K

//Use the provided private key to sign the certificate if that exists; otherwise sign the certificate with own key
// use the provided private key to sign the certificate if that exists
// otherwise sign the certificate with own key
signWith = signWith? pki.privateKeyFromPem(signWith): keyPair.privateKey;

//Set public key
// public key
cert.publicKey = keyPair.publicKey;
cert.serialNumber = Buffer.from(serial).toString('hex'); //Hex encode the serial number
cert.serialNumber = Buffer.from(serial).toString('hex'); // hex encode the serial number

//Validity
// validity
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + validityDays);

//Set subject
cert.setSubject(subject);

//Set issuer
cert.setIssuer(issuer);

//Set extensions
cert.setExtensions(extensions);

//Sign using sha256
cert.sign(signWith, forge.md.sha256.create());

return {
Expand All @@ -41,7 +35,7 @@ async function generateCert({ subject, issuer, extensions, validityDays, signWit
}

async function createCA({ organization, countryCode, state, locality, validityDays }) {
//Certificate Attributes: https://git.io/fptna
// certificate Attributes: https://git.io/fptna
const attributes = [
{ name: 'commonName', value: organization },
{ name: 'countryName', value: countryCode },
Expand All @@ -50,7 +44,7 @@ async function createCA({ organization, countryCode, state, locality, validityDa
{ name: 'organizationName', value: organization }
];

//Certificate extensions for a CA
// certificate extensions for a CA
const extensions = [
{ name: 'basicConstraints', cA: true, critical: true },
{ name: 'keyUsage', keyCertSign: true, critical: true }
Expand All @@ -65,31 +59,27 @@ async function createCA({ organization, countryCode, state, locality, validityDa
}

async function createCert({ domains, validityDays, caKey, caCert }) {
//Certificate Attributes: https://git.io/fptna
// certificate Attributes: https://git.io/fptna
const attributes = [
{ name: 'commonName', value: domains[0] } //Use the first address as common name
{ name: 'commonName', value: domains[0] } // use the first address as common name
];

//Certificate extensions for a domain certificate
// certificate extensions for a domain certificate
const extensions = [
{ name: 'basicConstraints', cA: false, critical: true },
{ name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true },
{ name: 'extKeyUsage', serverAuth: true, clientAuth: true },
{ name: 'subjectAltName', altNames: domains.map( domain=> {
// Available Types: https://git.io/fptng
const types = { domain: 2, ip: 7 };
if(isIp(domain)) {
return { type: types.ip, ip: domain };
} else {
return { type: types.domain, value: domain };
}
const types = { domain: 2, ip: 7 }; // available Types: https://git.io/fptng
if(isIp(domain)) return { type: types.ip, ip: domain };
return { type: types.domain, value: domain };
})}
];

//Parse CA certificate
// parse CA certificate
const ca = pki.certificateFromPem(caCert);

//Create the cert
// create the cert
return await generateCert({
subject: attributes,
issuer: ca.subject.attributes,
Expand Down

0 comments on commit 698b441

Please sign in to comment.