smartacme/ts/smartacme.classes.jwebclient.ts

247 lines
7.4 KiB
TypeScript
Raw Normal View History

2016-11-01 17:27:57 +00:00
import * as plugins from './smartacme.plugins'
import * as https from 'https'
let jwa = require('jwa')
import * as url from 'url'
2016-11-03 17:57:42 +00:00
import * as q from 'q'
export interface IReqResArg {
ans: any
res: any
}
2016-11-01 17:27:57 +00:00
/**
* json_to_utf8base64url
* @private
* @description convert JSON to base64-url encoded string using UTF-8 encoding
* @param {Object} obj
* @return {string}
* @throws Exception if object cannot be stringified or contains cycle
*/
2016-11-03 17:57:42 +00:00
let json_to_utf8base64url = (obj) => {
2016-11-01 19:16:43 +00:00
return plugins.smartstring.base64.encodeUri(JSON.stringify(obj))
2016-11-01 17:27:57 +00:00
}
/**
* @class JWebClient
* @constructor
* @description Implementation of HTTPS-based JSON-Web-Client
*/
export class JWebClient {
2016-11-03 17:57:42 +00:00
/**
* 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
*/
2016-11-01 17:27:57 +00:00
verbose: boolean
constructor() {
2016-11-01 19:16:43 +00:00
this.verbose = false
2016-11-01 17:27:57 +00:00
}
/**
* createJWT
* @description create JSON-Web-Token signed object
* @param {string|undefined} nonce
* @param {Object|string|number|boolean} payload
* @param {string} alg
* @param {Object|string} key
* @param {Object} jwk
* @return {string}
*/
createJWT(nonce, payload, alg, key, jwk) {
/*jshint -W069 */
// prepare key
if (key instanceof Object) {
2016-11-01 19:16:43 +00:00
key = new Buffer(plugins.smartstring.base64.decode(key['k']))
2016-11-01 17:27:57 +00:00
}
// prepare header
let header = {
typ: 'JWT',
alg: alg,
jwk: jwk,
nonce: null
}
if (nonce !== void 0) {
header.nonce = nonce
}
// concatenate header and payload
let input = [
json_to_utf8base64url(header),
json_to_utf8base64url(payload)
].join('.')
// sign input
let hmac = jwa(alg)
let sig = hmac.sign(input, key)
// concatenate input and signature
let output = [
input,
sig
].join('.')
// output
return output
}
/**
* request
* @description make GET or POST request over HTTPS and use JOSE as payload type
* @param {string} query
* @param {string} payload
* @param {function} callback
* @param {function} errorCallback
*/
2016-11-03 17:57:42 +00:00
request(query: string, payload: string = null) {
let done = q.defer()
2016-11-01 17:27:57 +00:00
// prepare options
let uri = url.parse(query)
let options = {
hostname: uri.hostname,
port: parseInt(uri.port, 10),
path: uri.path,
method: null,
headers: {}
}
2016-11-03 17:57:42 +00:00
if (!payload === null) {
2016-11-01 17:27:57 +00:00
options.method = 'POST'
options.headers = {
'Content-Type': 'application/jose',
'Content-Length': payload.length
}
} else {
options.method = 'GET'
}
// prepare request
2016-11-03 17:57:42 +00:00
let req = https.request(options, (res) => {
2016-11-01 17:27:57 +00:00
// receive data
let data = []
2016-11-03 17:57:42 +00:00
res.on('data', (block) => {
2016-11-01 17:27:57 +00:00
if (block instanceof Buffer) {
data.push(block)
}
})
2016-11-03 17:57:42 +00:00
res.on('end', () => {
2016-11-01 17:27:57 +00:00
let buf = Buffer.concat(data)
let isJSON = (
(res instanceof Object)
&& (res['headers'] instanceof Object)
&& (typeof res.headers['content-type'] === 'string')
&& (res.headers['content-type'].indexOf('json') > -1)
)
if (isJSON && buf.length > 0) {
try {
// convert to JSON
let json = JSON.parse(buf.toString('utf8'))
2016-11-03 17:57:42 +00:00
done.resolve({ json: json, res: res })
2016-11-01 17:27:57 +00:00
} catch (e) {
// error (if empty or invalid JSON)
2016-11-03 17:57:42 +00:00
done.reject(e)
2016-11-01 17:27:57 +00:00
}
}
})
2016-11-03 17:57:42 +00:00
}).on('error', (e) => {
2016-11-01 17:27:57 +00:00
console.error('Error occured', e)
// error
2016-11-03 17:57:42 +00:00
done.reject(e)
2016-11-01 17:27:57 +00:00
})
// write POST body if payload was specified
2016-11-03 17:57:42 +00:00
if (!payload === null) {
2016-11-01 17:27:57 +00:00
req.write(payload)
}
// make request
req.end()
2016-11-03 17:57:42 +00:00
return done.promise
2016-11-01 17:27:57 +00:00
}
/**
* get
* @description make GET request
* @param {string} uri
* @param {function} callback
* @param {function} errorCallback
*/
2016-11-03 17:57:42 +00:00
get(uri: string) {
let done = q.defer<IReqResArg>()
this.request(uri)
.then((reqResArg: IReqResArg) => {
this.evaluateStatus(uri, null, reqResArg.ans, reqResArg.res)
// save replay nonce for later requests
if ((reqResArg.res instanceof Object) && (reqResArg.res['headers'] instanceof Object)) {
this.lastNonce = reqResArg.res.headers['replay-nonce']
}
done.resolve(reqResArg)
})
return done.promise
2016-11-01 17:27:57 +00:00
}
/**
2016-11-03 17:57:42 +00:00
* make POST request
2016-11-01 17:27:57 +00:00
* @param {string} uri
* @param {Object|string|number|boolean} payload
* @param {function} callback
* @param {function} errorCallback
*/
2016-11-03 17:57:42 +00:00
post(uri: string, payload) {
let done = q.defer<IReqResArg>()
2016-11-01 19:16:43 +00:00
let jwt = this.createJWT(
2016-11-03 17:57:42 +00:00
this.lastNonce,
2016-11-01 19:16:43 +00:00
payload,
'RS256',
2016-11-03 17:57:42 +00:00
this.keyPair['private_pem'],
this.keyPair['public_jwk'])
this.request(uri, jwt)
.then((reqResArg: IReqResArg) => {
this.evaluateStatus(uri, payload, reqResArg.ans, reqResArg.res)
// save replay nonce for later requests
if ((reqResArg.res instanceof Object) && (reqResArg.res['headers'] instanceof Object)) {
this.lastNonce = reqResArg.res.headers['replay-nonce']
}
done.resolve(reqResArg)
})
return done.promise
2016-11-01 17:27:57 +00:00
}
/**
2016-11-03 17:57:42 +00:00
* checks if status is expected and log errors
2016-11-01 17:27:57 +00:00
* @param {string} uri
* @param {Object|string|number|boolean} payload
* @param {Object|string} ans
* @param {Object} res
*/
evaluateStatus(uri, payload, ans, res) {
if (this.verbose) {
if (
(payload instanceof Object)
|| (typeof payload === 'string')
|| (typeof payload === 'number')
|| (typeof payload === 'boolean')
) {
console.error('Send :', payload) // what has been sent
}
}
let uri_parsed = url.parse(uri)
if (res['statusCode'] >= 100 && res['statusCode'] < 400) {
console.error('HTTP :', res['statusCode'], uri_parsed.path) // response code if successful
}
if (res['statusCode'] >= 400 && res['statusCode'] < 500) {
console.error('HTTP :', res['statusCode'], uri_parsed.path) // response code if error
if (ans instanceof Object) {
if (typeof ans['detail'] === 'string') {
console.error('Message:', ans.detail.split(' :: ').pop()) // error message if any
}
}
}
if (this.verbose) {
console.error('Receive:', res['headers']) // received headers
console.error('Receive:', ans) // received data
}
}
}