@zephr/node-sdk
Version:
Zephr Node.js SDK
39 lines (33 loc) • 1.23 kB
JavaScript
const crypto = require('crypto')
const algorithm = 'sha256'
function signRequest(secretKey, path, query, method, timestamp, nonce, body) {
if (!secretKey) throw new Error('Client secret must be provided')
if (!path) throw new Error('Request path must be provided')
if (!method) throw new Error('Request method must be provided')
if (!timestamp) throw new Error('Signature timestamp must be provided')
if (!nonce) throw new Error('Signature nonce must be provided')
try {
let hash = crypto.createHash(algorithm).update(secretKey)
if (body) hash.update(body)
hash = hash
.update(path)
.update(query)
.update(method)
.update(timestamp.toString())
.update(nonce)
.digest('hex')
return hash
} catch (err) {
console.error(`Error signing request ${err}`)
throw err
}
}
function buildAuthHeader(accessKey, secretKey, path, query, method, body) {
const timestamp = new Date().getTime()
const nonce = Math.round(Math.random() * 1000000000000).toString(16)
const hash = signRequest(secretKey, path, query, method, timestamp, nonce, body)
return `ZEPHR-HMAC-SHA256 ${accessKey}:${timestamp}:${nonce}:${hash}`
}
module.exports = {
buildAuthHeader
}