This commit is contained in:
2017-04-28 18:56:55 +02:00
parent 7d16ada760
commit 84177cd575
23 changed files with 1613 additions and 626 deletions

View File

@ -1,4 +1,4 @@
import * as q from 'q'
import * as q from 'smartq'
import * as plugins from './smartacme.plugins'
import * as helpers from './smartacme.helpers'
@ -10,85 +10,85 @@ import { AcmeCert } from './smartacme.classes.acmecert'
* class AcmeAccount represents an AcmeAccount
*/
export class AcmeAccount {
parentSmartAcme: SmartAcme
location: string
link: string
JWK
constructor(smartAcmeParentArg: SmartAcme) {
this.parentSmartAcme = smartAcmeParentArg
}
parentSmartAcme: SmartAcme
location: string
link: string
JWK
constructor(smartAcmeParentArg: SmartAcme) {
this.parentSmartAcme = smartAcmeParentArg
}
/**
* register the account with letsencrypt
*/
register() {
let done = q.defer()
this.parentSmartAcme.rawacmeClient.newReg(
{
contact: ['mailto:domains@lossless.org']
},
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
this.JWK = res.body.key
this.link = res.headers.link
console.log(this.link)
this.location = res.headers.location
done.resolve()
})
return done.promise
}
/**
* register the account with letsencrypt
*/
register() {
let done = q.defer()
this.parentSmartAcme.rawacmeClient.newReg(
{
contact: [ 'mailto:domains@lossless.org' ]
},
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
this.JWK = res.body.key
this.link = res.headers.link
console.log(this.link)
this.location = res.headers.location
done.resolve()
})
return done.promise
}
/**
* agree to letsencrypr terms of service
*/
agreeTos() {
let done = q.defer()
let tosPart = this.link.split(',')[1]
let tosLinkPortion = tosPart.split(';')[0]
let url = tosLinkPortion.split(';')[0].trim().replace(/[<>]/g, '')
this.parentSmartAcme.rawacmeClient.post(this.location, { Agreement: url, resource: 'reg' }, (err, res) => {
if (err) {
console.log(err)
done.reject(err)
return
}
done.resolve()
})
return done.promise
}
/**
* agree to letsencrypr terms of service
*/
agreeTos() {
let done = q.defer()
let tosPart = this.link.split(',')[ 1 ]
let tosLinkPortion = tosPart.split(';')[ 0 ]
let url = tosLinkPortion.split(';')[ 0 ].trim().replace(/[<>]/g, '')
this.parentSmartAcme.rawacmeClient.post(this.location, { Agreement: url, resource: 'reg' }, (err, res) => {
if (err) {
console.log(err)
done.reject(err)
return
}
done.resolve()
})
return done.promise
}
createAcmeCert(
domainNameArg: string,
countryArg = 'Germany',
countryShortArg = 'DE',
city = 'Bremen',
companyArg = 'Some Company',
companyShortArg = 'SC'
createAcmeCert(
domainNameArg: string,
countryArg = 'Germany',
countryShortArg = 'DE',
city = 'Bremen',
companyArg = 'Some Company',
companyShortArg = 'SC'
) {
let done = q.defer<AcmeCert>()
let acmeCert = new AcmeCert(
{
bit: 2064,
key: null, // not needed right now
domain: domainNameArg,
country: countryArg,
country_short: countryShortArg,
locality: city,
organization: companyArg,
organization_short: companyShortArg,
password: null,
unstructured: null,
subject_alt_names: null
},
this
)
done.resolve(acmeCert)
return done.promise
}
) {
let done = q.defer<AcmeCert>()
let acmeCert = new AcmeCert(
{
bit: 2064,
key: null, // not needed right now
domain: domainNameArg,
country: countryArg,
country_short: countryShortArg,
locality: city,
organization: companyArg,
organization_short: companyShortArg,
password: null,
unstructured: null,
subject_alt_names: null
},
this
)
done.resolve(acmeCert)
return done.promise
}
}

View File

