prepare switch to le-acme-core

This commit is contained in:
Philipp Kunz 2016-11-09 18:01:31 +01:00
parent 11f12d7c0e
commit 7bfc4e279f
5 changed files with 321 additions and 318 deletions

View File

@ -1,5 +1,6 @@
/// <reference types="q" /> /// <reference types="q" />
import * as q from 'q'; import * as q from 'q';
import { JWebClient } from './smartacme.classes.jwebclient';
import { IReqResArg } from './smartacme.classes.jwebclient'; import { IReqResArg } from './smartacme.classes.jwebclient';
/** /**
* @class AcmeClient * @class AcmeClient
@ -15,7 +16,7 @@ export declare class AcmeClient {
directoryUrl: string; directoryUrl: string;
emailDefaultPrefix: string; emailDefaultPrefix: string;
emailOverride: string; emailOverride: string;
jWebClient: any; jWebClient: JWebClient;
regLink: string; regLink: string;
tosLink: string; tosLink: string;
webroot: string; webroot: string;
@ -34,7 +35,7 @@ export declare class AcmeClient {
* @param {Object} payload * @param {Object} payload
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
newRegistration(payload: any, callback: any): void; newRegistration(payload: any): q.Promise<{}>;
/** /**
* getRegistration * getRegistration
* @description get information about registration * @description get information about registration
@ -49,14 +50,14 @@ export declare class AcmeClient {
* @param {string} domain * @param {string} domain
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
authorizeDomain(domain: any, callback: any): void; authorizeDomain(domain: any): q.Promise<{}>;
/** /**
* acceptChallenge * acceptChallenge
* @description tell server which challenge will be accepted * @description tell server which challenge will be accepted
* @param {Object} challenge * @param {Object} challenge
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
acceptChallenge(challenge: any, callback: any): void; acceptChallenge(challenge?: {}): q.Promise<{}>;
/** /**
* pollUntilValid * pollUntilValid
* @description periodically (with exponential back-off) check status of challenge * @description periodically (with exponential back-off) check status of challenge
@ -64,7 +65,7 @@ export declare class AcmeClient {
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
* @param {number} retry - factor of delay * @param {number} retry - factor of delay
*/ */
pollUntilValid(uri: any, callback: any, retry?: number): void; pollUntilValid(uri: any, retry?: number): q.Promise<{}>;
/** /**
* pollUntilIssued * pollUntilIssued
* @description periodically (with exponential back-off) check status of CSR * @description periodically (with exponential back-off) check status of CSR
@ -72,14 +73,14 @@ export declare class AcmeClient {
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
* @param {number} retry - factor of delay * @param {number} retry - factor of delay
*/ */
pollUntilIssued(uri: any, callback: any, retry?: number): void; pollUntilIssued(uri: any, retry?: number): q.Promise<{}>;
/** /**
* requestSigning * requestSigning
* @description send CSR * @description send CSR
* @param {string} domain - expected to be already sanitized * @param {string} domain - expected to be already sanitized
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
requestSigning(commonName: any, callback: any): q.Promise<{}>; requestSigning(commonName: any): q.Promise<{}>;
/** /**
* retrieves profile of user (will make directory lookup and registration check) * retrieves profile of user (will make directory lookup and registration check)
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
@ -91,14 +92,14 @@ export declare class AcmeClient {
* @param {string} email * @param {string} email
* @param {function} callback - first argument will be the registration URI * @param {function} callback - first argument will be the registration URI
*/ */
createAccount(email: any, callback: any): void; createAccount(email: string): q.Promise<{}>;
/** /**
* agreeTos * agreeTos
* @description agree with terms of service (update agreement status in profile) * @description agree with terms of service (update agreement status in profile)
* @param {string} tosLink * @param {string} tosLink
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
agreeTos(tosLink: any, callback: any): void; agreeTos(tosLink: any): q.Promise<{}>;
/** /**
* Entry-Point: Request certificate * Entry-Point: Request certificate
*/ */

File diff suppressed because one or more lines are too long

View File

@ -14,6 +14,6 @@ describe('smartacme', function(){
}) })
it('should register a new account', function() { it('should register a new account', function() {
testAcme.createAccount() testAcme.createAccount().catch()
}) })
}) })

View File

