Created
April 26, 2018 02:17
-
-
Save nubela/a7d3ef92eabb490c3ce7ccca04bca3b1 to your computer and use it in GitHub Desktop.
This is the JS library for accessing NuMoney Exchange's API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sign requests using: | |
// https://tools.ietf.org/html/draft-cavage-http-signatures-09 | |
import hmacSHA256 from 'crypto-js/hmac-sha256'; | |
import sha256 from 'crypto-js/sha256'; | |
import Base64 from 'crypto-js/enc-base64'; | |
// Signed string be MUST be built from headers in this specific order | |
const SIGNATURE_HEADERS = [ | |
"(request-target)", "host", "accept", "content-type", "x-original-length", | |
"x-timestamp", "digest", | |
]; | |
const SIGNATURE_HEADERS_VALUE = SIGNATURE_HEADERS.join(" "); | |
export class NMXClient { | |
constructor(config) { | |
Object.assign(this, {url: '/'}, config); | |
var a = document.createElement('a'); | |
a.href = this.url; | |
this.host = a.host; | |
this.requestTarget = "post " + a.pathname + a.search; | |
this.textEncoder = new TextEncoder('utf-8'); | |
} | |
query(graphQLParams) { | |
// Digest body | |
const body = JSON.stringify(graphQLParams); | |
const bodyDigest = Base64.stringify(sha256(body)); | |
// Headers to send with fetch | |
var headers = { | |
'accept': 'application/json', | |
'content-type': 'application/json', | |
'x-timestamp': Date.now(), | |
'digest': 'SHA-256=' + bodyDigest, | |
'x-original-length': this.textEncoder.encode(body).length | |
}; | |
// Extra headers which cannot be set or sent | |
var extraHeaders = { | |
"(request-target)": this.requestTarget, | |
"host": this.host | |
}; | |
// Sign request | |
var allHeaders = Object.assign({}, headers, extraHeaders); | |
var stringToSignLines = SIGNATURE_HEADERS.map(header => { | |
return header + ": " + allHeaders[header] | |
}); | |
var stringToSign = stringToSignLines.join("\n"); | |
var signature = Base64.stringify(hmacSHA256(stringToSign, this.apiSecret)); | |
// Build authorization header | |
var authHeaderDict = { | |
'keyId': this.apiKey, | |
'algorithm': 'hmac-sha256', | |
'headers': SIGNATURE_HEADERS_VALUE, | |
'signature': signature | |
}; | |
var authHeaderParts = []; | |
Object.entries(authHeaderDict).forEach(([k, v]) => { | |
authHeaderParts.push(k + '="' + v + '"'); | |
}); | |
headers['authorization'] = "Signature " + authHeaderParts.join(","); | |
// Send request | |
return fetch('/', { | |
method: 'POST', | |
headers: headers, | |
body: body | |
}).then(response => response.json()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment