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,11 +146,12 @@ 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)) {
let linkStr = reqResArg.res.headers['link']
if (typeof linkStr === 'string') { if (typeof linkStr === 'string') {
let tosLink = this.getTosLink(linkStr) let tosLink = this.getTosLink(linkStr)
if (typeof tosLink === 'string') { if (typeof tosLink === 'string') {
@ -170,7 +165,7 @@ export class AcmeClient {
} else { } else {
this.tosLink = null // reset TOS link this.tosLink = null // reset TOS link
} }
done.resolve({ ans: ans, res: res }) done.resolve({ ans: reqResArg.ans, res: reqResArg.res })
} else { } else {
done.reject(new Error('some error')) done.reject(new Error('some error'))
} }
@ -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
this.agreeTos(this.tosLink)
.then((reqResArg2: IReqResArg) => { // agree to TOS
if ( // if TOS were agreed successfully if ( // if TOS were agreed successfully
(res_ instanceof Object) (reqResArg.res instanceof Object)
&& (res_['statusCode'] >= 200) && (reqResArg2.res['statusCode'] >= 200)
&& (res_['statusCode'] <= 400) && (reqResArg2.res['statusCode'] <= 400)
) { ) {
this.authorizeDomain(domain, callback) // try authorization again this.authorizeDomain(domain).then(() => {
done.resolve()
}) // try authorization again
} else { } else {
callback(false) // agreement failed done.reject(false) // agreement failed
} }
}) })
} else { } else {
if ( if (
(res instanceof Object) (reqResArg.res instanceof Object)
&& (res['headers'] instanceof Object) && (reqResArg.res['headers'] instanceof Object)
&& (typeof res.headers['location'] === 'string') && (typeof reqResArg.res.headers['location'] === 'string')
&& (ans instanceof Object) && (reqResArg.ans instanceof Object)
) { ) {
let poll_uri = res.headers['location'] // status URI for polling let poll_uri = reqResArg.res.headers['location'] // status URI for polling
let challenge = this.selectChallenge(ans, 'http-01') // select simple http challenge let challenge = this.selectChallenge(reqResArg.ans, 'http-01') // select simple http challenge
if (challenge instanceof Object) { // desired challenge is in list if (challenge instanceof Object) { // desired challenge is in list
this.prepareChallenge(domain, challenge, () => { // prepare all objects and files for challenge this.prepareChallenge(domain, challenge, () => { // prepare all objects and files for challenge
// reset // reset
ans = null reqResArg.ans = null
res = null reqResArg.res = null
// accept challenge // accept challenge
this.acceptChallenge(challenge, (ans, res) => { this.acceptChallenge(challenge)
.then((reqResArg2: IReqResArg) => {
if ( if (
(res instanceof Object) (reqResArg2.res instanceof Object)
&& (res['statusCode'] < 400) // server confirms challenge acceptance && (reqResArg2.res['statusCode'] < 400) // server confirms challenge acceptance
) { ) {
this.pollUntilValid(poll_uri, callback) // poll status until server states success this.pollUntilValid(poll_uri)
.then(() => {
done.resolve()
}) // poll status until server states success
} else { } else {
callback(false) // server did not confirm challenge acceptance done.reject(false) // server did not confirm challenge acceptance
} }
}) })
}) })
} else { } else {
callback(false) // desired challenge is not in list done.reject(false) // desired challenge is not in list
} }
} else { } else {
callback(false) // server did not respond with status URI 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)) {
done.reject(false) // invalid answer
} else { } else {
if (ans['status'] === 'pending') { // still pending if (reqResArg.ans['status'] === 'pending') { // still pending
setTimeout(() => { setTimeout(() => {
this.pollUntilValid(uri, callback, retry * 2) // retry this.pollUntilValid(uri, retry * 2) // retry
}, retry * 500) }, retry * 500)
} else { } else {
callback(ans, res) // challenge complete 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)) {
done.resolve(reqResArg.ans) // certificate was returned with answer
} else { } else {
if ((res instanceof Object) && (res['statusCode'] < 400)) { // still pending if ((reqResArg.res instanceof Object) && (reqResArg.res['statusCode'] < 400)) { // still pending
setTimeout(() => { setTimeout(() => {
this.pollUntilIssued(uri, callback, retry * 2) // retry this.pollUntilIssued(uri, retry * 2) // retry
}, retry * 500) }, retry * 500)
} else { } else {
callback(false) // CSR complete done.reject(false) // CSR complete
} }
} }
}) })
} }
return done.promise
} }
/** /**
@ -330,34 +327,34 @@ 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
done.resolve(reqResArg.ans) // certificate was returned with answer
} else { } else {
if (res instanceof Object) { if (reqResArg.res instanceof Object) {
if ((res['statusCode'] < 400) && !ans) { // success response, but no answer was provided if ((reqResArg.res['statusCode'] < 400) && !reqResArg.ans) { // success response, but no answer was provided
let headers = res['headers'] let headers = reqResArg['headers']
if (!(headers instanceof Object)) { if (!(headers instanceof Object)) {
headers = {} // ensure headers is object headers = {} // ensure headers is object
} }
this.pollUntilIssued(headers['location'], callback) // poll provided status URI this.pollUntilIssued(headers['location'])
// dereference .then(x => { done.resolve(x) })
headers = null
} else { } else {
callback((res['statusCode'] < 400) ? ans : false) // answer may be provided as string or object done.resolve((reqResArg.res['statusCode'] < 400) ? reqResArg.ans : false) // answer may be provided as string or object
} }
} else { } else {
callback(false) // invalid response done.reject(false) // invalid response
} }
} }
}) })
@ -378,13 +375,14 @@ 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)
.then((reqResArg: IReqResArg) => { // try new registration to get registration link
if ( if (
(res instanceof Object) (reqResArg.res instanceof Object)
&& (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']
this.getRegistration(this.regLink, null) this.getRegistration(this.regLink, null)
.then((reqResArg: IReqResArg) => { .then((reqResArg: IReqResArg) => {
done.resolve() done.resolve()
@ -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
}
this.newRegistration(
{
contact: [ contact: [
'mailto:' + email 'mailto:' + email
] ]
}, })
(ans, res) => { .then((reqResArg: IReqResArg) => {
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,7 +467,8 @@ export class AcmeClient {
emailAddress: email emailAddress: email
}) })
.then(() => { .then(() => {
this.requestSigning(domainArg, (cert) => { // send CSR this.requestSigning(domainArg)
.then((cert) => { // send CSR
if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data
fs.writeFile(domainArg + '.der', cert, (err) => { // sanitize domain name for file path fs.writeFile(domainArg + '.der', cert, (err) => { // sanitize domain name for file path
if (err instanceof Object) { // file system error if (err instanceof Object) { // file system error

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) })
} }
/** /**