@ -32,7 +32,7 @@ export class AcmeClient {
directoryUrl: string directoryUrl: string
emailDefaultPrefix: string emailDefaultPrefix: string
emailOverride: string emailOverride: string
jWebClient: any jWebClient = new JWebClient()
regLink: string regLink: string
tosLink: string tosLink: string
webroot: string webroot: string
@ -72,11 +72,6 @@ export class AcmeClient {
* @desc Email address to use * @desc Email address to use
*/ */
this.emailOverride = null // {string} this.emailOverride = null // {string}
/**
* @member {module:JWebClient~JWebClient} module:AcmeClient~AcmeClient#jWebClient
* @desc Reference to JSON-Web-Client
*/
this.jWebClient = new JWebClient() // {JWebClient}
/** /**
* @member {string} module:AcmeClient~AcmeClient#regLink * @member {string} module:AcmeClient~AcmeClient#regLink
* @desc Cached registration URI * @desc Cached registration URI
@ -131,15 +126,14 @@ export class AcmeClient {
* @param {Object} payload * @param {Object} payload
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
newRegistration(payload, callback) { newRegistration(payload) {
let done = q.defer()
if (!(payload instanceof Object)) { if (!(payload instanceof Object)) {
payload = {} // ensure payload is object payload = {} // ensure payload is object
} }
payload.resource = 'new-reg' payload.resource = 'new-reg'
this.jWebClient.post(this.directory['new-reg'], payload, callback, callback) this.jWebClient.post(this.directory['new-reg'], payload)
// dereference return done.promise
callback = null
payload = null
} }
/** /**
@ -152,29 +146,30 @@ export class AcmeClient {
getRegistration(uri, payload) { getRegistration(uri, payload) {
let done = q.defer<IReqResArg>() let done = q.defer<IReqResArg>()
payload['resource'] = 'reg' payload['resource'] = 'reg'
this.jWebClient.post(uri, payload, (ans, res) => { this.jWebClient.post(uri, payload)
if (ans instanceof Object) { .then((reqResArg: IReqResArg) => {
this.clientProfilePubKey = ans.key // cache or reset returned public key if (reqResArg.ans instanceof Object) {
if ((res instanceof Object) && (res['headers'] instanceof Object)) { this.clientProfilePubKey = reqResArg.ans.key // cache or reset returned public key
let linkStr = res.headers['link'] if ((reqResArg.res instanceof Object) && (reqResArg.res['headers'] instanceof Object)) {
if (typeof linkStr === 'string') { let linkStr = reqResArg.res.headers['link']
let tosLink = this.getTosLink(linkStr) if (typeof linkStr === 'string') {
if (typeof tosLink === 'string') { let tosLink = this.getTosLink(linkStr)
this.tosLink = tosLink // cache TOS link if (typeof tosLink === 'string') {
this.tosLink = tosLink // cache TOS link
} else {
this.tosLink = null // reset TOS link
}
} else { } else {
this.tosLink = null // reset TOS link this.tosLink = null // reset TOS link
} }
} else { } else {
this.tosLink = null // reset TOS link this.tosLink = null // reset TOS link
} }
done.resolve({ ans: reqResArg.ans, res: reqResArg.res })
} else { } else {
this.tosLink = null // reset TOS link done.reject(new Error('some error'))
} }
done.resolve({ ans: ans, res: res }) })
} else {
done.reject(new Error('some error'))
}
})
return done.promise return done.promise
} }
@ -184,65 +179,71 @@ export class AcmeClient {
* @param {string} domain * @param {string} domain
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
authorizeDomain(domain, callback) { authorizeDomain(domain) {
/*jshint -W069 */ let done = q.defer()
if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function
}
this.getProfile() this.getProfile()
.then(profile => { .then(profile => {
if (!(profile instanceof Object)) { if (!(profile instanceof Object)) {
callback(false) // no profile returned done.reject(new Error('no profile returned'))
} else { } else {
this.jWebClient.post(this.directory['new-authz'], this.makeDomainAuthorizationRequest(domain), (ans, res) => { this.jWebClient.post(this.directory['new-authz'], this.makeDomainAuthorizationRequest(domain))
if ((res instanceof Object) && (res['statusCode'] === 403)) { // if unauthorized .then((reqResArg: IReqResArg) => {
this.agreeTos(this.tosLink, (ans_, res_) => { // agree to TOS if ((reqResArg.res instanceof Object) && (reqResArg.res['statusCode'] === 403)) { // if unauthorized
if ( // if TOS were agreed successfully this.agreeTos(this.tosLink)
(res_ instanceof Object) .then((reqResArg2: IReqResArg) => { // agree to TOS
&& (res_['statusCode'] >= 200) if ( // if TOS were agreed successfully
&& (res_['statusCode'] <= 400) (reqResArg.res instanceof Object)
) { && (reqResArg2.res['statusCode'] >= 200)
this.authorizeDomain(domain, callback) // try authorization again && (reqResArg2.res['statusCode'] <= 400)
} else { ) {
callback(false) // agreement failed this.authorizeDomain(domain).then(() => {
} done.resolve()
}) }) // try authorization again
} else { } else {
if ( done.reject(false) // agreement failed
(res instanceof Object) }
&& (res['headers'] instanceof Object)
&& (typeof res.headers['location'] === 'string')
&& (ans instanceof Object)
) {
let poll_uri = res.headers['location'] // status URI for polling
let challenge = this.selectChallenge(ans, 'http-01') // select simple http challenge
if (challenge instanceof Object) { // desired challenge is in list
this.prepareChallenge(domain, challenge, () => { // prepare all objects and files for challenge
// reset
ans = null
res = null
// accept challenge
this.acceptChallenge(challenge, (ans, res) => {
if (
(res instanceof Object)
&& (res['statusCode'] < 400) // server confirms challenge acceptance
) {
this.pollUntilValid(poll_uri, callback) // poll status until server states success
} else {
callback(false) // server did not confirm challenge acceptance
}
})
}) })
} else {
callback(false) // desired challenge is not in list
}
} else { } else {
callback(false) // server did not respond with status URI if (
(reqResArg.res instanceof Object)
&& (reqResArg.res['headers'] instanceof Object)
&& (typeof reqResArg.res.headers['location'] === 'string')
&& (reqResArg.ans instanceof Object)
) {
let poll_uri = reqResArg.res.headers['location'] // status URI for polling
let challenge = this.selectChallenge(reqResArg.ans, 'http-01') // select simple http challenge
if (challenge instanceof Object) { // desired challenge is in list
this.prepareChallenge(domain, challenge, () => { // prepare all objects and files for challenge
// reset
reqResArg.ans = null
reqResArg.res = null
// accept challenge
this.acceptChallenge(challenge)
.then((reqResArg2: IReqResArg) => {
if (
(reqResArg2.res instanceof Object)
&& (reqResArg2.res['statusCode'] < 400) // server confirms challenge acceptance
) {
this.pollUntilValid(poll_uri)
.then(() => {
done.resolve()
}) // poll status until server states success
} else {
done.reject(false) // server did not confirm challenge acceptance
}
})
})
} else {
done.reject(false) // desired challenge is not in list
}
} else {
done.reject(false) // server did not respond with status URI
}
} }
} })
})
} }
}) })
return done.promise
} }
/** /**
@ -251,15 +252,13 @@ export class AcmeClient {
* @param {Object} challenge * @param {Object} challenge
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
acceptChallenge(challenge, callback) { acceptChallenge(challenge = {}) {
/*jshint -W069 */ let done = q.defer()
if (!(challenge instanceof Object)) { this.jWebClient.post(challenge['uri'], this.makeChallengeResponse(challenge))
challenge = {} // ensure challenge is object .then(() => {
} done.resolve()
this.jWebClient.post(challenge['uri'], this.makeChallengeResponse(challenge), callback) })
// dereference return done.promise
callback = null
challenge = null
} }
/** /**
@ -269,28 +268,27 @@ export class AcmeClient {
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
* @param {number} retry - factor of delay * @param {number} retry - factor of delay
*/ */
pollUntilValid(uri, callback, retry = 1) { pollUntilValid(uri, retry = 1) {
/*jshint -W069 */ let done = q.defer()
if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function
}
if (retry > 128) { if (retry > 128) {
callback(false) // stop if retry value exceeds maximum done.reject(false) // stop if retry value exceeds maximum
} else { } else {
this.jWebClient.get(uri, (ans, res) => { this.jWebClient.get(uri)
if (!(ans instanceof Object)) { .then((reqResArg) => {
callback(false) // invalid answer if (!(reqResArg.ans instanceof Object)) {
} else { done.reject(false) // invalid answer
if (ans['status'] === 'pending') { // still pending
setTimeout(() => {
this.pollUntilValid(uri, callback, retry * 2) // retry
}, retry * 500)
} else { } else {
callback(ans, res) // challenge complete if (reqResArg.ans['status'] === 'pending') { // still pending
setTimeout(() => {
this.pollUntilValid(uri, retry * 2) // retry
}, retry * 500)
} else {
done.resolve() // challenge complete
}
} }
} })
})
} }
return done.promise
} }
/** /**
@ -300,28 +298,27 @@ export class AcmeClient {
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
* @param {number} retry - factor of delay * @param {number} retry - factor of delay
*/ */
pollUntilIssued(uri, callback, retry = 1) { pollUntilIssued(uri, retry = 1) {
/*jshint -W069 */ let done = q.defer()
if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function
}
if (retry > 128) { if (retry > 128) {
callback(false) // stop if retry value exceeds maximum done.reject(false) // stop if retry value exceeds maximum
} else { } else {
this.jWebClient.get(uri, (ans, res) => { this.jWebClient.get(uri)
if ((ans instanceof Buffer) && (ans.length > 0)) { .then((reqResArg: IReqResArg) => {
callback(ans) // certificate was returned with answer if ((reqResArg.ans instanceof Buffer) && (reqResArg.ans.length > 0)) {
} else { done.resolve(reqResArg.ans) // certificate was returned with answer
if ((res instanceof Object) && (res['statusCode'] < 400)) { // still pending
setTimeout(() => {
this.pollUntilIssued(uri, callback, retry * 2) // retry
}, retry * 500)
} else { } else {
callback(false) // CSR complete if ((reqResArg.res instanceof Object) && (reqResArg.res['statusCode'] < 400)) { // still pending
setTimeout(() => {
this.pollUntilIssued(uri, retry * 2) // retry
}, retry * 500)
} else {
done.reject(false) // CSR complete
}
} }
} })
})
} }
return done.promise
} }
/** /**
@ -330,37 +327,37 @@ export class AcmeClient {
* @param {string} domain - expected to be already sanitized * @param {string} domain - expected to be already sanitized
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
requestSigning(commonName, callback) { requestSigning(commonName) {
let done = q.defer() let done = q.defer()
fs.readFile(commonName + '.csr', (err, csrBuffer: Buffer) => { fs.readFile(commonName + '.csr', (err, csrBuffer: Buffer) => {
if (err instanceof Object) { // file system error if (err instanceof Object) { // file system error
if (this.jWebClient.verbose) { if (this.jWebClient.verbose) {
console.error('Error : File system error', err['code'], 'while reading key from file') console.error('Error : File system error', err['code'], 'while reading key from file')
} }
callback(false) done.reject(false)
} else { } else {
let csr = csrBuffer.toString() let csr = csrBuffer.toString()
this.jWebClient.post(this.directory['new-cert'], this.makeCertRequest(csr, this.daysValid), (ans, res) => { this.jWebClient.post(this.directory['new-cert'], this.makeCertRequest(csr, this.daysValid))
if ((ans instanceof Buffer) && (ans.length > 0)) { // answer is buffer .then((reqResArg: IReqResArg) => {
callback(ans) // certificate was returned with answer if ((reqResArg.ans instanceof Buffer) && (reqResArg.ans.length > 0)) { // answer is buffer
} else { done.resolve(reqResArg.ans) // certificate was returned with answer
if (res instanceof Object) {
if ((res['statusCode'] < 400) && !ans) { // success response, but no answer was provided
let headers = res['headers']
if (!(headers instanceof Object)) {
headers = {} // ensure headers is object
}
this.pollUntilIssued(headers['location'], callback) // poll provided status URI
// dereference
headers = null
} else {
callback((res['statusCode'] < 400) ? ans : false) // answer may be provided as string or object
}
} else { } else {
callback(false) // invalid response if (reqResArg.res instanceof Object) {
if ((reqResArg.res['statusCode'] < 400) && !reqResArg.ans) { // success response, but no answer was provided
let headers = reqResArg['headers']
if (!(headers instanceof Object)) {
headers = {} // ensure headers is object
}
this.pollUntilIssued(headers['location'])
.then(x => { done.resolve(x) })
} else {
done.resolve((reqResArg.res['statusCode'] < 400) ? reqResArg.ans : false) // answer may be provided as string or object
}
} else {
done.reject(false) // invalid response
}
} }
} })
})
} }
}) })
return done.promise return done.promise
@ -378,21 +375,22 @@ export class AcmeClient {
done.reject(new Error('server did not respond with directory')) done.reject(new Error('server did not respond with directory'))
} else { } else {
this.directory = dir // cache directory this.directory = dir // cache directory
this.newRegistration(null, (ans, res) => { // try new registration to get registration link this.newRegistration(null)
if ( .then((reqResArg: IReqResArg) => { // try new registration to get registration link
(res instanceof Object) if (
&& (res['headers'] instanceof Object) (reqResArg.res instanceof Object)
&& (typeof res.headers['location'] === 'string') && (reqResArg.res['headers'] instanceof Object)
) { && (typeof reqResArg.res.headers['location'] === 'string')
this.regLink = res.headers['location'] ) {
this.getRegistration(this.regLink, null) this.regLink = reqResArg.res.headers['location']
.then((reqResArg: IReqResArg) => { this.getRegistration(this.regLink, null)
done.resolve() .then((reqResArg: IReqResArg) => {
}) // get registration info from link done.resolve()
} else { }) // get registration info from link
done.reject(new Error('registration failed')) } else {
} done.reject(new Error('registration failed'))
}) }
})
} }
}) })
return done.promise return done.promise
@ -404,34 +402,32 @@ export class AcmeClient {
* @param {string} email * @param {string} email
* @param {function} callback - first argument will be the registration URI * @param {function} callback - first argument will be the registration URI
*/ */
createAccount(email, callback) { createAccount(email: string) {
/*jshint -W069 */ let done = q.defer()
if (typeof email === 'string') { if (typeof email === 'string') {
if (typeof callback !== 'function') { this.newRegistration({
callback = this.emptyCallback // ensure callback is function contact: [
} 'mailto:' + email
this.newRegistration( ]
{ })
contact: [ .then((reqResArg: IReqResArg) => {
'mailto:' + email
]
},
(ans, res) => {
if ( if (
(res instanceof Object) (reqResArg.res instanceof Object)
&& (res['statusCode'] === 201) && (reqResArg.res['statusCode'] === 201)
&& (res['headers'] instanceof Object) && (reqResArg.res['headers'] instanceof Object)
&& (typeof res.headers['location'] === 'string') && (typeof reqResArg.res.headers['location'] === 'string')
) { ) {
this.regLink = res.headers['location'] this.regLink = reqResArg.res.headers['location']
callback(this.regLink) // registration URI done.resolve(this.regLink) // registration URI
} else { } else {
callback(false) // registration failed done.reject(new Error('could not register new account')) // registration failed
} }
}) })
} else { } else {
callback(false) // no email address provided done.reject(new Error('no email address provided'))
} }
return done.promise
} }
/** /**
@ -440,11 +436,14 @@ export class AcmeClient {
* @param {string} tosLink * @param {string} tosLink
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
agreeTos(tosLink, callback) { agreeTos(tosLink) {
let done = q.defer() let done = q.defer()
this.getRegistration(this.regLink, { this.getRegistration(this.regLink, {
'Agreement': tosLink // terms of service URI 'Agreement': tosLink // terms of service URI
}).then(() => { done.resolve() }) }).then(() => {
done.resolve()
})
return done.promise
} }
/** /**
@ -468,22 +467,23 @@ export class AcmeClient {
emailAddress: email emailAddress: email
}) })
.then(() => { .then(() => {
this.requestSigning(domainArg, (cert) => { // send CSR this.requestSigning(domainArg)
if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data .then((cert) => { // send CSR
fs.writeFile(domainArg + '.der', cert, (err) => { // sanitize domain name for file path if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data
if (err instanceof Object) { // file system error fs.writeFile(domainArg + '.der', cert, (err) => { // sanitize domain name for file path
if (this.jWebClient.verbose) { if (err instanceof Object) { // file system error
console.error('Error : File system error', err['code'], 'while writing certificate to file') if (this.jWebClient.verbose) {
console.error('Error : File system error', err['code'], 'while writing certificate to file')
}
done.reject(err)
} else {
done.resolve() // CSR complete and certificate written to file system
} }
done.reject(err) })
} else { } else {
done.resolve() // CSR complete and certificate written to file system done.reject('invalid certificate data')
} }
}) })
} else {
done.reject('invalid certificate data')
}
})
}) })
}) })

View File

@ -12,9 +12,9 @@ export class SmartAcme {
* creates an account * creates an account
*/ */
createAccount() { createAccount() {
this.acmeClient.createAccount('test@bleu.de',(answer) => { this.acmeClient.createAccount('test@bleu.de').then((answer) => {
console.log(answer) console.log(answer)
}) }).catch(err => { console.log(err) })
} }
/** /**