update to use more promises

This commit is contained in:
Philipp Kunz 2016-11-03 18:57:42 +01:00
parent a2c6b6a259
commit e1f24823c6
10 changed files with 359 additions and 441 deletions

View File

@ -1,3 +1,6 @@
/// <reference types="q" />
import * as q from 'q';
import { IReqResArg } from './smartacme.classes.jwebclient';
/** /**
* @class AcmeClient * @class AcmeClient
* @constructor * @constructor
@ -7,7 +10,7 @@
*/ */
export declare class AcmeClient { export declare class AcmeClient {
clientProfilePubKey: any; clientProfilePubKey: any;
days_valid: number; daysValid: number;
defaultRsaKeySize: number; defaultRsaKeySize: number;
directory: any; directory: any;
directoryUrl: string; directoryUrl: string;
@ -17,7 +20,7 @@ export declare class AcmeClient {
regLink: string; regLink: string;
tosLink: string; tosLink: string;
webroot: string; webroot: string;
well_known_path: string; wellKnownPath: string;
withInteraction: boolean; withInteraction: boolean;
constructor(directoryUrlArg: any); constructor(directoryUrlArg: any);
/** /**
@ -25,7 +28,7 @@ export declare class AcmeClient {
* @description retrieve directory entries (directory url must be set prior to execution) * @description retrieve directory entries (directory url must be set prior to execution)
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
getDirectory(callback: any): void; getDirectory(): q.Promise<IReqResArg>;
/** /**
* newRegistration * newRegistration
* @description try to register (directory lookup must have occured prior to execution) * @description try to register (directory lookup must have occured prior to execution)
@ -40,7 +43,7 @@ export declare class AcmeClient {
* @param {Object} payload - update information * @param {Object} payload - update information
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
getRegistration(uri: any, payload: any, callback: any): void; getRegistration(uri: any, payload: any): q.Promise<IReqResArg>;
/** /**
* authorizeDomain * authorizeDomain
* @description authorize domain using challenge-response-method * @description authorize domain using challenge-response-method
@ -79,11 +82,10 @@ export declare class AcmeClient {
*/ */
requestSigning(domain: any, callback: any): void; requestSigning(domain: any, callback: any): void;
/** /**
* getProfile * retrieves profile of user (will make directory lookup and registration check)
* @description retrieve 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
*/ */
getProfile(callback: any): void; getProfile(): q.Promise<{}>;
/** /**
* createAccount * createAccount
* @description create new account (assumes directory lookup has already occured) * @description create new account (assumes directory lookup has already occured)
@ -104,8 +106,9 @@ export declare class AcmeClient {
* @param {string} organization * @param {string} organization
* @param {string} country * @param {string} country
* @param {function} callback * @param {function} callback
* @returns Promise
*/ */
requestCertificate(domain: any, organization: any, country: any, callback: any): void; requestCertificate(domain: string, organization: string, country: string): q.Promise<{}>;
/** /**
* External: Create key pair * External: Create key pair
* @param {number} bit - key strength, expected to be already sanitized * @param {number} bit - key strength, expected to be already sanitized
@ -115,7 +118,7 @@ export declare class AcmeClient {
* @param {string} e - email address, expected to be already sanitized * @param {string} e - email address, expected to be already sanitized
* @param {function} callback * @param {function} callback
*/ */
createKeyPair(bit: any, c: any, o: any, cn: any, e: any, callback: any): void; createKeyPair(bit: any, c: any, o: any, cn: any, e: any): q.Promise<{}>;
/** /**
* Helper: Empty callback * Helper: Empty callback
*/ */

File diff suppressed because one or more lines are too long

View File

@ -1,11 +1,27 @@
/// <reference types="q" />
import * as q from 'q';
export interface IReqResArg {
ans: any;
res: any;
}
/** /**
* @class JWebClient * @class JWebClient
* @constructor * @constructor
* @description Implementation of HTTPS-based JSON-Web-Client * @description Implementation of HTTPS-based JSON-Web-Client
*/ */
export declare class JWebClient { export declare class JWebClient {
key_pair: any; /**
last_nonce: string; * User account key pair
*/
keyPair: any;
/**
* Cached nonce returned with last request
*/
lastNonce: string;
/**
* @member {boolean} module:JWebClient~JWebClient#verbose
* @desc Determines verbose mode
*/
verbose: boolean; verbose: boolean;
constructor(); constructor();
/** /**
@ -27,7 +43,7 @@ export declare class JWebClient {
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
request(query: any, payload: any, callback: any, errorCallback: any): void; request(query: string, payload?: string): q.Promise<{}>;
/** /**
* get * get
* @description make GET request * @description make GET request
@ -35,27 +51,21 @@ export declare class JWebClient {
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
get(uri: any, callback: any, errorCallback: any): void; get(uri: string): q.Promise<IReqResArg>;
/** /**
* post * make POST request
* @description make POST request
* @param {string} uri * @param {string} uri
* @param {Object|string|number|boolean} payload * @param {Object|string|number|boolean} payload
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
post(uri: any, payload: any, callback: any, errorCallback: any): void; post(uri: string, payload: any): q.Promise<IReqResArg>;
/** /**
* evaluateStatus * checks if status is expected and log errors
* @description check if status is expected and log errors
* @param {string} uri * @param {string} uri
* @param {Object|string|number|boolean} payload * @param {Object|string|number|boolean} payload
* @param {Object|string} ans * @param {Object|string} ans
* @param {Object} res * @param {Object} res
*/ */
evaluateStatus(uri: any, payload: any, ans: any, res: any): void; evaluateStatus(uri: any, payload: any, ans: any, res: any): void;
/**
* Helper: Empty callback
*/
emptyCallback(): void;
} }

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,5 @@
import 'typings-global'; import 'typings-global';
import * as path from 'path'; import * as path from 'path';
import * as smartstring from 'smartstring'; import * as smartstring from 'smartstring';
export { path, smartstring }; import * as shelljs from 'shelljs';
export { path, smartstring, shelljs };

View File

@ -4,4 +4,6 @@ const path = require("path");
exports.path = path; exports.path = path;
const smartstring = require("smartstring"); const smartstring = require("smartstring");
exports.smartstring = smartstring; exports.smartstring = smartstring;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRhY21lLnBsdWdpbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9zbWFydGFjbWUucGx1Z2lucy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsMEJBQXVCO0FBQ3ZCLDZCQUE0QjtBQUl4QixvQkFBSTtBQUhSLDJDQUEwQztBQUl0QyxrQ0FBVyJ9 const shelljs = require("shelljs");
exports.shelljs = shelljs;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRhY21lLnBsdWdpbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9zbWFydGFjbWUucGx1Z2lucy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsMEJBQXVCO0FBQ3ZCLDZCQUE0QjtBQUt4QixvQkFBSTtBQUpSLDJDQUEwQztBQUt0QyxrQ0FBVztBQUpmLG1DQUFrQztBQUs5QiwwQkFBTyJ9

View File

@ -25,7 +25,9 @@
"dependencies": { "dependencies": {
"@types/base64url": "^2.0.3", "@types/base64url": "^2.0.3",
"jwa": "^1.1.3", "jwa": "^1.1.3",
"q": "^1.4.1",
"rsa-pem-to-jwk": "^1.1.3", "rsa-pem-to-jwk": "^1.1.3",
"shelljs": "^0.7.5",
"smartstring": "^2.0.20", "smartstring": "^2.0.20",
"typings-global": "^1.0.14" "typings-global": "^1.0.14"
}, },

View File

@ -1,9 +1,10 @@
import * as plugins from './smartacme.plugins' import * as plugins from './smartacme.plugins'
import * as child_process from 'child_process' import * as q from 'q'
import * as crypto from 'crypto' import * as crypto from 'crypto'
import * as fs from 'fs' import * as fs from 'fs'
import * as readline from 'readline' import * as readline from 'readline'
import { JWebClient } from './smartacme.classes.jwebclient' import { JWebClient } from './smartacme.classes.jwebclient'
import { IReqResArg } from './smartacme.classes.jwebclient'
/** /**
* json_to_utf8buffer * json_to_utf8buffer
@ -121,10 +122,13 @@ export class AcmeClient {
* @description retrieve directory entries (directory url must be set prior to execution) * @description retrieve directory entries (directory url must be set prior to execution)
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
getDirectory(callback) { getDirectory() {
this.jWebClient.get(this.directoryUrl, callback, callback) let done = q.defer<IReqResArg>()
// dereference this.jWebClient.get(this.directoryUrl)
callback = null .then((reqResArg: IReqResArg) => {
done.resolve(reqResArg)
})
return done.promise
} }
/** /**
@ -151,16 +155,10 @@ export class AcmeClient {
* @param {Object} payload - update information * @param {Object} payload - update information
* @param {function} callback - first argument will be the answer object * @param {function} callback - first argument will be the answer object
*/ */
getRegistration(uri, payload, callback) { getRegistration(uri, payload) {
/*jshint -W069 */ let done = q.defer<IReqResArg>()
if (!(payload instanceof Object)) {
payload = {} // ensure payload is object
}
payload['resource'] = 'reg' payload['resource'] = 'reg'
if (typeof callback !== 'function') { this.jWebClient.post(uri, payload, (ans, res) => {
callback = this.emptyCallback // ensure callback is function
}
this.jWebClient.post(uri, payload,(ans, res) => {
if (ans instanceof Object) { if (ans instanceof Object) {
this.clientProfilePubKey = ans.key // cache or reset returned public key this.clientProfilePubKey = ans.key // cache or reset returned public key
if ((res instanceof Object) && (res['headers'] instanceof Object)) { if ((res instanceof Object) && (res['headers'] instanceof Object)) {
@ -178,13 +176,12 @@ export class AcmeClient {
} else { } else {
this.tosLink = null // reset TOS link this.tosLink = null // reset TOS link
} }
callback(ans, res) done.resolve({ ans: ans, res: res })
} else { } else {
callback(false) done.reject(new Error('some error'))
} }
}) })
// dereference return done.promise
payload = null
} }
/** /**
@ -198,59 +195,60 @@ export class AcmeClient {
if (typeof callback !== 'function') { if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function callback = this.emptyCallback // ensure callback is function
} }
this.getProfile((profile) => { this.getProfile()
if (!(profile instanceof Object)) { .then(profile => {
callback(false) // no profile returned if (!(profile instanceof Object)) {
} else { callback(false) // no profile returned
this.jWebClient.post(this.directory['new-authz'], this.makeDomainAuthorizationRequest(domain), (ans, res) => { } else {
if ((res instanceof Object) && (res['statusCode'] === 403)) { // if unauthorized this.jWebClient.post(this.directory['new-authz'], this.makeDomainAuthorizationRequest(domain), (ans, res) => {
this.agreeTos(this.tosLink, (ans_, res_) => { // agree to TOS if ((res instanceof Object) && (res['statusCode'] === 403)) { // if unauthorized
if ( // if TOS were agreed successfully this.agreeTos(this.tosLink, (ans_, res_) => { // agree to TOS
(res_ instanceof Object) if ( // if TOS were agreed successfully
&& (res_['statusCode'] >= 200) (res_ instanceof Object)
&& (res_['statusCode'] <= 400) && (res_['statusCode'] >= 200)
) { && (res_['statusCode'] <= 400)
this.authorizeDomain(domain, callback) // try authorization again ) {
} else { this.authorizeDomain(domain, callback) // try authorization again
callback(false) // agreement failed } else {
} callback(false) // agreement failed
}) }
} else { })
if (
(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 (
(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 {
callback(false) // server did not respond with status URI
}
} }
} })
}) }
} })
})
} }
/** /**
@ -316,7 +314,7 @@ export class AcmeClient {
if (retry > 128) { if (retry > 128) {
callback(false) // stop if retry value exceeds maximum callback(false) // stop if retry value exceeds maximum
} else { } else {
this.jWebClient.get(uri,(ans, res) => { this.jWebClient.get(uri, (ans, res) => {
if ((ans instanceof Buffer) && (ans.length > 0)) { if ((ans instanceof Buffer) && (ans.length > 0)) {
callback(ans) // certificate was returned with answer callback(ans) // certificate was returned with answer
} else { } else {
@ -377,34 +375,35 @@ export class AcmeClient {
} }
/** /**
* getProfile * retrieves profile of user (will make directory lookup and registration check)
* @description retrieve 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
*/ */
getProfile(callback) { getProfile() {
/*jshint -W069 */ let done = q.defer()
if (typeof callback !== 'function') { this.getDirectory()
callback = this.emptyCallback // ensure callback is function .then((dir) => {
} if (!(dir instanceof Object)) {
this.getDirectory((dir) => { done.reject(new Error('server did not respond with directory'))
if (!(dir instanceof Object)) { } else {
callback(false) // server did not respond with directory this.directory = dir // cache directory
} else { this.newRegistration(null, (ans, res) => { // try new registration to get registration link
this.directory = dir // cache directory if (
this.newRegistration(null, (ans, res) => { // try new registration to get registration link (res instanceof Object)
if ( && (res['headers'] instanceof Object)
(res instanceof Object) && (typeof res.headers['location'] === 'string')
&& (res['headers'] instanceof Object) ) {
&& (typeof res.headers['location'] === 'string') this.regLink = res.headers['location']
) { this.getRegistration(this.regLink, null)
this.regLink = res.headers['location'] .then((reqResArg: IReqResArg) => {
this.getRegistration(this.regLink, null, callback) // get registration info from link done.resolve()
} else { }) // get registration info from link
callback(false) // registration failed } else {
} done.reject(new Error('registration failed'))
}) }
} })
}) }
})
return done.promise
} }
/** /**
@ -450,11 +449,10 @@ export class AcmeClient {
* @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, callback) {
let done = q.defer()
this.getRegistration(this.regLink, { this.getRegistration(this.regLink, {
'Agreement': tosLink // terms of service URI 'Agreement': tosLink // terms of service URI
}, callback) }).then(() => { done.resolve() })
// dereference
callback = null
} }
/** /**
@ -463,53 +461,43 @@ export class AcmeClient {
* @param {string} organization * @param {string} organization
* @param {string} country * @param {string} country
* @param {function} callback * @param {function} callback
* @returns Promise
*/ */
requestCertificate(domain, organization, country, callback) { requestCertificate(domain: string, organization: string, country: string) {
/*jshint -W069 */ let done = q.defer()
if (typeof domain !== 'string') { this.getProfile()
domain = '' // ensure domain is string .then((profile) => {
} let email = this.extractEmail(profile) // try to determine email address from profile
if (typeof callback !== 'function') { let bit = this.defaultRsaKeySize
callback = this.emptyCallback // ensure callback is function // sanitize
} bit = Number(bit)
this.getProfile((profile) => { country = this.makeSafeFileName(country)
let email = this.extractEmail(profile) // try to determine email address from profile domain = this.makeSafeFileName(domain)
if (typeof this.emailOverride === 'string') { email = this.makeSafeFileName(email)
email = this.emailOverride // override email address if set organization = this.makeSafeFileName(organization)
} else if (typeof email !== 'string') { // create key pair
email = this.emailDefaultPrefix + '@' + domain // or set default this.createKeyPair(bit, country, organization, domain, email)
} .then(() => { // create key pair
let bit = this.defaultRsaKeySize this.requestSigning(domain, (cert) => { // send CSR
// sanitize if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data
bit = Number(bit) fs.writeFile(domain + '.der', cert, (err) => { // sanitize domain name for file path
country = this.makeSafeFileName(country) if (err instanceof Object) { // file system error
domain = this.makeSafeFileName(domain) if (this.jWebClient.verbose) {
email = this.makeSafeFileName(email) console.error('Error : File system error', err['code'], 'while writing certificate to file')
organization = this.makeSafeFileName(organization) }
// create key pair done.reject(err)
this.createKeyPair(bit, country, organization, domain, email, (e) => { // create key pair } else {
if (!e) { done.resolve() // CSR complete and certificate written to file system
this.requestSigning(domain, (cert) => { // send CSR
if ((cert instanceof Buffer) || (typeof cert === 'string')) { // valid certificate data
fs.writeFile(domain + '.der', cert, (err) => { // sanitize domain name for file path
if (err instanceof Object) { // file system error
if (this.jWebClient.verbose) {
console.error('Error : File system error', err['code'], 'while writing certificate to file')
} }
callback(false) })
} else { } else {
callback(true) // CSR complete and certificate written to file system done.reject('invalid certificate data')
} }
}) })
} else {
callback(false) // invalid certificate data
}
}) })
} else {
callback(false) // could not create key pair
}
}) })
}) return done.promise
} }
/** /**
@ -521,27 +509,21 @@ export class AcmeClient {
* @param {string} e - email address, expected to be already sanitized * @param {string} e - email address, expected to be already sanitized
* @param {function} callback * @param {function} callback
*/ */
createKeyPair(bit, c, o, cn, e, callback) { createKeyPair(bit, c, o, cn, e) {
if (typeof callback !== 'function') { let done = q.defer()
callback = this.emptyCallback // ensure callback is function
}
let openssl = `openssl req -new -nodes -newkey rsa:${bit} -sha256 -subj "/C=${c}/O=${o}/CN=${cn}/emailAddress=${e}" -keyout \"${cn}.key\" -outform der -out \"${cn}.csr\"` let openssl = `openssl req -new -nodes -newkey rsa:${bit} -sha256 -subj "/C=${c}/O=${o}/CN=${cn}/emailAddress=${e}" -keyout \"${cn}.key\" -outform der -out \"${cn}.csr\"`
console.error('Action : Creating key pair') console.error('Action : Creating key pair')
if (this.jWebClient.verbose) { if (this.jWebClient.verbose) {
console.error('Running:', openssl) console.error('Running:', openssl)
} }
child_process.exec(openssl, (e) => { plugins.shelljs.exec(openssl, (codeArg, stdOutArg, stdErrorArg) => {
if (!e) { if (!stdErrorArg) {
console.error('Result : done') done.resolve()
} else { } else {
console.error('Result : failed') done.reject(stdErrorArg)
} }
callback(e) })
// dereference return done.promise
callback = null
e = null
}
)
} }
/** /**
@ -562,9 +544,9 @@ export class AcmeClient {
name = '' name = ''
} }
// respects file name restrictions for ntfs and ext2 // respects file name restrictions for ntfs and ext2
let regex_file = '[<>:\"/\\\\\\|\\?\\*\\u0000-\\u001f\\u007f\\u0080-\\u009f]' let regexFile = '[<>:\"/\\\\\\|\\?\\*\\u0000-\\u001f\\u007f\\u0080-\\u009f]'
let regex_path = '[<>:\"\\\\\\|\\?\\*\\u0000-\\u001f\\u007f\\u0080-\\u009f]' let regexPath = '[<>:\"\\\\\\|\\?\\*\\u0000-\\u001f\\u007f\\u0080-\\u009f]'
return name.replace(new RegExp(withPath ? regex_path : regex_file, 'g'), (charToReplace) => { return name.replace(new RegExp(withPath ? regexPath : regexFile, 'g'), (charToReplace) => {
if (typeof charToReplace === 'string') { if (typeof charToReplace === 'string') {
return '%' + charToReplace.charCodeAt(0).toString(16).toLocaleUpperCase() return '%' + charToReplace.charCodeAt(0).toString(16).toLocaleUpperCase()
} }

View File

@ -2,6 +2,12 @@ import * as plugins from './smartacme.plugins'
import * as https from 'https' import * as https from 'https'
let jwa = require('jwa') let jwa = require('jwa')
import * as url from 'url' import * as url from 'url'
import * as q from 'q'
export interface IReqResArg {
ans: any
res: any
}
/** /**
* json_to_utf8base64url * json_to_utf8base64url
@ -11,7 +17,7 @@ import * as url from 'url'
* @return {string} * @return {string}
* @throws Exception if object cannot be stringified or contains cycle * @throws Exception if object cannot be stringified or contains cycle
*/ */
let json_to_utf8base64url = function (obj) { let json_to_utf8base64url = (obj) => {
return plugins.smartstring.base64.encodeUri(JSON.stringify(obj)) return plugins.smartstring.base64.encodeUri(JSON.stringify(obj))
} }
@ -21,24 +27,22 @@ let json_to_utf8base64url = function (obj) {
* @description Implementation of HTTPS-based JSON-Web-Client * @description Implementation of HTTPS-based JSON-Web-Client
*/ */
export class JWebClient { export class JWebClient {
key_pair: any /**
last_nonce: string * User account key pair
*/
keyPair: any = {}
/**
* Cached nonce returned with last request
*/
lastNonce: string = null
/**
* @member {boolean} module:JWebClient~JWebClient#verbose
* @desc Determines verbose mode
*/
verbose: boolean verbose: boolean
constructor() { constructor() {
/**
* @member {Object} module:JWebClient~JWebClient#key_pair
* @desc User account key pair
*/
this.key_pair = {}
/**
* @member {string} module:JWebClient~JWebClient#last_nonce
* @desc Cached nonce returned with last request
*/
this.last_nonce = null
/**
* @member {boolean} module:JWebClient~JWebClient#verbose
* @desc Determines verbose mode
*/
this.verbose = false this.verbose = false
} }
@ -94,17 +98,8 @@ export class JWebClient {
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
request(query, payload, callback, errorCallback) { request(query: string, payload: string = null) {
/*jshint -W069 */ let done = q.defer()
if (typeof query !== 'string') {
query = '' // ensure query is string
}
if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function
}
if (typeof errorCallback !== 'function') {
errorCallback = this.emptyCallback // ensure callback is function
}
// prepare options // prepare options
let uri = url.parse(query) let uri = url.parse(query)
let options = { let options = {
@ -114,7 +109,7 @@ export class JWebClient {
method: null, method: null,
headers: {} headers: {}
} }
if (typeof payload === 'string') { if (!payload === null) {
options.method = 'POST' options.method = 'POST'
options.headers = { options.headers = {
'Content-Type': 'application/jose', 'Content-Type': 'application/jose',
@ -124,15 +119,15 @@ export class JWebClient {
options.method = 'GET' options.method = 'GET'
} }
// prepare request // prepare request
let req = https.request(options, function (res) { let req = https.request(options, (res) => {
// receive data // receive data
let data = [] let data = []
res.on('data', function (block) { res.on('data', (block) => {
if (block instanceof Buffer) { if (block instanceof Buffer) {
data.push(block) data.push(block)
} }
}) })
res.on('end', function () { res.on('end', () => {
let buf = Buffer.concat(data) let buf = Buffer.concat(data)
let isJSON = ( let isJSON = (
(res instanceof Object) (res instanceof Object)
@ -144,26 +139,25 @@ export class JWebClient {
try { try {
// convert to JSON // convert to JSON
let json = JSON.parse(buf.toString('utf8')) let json = JSON.parse(buf.toString('utf8'))
callback(json, res) done.resolve({ json: json, res: res })
} catch (e) { } catch (e) {
// error (if empty or invalid JSON) // error (if empty or invalid JSON)
errorCallback(void 0, e) done.reject(e)
} }
} else {
callback(buf, res)
} }
}) })
}).on('error', function (e) { }).on('error', (e) => {
console.error('Error occured', e) console.error('Error occured', e)
// error // error
errorCallback(void 0, e) done.reject(e)
}) })
// write POST body if payload was specified // write POST body if payload was specified
if (typeof payload === 'string') { if (!payload === null) {
req.write(payload) req.write(payload)
} }
// make request // make request
req.end() req.end()
return done.promise
} }
/** /**
@ -173,69 +167,55 @@ export class JWebClient {
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
get(uri, callback, errorCallback) { get(uri: string) {
/*jshint -W069 */ let done = q.defer<IReqResArg>()
let ctx = this this.request(uri)
if (typeof callback !== 'function') { .then((reqResArg: IReqResArg) => {
callback = this.emptyCallback // ensure callback is function this.evaluateStatus(uri, null, reqResArg.ans, reqResArg.res)
} // save replay nonce for later requests
this.request(uri, void 0, function (ans, res) { if ((reqResArg.res instanceof Object) && (reqResArg.res['headers'] instanceof Object)) {
ctx.evaluateStatus(uri, null, ans, res) this.lastNonce = reqResArg.res.headers['replay-nonce']
// save replay nonce for later requests }
if ((res instanceof Object) && (res['headers'] instanceof Object)) { done.resolve(reqResArg)
ctx.last_nonce = res.headers['replay-nonce'] })
} return done.promise
callback(ans, res)
// dereference
ans = null
callback = null
ctx = null
res = null
}, errorCallback)
// dereference
errorCallback = null
} }
/** /**
* post * make POST request
* @description make POST request
* @param {string} uri * @param {string} uri
* @param {Object|string|number|boolean} payload * @param {Object|string|number|boolean} payload
* @param {function} callback * @param {function} callback
* @param {function} errorCallback * @param {function} errorCallback
*/ */
post(uri, payload, callback, errorCallback) { post(uri: string, payload) {
/*jshint -W069 */ let done = q.defer<IReqResArg>()
let ctx = this
if (typeof callback !== 'function') {
callback = this.emptyCallback // ensure callback is function
}
let jwt = this.createJWT( let jwt = this.createJWT(
this.last_nonce, this.lastNonce,
payload, payload,
'RS256', 'RS256',
this.key_pair['private_pem'], this.keyPair['private_pem'],
this.key_pair['public_jwk']) this.keyPair['public_jwk'])
this.request(uri, jwt, (ans, res) => { this.request(uri, jwt)
ctx.evaluateStatus(uri, payload, ans, res) .then((reqResArg: IReqResArg) => {
// save replay nonce for later requests this.evaluateStatus(uri, payload, reqResArg.ans, reqResArg.res)
if ((res instanceof Object) && (res['headers'] instanceof Object)) { // save replay nonce for later requests
ctx.last_nonce = res.headers['replay-nonce'] if ((reqResArg.res instanceof Object) && (reqResArg.res['headers'] instanceof Object)) {
} this.lastNonce = reqResArg.res.headers['replay-nonce']
callback(ans, res) }
}, errorCallback ) done.resolve(reqResArg)
})
return done.promise
} }
/** /**
* evaluateStatus * checks if status is expected and log errors
* @description check if status is expected and log errors
* @param {string} uri * @param {string} uri
* @param {Object|string|number|boolean} payload * @param {Object|string|number|boolean} payload
* @param {Object|string} ans * @param {Object|string} ans
* @param {Object} res * @param {Object} res
*/ */
evaluateStatus(uri, payload, ans, res) { evaluateStatus(uri, payload, ans, res) {
/*jshint -W069 */
if (this.verbose) { if (this.verbose) {
if ( if (
(payload instanceof Object) (payload instanceof Object)
@ -263,11 +243,4 @@ export class JWebClient {
console.error('Receive:', ans) // received data console.error('Receive:', ans) // received data
} }
} }
/**
* Helper: Empty callback
*/
emptyCallback() {
// nop
}
} }

View File

@ -1,8 +1,10 @@
import 'typings-global' import 'typings-global'
import * as path from 'path' import * as path from 'path'
import * as smartstring from 'smartstring' import * as smartstring from 'smartstring'
import * as shelljs from 'shelljs'
export { export {
path, path,
smartstring smartstring,
shelljs
} }