@ -1,4 +1,4 @@
import * as q from 'q'
import * as q from 'smartq'
import * as plugins from './smartacme.plugins'
import * as helpers from './smartacme.helpers'
@ -17,31 +17,31 @@ export type TChallengeType = 'dns-01' | 'http-01'
export type TChallengeStatus = 'pending'
export interface ISmartAcmeChallenge {
uri: string
status: TChallengeStatus
type: TChallengeType
token: string
keyAuthorization: string
uri: string
status: TChallengeStatus
type: TChallengeType
token: string
keyAuthorization: string
}
export interface ISmartAcmeChallengeChosen extends ISmartAcmeChallenge {
dnsKeyHash: string
domainName: string
domainNamePrefixed: string
dnsKeyHash: string
domainName: string
domainNamePrefixed: string
}
export interface IAcmeCsrConstructorOptions {
bit: number,
key: string,
domain: string,
country: string,
country_short: string,
locality: string,
organization: string,
organization_short: string,
password: string,
unstructured: string,
subject_alt_names: string[]
bit: number,
key: string,
domain: string,
country: string,
country_short: string,
locality: string,
organization: string,
organization_short: string,
password: string,
unstructured: string,
subject_alt_names: string[]
}
// Dnsly instance (we really just need one)
@ -51,205 +51,205 @@ let myDnsly = new plugins.dnsly.Dnsly('google')
* class AcmeCert represents a cert for domain
*/
export class AcmeCert {
domainName: string
attributes
fullchain: string
parentAcmeAccount: AcmeAccount
csr
validFrom: Date
validTo: Date
keypair: IRsaKeypair
keyPairFinal: IRsaKeypair
chosenChallenge: ISmartAcmeChallengeChosen
dnsKeyHash: string
constructor(optionsArg: IAcmeCsrConstructorOptions, parentAcmeAccount: AcmeAccount) {
this.domainName = optionsArg.domain
this.parentAcmeAccount = parentAcmeAccount
this.keypair = helpers.createKeypair(optionsArg.bit)
let privateKeyForged = plugins.nodeForge.pki.privateKeyFromPem(this.keypair.privateKey)
let publicKeyForged = plugins.nodeForge.pki.publicKeyToPem(
plugins.nodeForge.pki.setRsaPublicKey(privateKeyForged.n, privateKeyForged.e)
)
this.keyPairFinal = {
privateKey: privateKeyForged,
publicKey: publicKeyForged
domainName: string
attributes
fullchain: string
parentAcmeAccount: AcmeAccount
csr
validFrom: Date
validTo: Date
keypair: IRsaKeypair
keyPairFinal: IRsaKeypair
chosenChallenge: ISmartAcmeChallengeChosen
dnsKeyHash: string
constructor(optionsArg: IAcmeCsrConstructorOptions, parentAcmeAccount: AcmeAccount) {
this.domainName = optionsArg.domain
this.parentAcmeAccount = parentAcmeAccount
this.keypair = helpers.createKeypair(optionsArg.bit)
let privateKeyForged = plugins.nodeForge.pki.privateKeyFromPem(this.keypair.privateKey)
let publicKeyForged = plugins.nodeForge.pki.publicKeyToPem(
plugins.nodeForge.pki.setRsaPublicKey(privateKeyForged.n, privateKeyForged.e)
)
this.keyPairFinal = {
privateKey: privateKeyForged,
publicKey: publicKeyForged
}
// set dates
this.validFrom = new Date()
this.validTo = new Date()
this.validTo.setDate(this.validFrom.getDate() + 90)
// set attributes
this.attributes = [
{ name: 'commonName', value: optionsArg.domain },
{ name: 'countryName', value: optionsArg.country },
{ shortName: 'ST', value: optionsArg.country_short },
{ name: 'localityName', value: optionsArg.locality },
{ name: 'organizationName', value: optionsArg.organization },
{ shortName: 'OU', value: optionsArg.organization_short },
{ name: 'challengePassword', value: optionsArg.password },
{ name: 'unstructuredName', value: optionsArg.unstructured }
]
// set up csr
this.csr = plugins.nodeForge.pki.createCertificationRequest()
this.csr.setSubject(this.attributes)
this.csr.setAttributes(this.attributes)
}
/**
* requests a challenge for a domain
* @param domainNameArg - the domain name to request a challenge for
* @param challengeType - the challenge type to request
*/
requestChallenge(challengeTypeArg: TChallengeType = 'dns-01') {
let done = q.defer<ISmartAcmeChallengeChosen>()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.newAuthz(
{
identifier: {
type: 'dns',
value: this.domainName
}
},
this.parentAcmeAccount.parentSmartAcme.keyPair,
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
}
let preChosenChallenge = res.body.challenges.filter(x => {
return x.type === challengeTypeArg
})[ 0 ]
// set dates
this.validFrom = new Date()
this.validTo = new Date()
this.validTo.setDate(this.validFrom.getDate() + 90)
// set attributes
this.attributes = [
{ name: 'commonName', value: optionsArg.domain },
{ name: 'countryName', value: optionsArg.country },
{ shortName: 'ST', value: optionsArg.country_short },
{ name: 'localityName', value: optionsArg.locality },
{ name: 'organizationName', value: optionsArg.organization },
{ shortName: 'OU', value: optionsArg.organization_short },
{ name: 'challengePassword', value: optionsArg.password },
{ name: 'unstructuredName', value: optionsArg.unstructured }
]
// set up csr
this.csr = plugins.nodeForge.pki.createCertificationRequest()
this.csr.setSubject(this.attributes)
this.csr.setAttributes(this.attributes)
}
/**
* requests a challenge for a domain
* @param domainNameArg - the domain name to request a challenge for
* @param challengeType - the challenge type to request
*/
requestChallenge(challengeTypeArg: TChallengeType = 'dns-01') {
let done = q.defer<ISmartAcmeChallengeChosen>()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.newAuthz(
{
identifier: {
type: 'dns',
value: this.domainName
}
},
this.parentAcmeAccount.parentSmartAcme.keyPair,
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
}
let preChosenChallenge = res.body.challenges.filter(x => {
return x.type === challengeTypeArg
})[0]
/**
* the key is needed to accept the challenge
*/
let authKey: string = plugins.rawacme.keyAuthz(
preChosenChallenge.token,
this.parentAcmeAccount.parentSmartAcme.keyPair.publicKey
)
/**
* needed in case selected challenge is of type dns-01
*/
this.dnsKeyHash = plugins.rawacme.dnsKeyAuthzHash(authKey) // needed if dns challenge is chosen
/**
* the return challenge
*/
this.chosenChallenge = {
uri: preChosenChallenge.uri,
type: preChosenChallenge.type,
token: preChosenChallenge.token,
keyAuthorization: authKey,
status: preChosenChallenge.status,
dnsKeyHash: this.dnsKeyHash,
domainName: this.domainName,
domainNamePrefixed: helpers.prefixName(this.domainName)
}
done.resolve(this.chosenChallenge)
}
/**
* the key is needed to accept the challenge
*/
let authKey: string = plugins.rawacme.keyAuthz(
preChosenChallenge.token,
this.parentAcmeAccount.parentSmartAcme.keyPair.publicKey
)
return done.promise
}
/**
* checks if DNS records are set, will go through a max of 30 cycles
*/
async checkDns(cycleArg = 1) {
let result = await myDnsly.checkUntilAvailable(helpers.prefixName(this.domainName), 'TXT', this.dnsKeyHash)
if (result) {
console.log('DNS is set!')
return
/**
* needed in case selected challenge is of type dns-01
*/
this.dnsKeyHash = plugins.rawacme.dnsKeyAuthzHash(authKey) // needed if dns challenge is chosen
/**
* the return challenge
*/
this.chosenChallenge = {
uri: preChosenChallenge.uri,
type: preChosenChallenge.type,
token: preChosenChallenge.token,
keyAuthorization: authKey,
status: preChosenChallenge.status,
dnsKeyHash: this.dnsKeyHash,
domainName: this.domainName,
domainNamePrefixed: helpers.prefixName(this.domainName)
}
done.resolve(this.chosenChallenge)
}
)
return done.promise
}
/**
* checks if DNS records are set, will go through a max of 30 cycles
*/
async checkDns(cycleArg = 1) {
let result = await myDnsly.checkUntilAvailable(helpers.prefixName(this.domainName), 'TXT', this.dnsKeyHash)
if (result) {
console.log('DNS is set!')
return
} else {
throw new Error('DNS not set!')
}
}
/**
* validates a challenge, only call after you have set the challenge at the expected location
*/
async requestValidation() {
let makeRequest = () => {
let done = q.defer()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.poll(this.chosenChallenge.uri, async (err, res) => {
if (err) {
console.log(err)
return
}
console.log(`Validation response:`)
console.log(JSON.stringify(res.body))
if (res.body.status === 'pending' || res.body.status === 'invalid') {
await plugins.smartdelay.delayFor(3000)
makeRequest().then((x: any) => { done.resolve(x) })
} else {
throw new Error('DNS not set!')
console.log('perfect!')
done.resolve(res.body)
}
})
return done.promise
}
await makeRequest()
}
/**
* validates a challenge, only call after you have set the challenge at the expected location
*/
async requestValidation() {
let makeRequest = () => {
let done = q.defer()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.poll(this.chosenChallenge.uri, async (err, res) => {
if (err) {
console.log(err)
return
}
console.log(`Validation response:`)
console.log(JSON.stringify(res.body))
if (res.body.status === 'pending' || res.body.status === 'invalid') {
await plugins.smartdelay.delayFor(3000)
makeRequest().then((x: any) => { done.resolve(x) })
} else {
console.log('perfect!')
done.resolve(res.body)
}
})
return done.promise
}
await makeRequest()
}
/**
* requests a certificate
*/
requestCert() {
let done = q.defer()
let payload = {
csr: plugins.rawacme.base64.encode(
plugins.rawacme.toDer(
plugins.nodeForge.pki.certificationRequestToPem(
this.csr
)
)
),
notBefore: this.validFrom.toISOString(),
notAfter: this.validTo.toISOString()
}
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.newCert(
payload,
helpers.createKeypair(),
(err, res) => {
if (err) {
console.log(err)
done.reject(err)
}
console.log(res.body)
done.resolve(res.body)
})
return done.promise
}
/**
* getCertificate - takes care of cooldown, validation polling and certificate retrieval
*/
getCertificate() {
}
/**
* accept a challenge - for private use only
*/
acceptChallenge() {
let done = q.defer()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.post(
this.chosenChallenge.uri,
{
resource: 'challenge',
keyAuthorization: this.chosenChallenge.keyAuthorization
},
this.parentAcmeAccount.parentSmartAcme.keyPair,
(err, res) => {
if (err) {
console.log(err)
done.reject(err)
}
done.resolve(res.body)
}
/**
* requests a certificate
*/
requestCert() {
let done = q.defer()
let payload = {
csr: plugins.rawacme.base64.encode(
plugins.rawacme.toDer(
plugins.nodeForge.pki.certificationRequestToPem(
this.csr
)
)
return done.promise
),
notBefore: this.validFrom.toISOString(),
notAfter: this.validTo.toISOString()
}
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.newCert(
payload,
helpers.createKeypair(),
(err, res) => {
if (err) {
console.log(err)
done.reject(err)
}
console.log(res.body)
done.resolve(res.body)
})
return done.promise
}
/**
* getCertificate - takes care of cooldown, validation polling and certificate retrieval
*/
getCertificate() {
}
/**
* accept a challenge - for private use only
*/
acceptChallenge() {
let done = q.defer()
this.parentAcmeAccount.parentSmartAcme.rawacmeClient.post(
this.chosenChallenge.uri,
{
resource: 'challenge',
keyAuthorization: this.chosenChallenge.keyAuthorization
},
this.parentAcmeAccount.parentSmartAcme.keyPair,
(err, res) => {
if (err) {
console.log(err)
done.reject(err)
}
done.resolve(res.body)
}
)
return done.promise
}
}

View File

@ -1,5 +1,5 @@
// third party modules
import * as q from 'q' // promises
import * as q from 'smartq' // promises
import * as plugins from './smartacme.plugins'
import * as helpers from './smartacme.helpers'
@ -9,8 +9,8 @@ import { AcmeAccount } from './smartacme.classes.acmeaccount'
* a rsa keypair needed for account creation and subsequent requests
*/
export interface IRsaKeypair {
publicKey: string
privateKey: string
publicKey: string
privateKey: string
}
export { AcmeAccount } from './smartacme.classes.acmeaccount'
@ -20,63 +20,63 @@ export { AcmeCert, ISmartAcmeChallenge, ISmartAcmeChallengeChosen } from './smar
* class SmartAcme exports methods for maintaining SSL Certificates
*/
export class SmartAcme {
acmeUrl: string // the acme url to use for this instance
productionBool: boolean // a boolean to quickly know wether we are in production or not
keyPair: IRsaKeypair // the keyPair needed for account creation
rawacmeClient
acmeUrl: string // the acme url to use for this instance
productionBool: boolean // a boolean to quickly know wether we are in production or not
keyPair: IRsaKeypair // the keyPair needed for account creation
rawacmeClient
/**
* the constructor for class SmartAcme
*/
constructor(productionArg: boolean = false) {
this.productionBool = productionArg
this.keyPair = helpers.createKeypair()
if (this.productionBool) {
this.acmeUrl = plugins.rawacme.LETSENCRYPT_URL
} else {
this.acmeUrl = plugins.rawacme.LETSENCRYPT_STAGING_URL
/**
* the constructor for class SmartAcme
*/
constructor(productionArg: boolean = false) {
this.productionBool = productionArg
this.keyPair = helpers.createKeypair()
if (this.productionBool) {
this.acmeUrl = plugins.rawacme.LETSENCRYPT_URL
} else {
this.acmeUrl = plugins.rawacme.LETSENCRYPT_STAGING_URL
}
}
/**
* init the smartacme instance
*/
init() {
let done = q.defer()
plugins.rawacme.createClient(
{
url: this.acmeUrl,
publicKey: this.keyPair.publicKey,
privateKey: this.keyPair.privateKey
},
(err, client) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
}
/**
* init the smartacme instance
*/
init() {
let done = q.defer()
plugins.rawacme.createClient(
{
url: this.acmeUrl,
publicKey: this.keyPair.publicKey,
privateKey: this.keyPair.privateKey
},
(err, client) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
// make client available in class
this.rawacmeClient = client
done.resolve()
}
)
return done.promise
}
// make client available in class
this.rawacmeClient = client
done.resolve()
}
)
return done.promise
}
/**
* creates an account if not currently present in module
* @executes ASYNC
*/
createAcmeAccount() {
let done = q.defer<AcmeAccount>()
let acmeAccount = new AcmeAccount(this)
acmeAccount.register().then(() => {
return acmeAccount.agreeTos()
}).then(() => {
done.resolve(acmeAccount)
})
return done.promise
}
/**
* creates an account if not currently present in module
* @executes ASYNC
*/
createAcmeAccount() {
let done = q.defer<AcmeAccount>()
let acmeAccount = new AcmeAccount(this)
acmeAccount.register().then(() => {
return acmeAccount.agreeTos()
}).then(() => {
done.resolve(acmeAccount)
})
return done.promise
}
}

View File

@ -1,5 +1,5 @@
import 'typings-global'
import * as q from 'q'
import * as q from 'smartq'
import * as plugins from './smartacme.plugins'
@ -10,18 +10,18 @@ import { AcmeAccount } from './smartacme.classes.acmeaccount'
* creates a keypair to use with requests and to generate JWK from
*/
export let createKeypair = (bit = 2048): IRsaKeypair => {
let result = plugins.rsaKeygen.generate(bit)
return {
publicKey: result.public_key,
privateKey: result.private_key
}
let result = plugins.rsaKeygen.generate(bit)
return {
publicKey: result.public_key,
privateKey: result.private_key
}
}
/**
* prefix a domain name to make sure it complies with letsencrypt
*/
export let prefixName = (domainNameArg: string): string => {
return '_acme-challenge.' + domainNameArg
return '_acme-challenge.' + domainNameArg
}
/**
@ -29,22 +29,22 @@ export let prefixName = (domainNameArg: string): string => {
* @executes ASYNC
*/
let getReg = (SmartAcmeArg: SmartAcme, location: string) => {
let done = q.defer()
let body = { resource: 'reg' }
SmartAcmeArg.rawacmeClient.post(
location,
body,
SmartAcmeArg.keyPair,
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
console.log(JSON.stringify(res.body))
done.resolve()
}
)
return done.promise
let done = q.defer()
let body = { resource: 'reg' }
SmartAcmeArg.rawacmeClient.post(
location,
body,
SmartAcmeArg.keyPair,
(err, res) => {
if (err) {
console.error('smartacme: something went wrong:')
console.log(err)
done.reject(err)
return
}
console.log(JSON.stringify(res.body))
done.resolve()
}
)
return done.promise
}

View File

@ -12,11 +12,11 @@ import * as smartfile from 'smartfile'
import * as smartstring from 'smartstring'
export {
dnsly,
rsaKeygen,
rawacme,
nodeForge,
smartdelay,
smartfile,
smartstring
dnsly,
rsaKeygen,
rawacme,
nodeForge,
smartdelay,
smartfile,
smartstring
}

View File