/**
* Utility functions
*
* Implements methods to support other functions
*
* @author michael whobrey <mwhobrey@idealss.com>
*/
const crypto = require('crypto');
const moment = require('moment');
const { authDoc } = require('./data');
/**
* Validate signature of request
*
* Validate that the signature was in fact created from
* the right credentials to ensure integrity.
*
* @param token {string} - the identifying token of the client
* @param signature {string} - the signature sent with the request
* @param payload {Object} - the request payload (varies by request)
* @param dbClient {MongoClient} - the db client used to retrieve the private key
*
* @return {Promise} Promise object represents whether
* the rebuilt signature matches the signature sent in the request
*/
const validateSignature = async (token, signature, payload, dbClient) => {
const ad = await authDoc(token, dbClient);
const key = ad.private_key;
const sig = crypto
.createHash("sha256")
.update(payload + key)
.digest("hex");
return new Promise((resolve, reject) => {
resolve(sig === signature);
reject(false);
});
}
/**
* Validate request structure
*
* Validate that the request has all the necessary components of a request
*
* @param reqBody {Object} The request body to validate
*
* @return {Object} Object represents whether
* the request is structurally valid and a string of why it's not if it's not
*/
const validateRequest = (reqBody) => {
if (!reqBody.token || reqBody.token === '') {
return { valid: false, message: 'Missing or invalid token!' }
}
if (!reqBody.signature || reqBody.signature === '') {
return { valid: false, message: 'Missing or invalid signature!' }
}
if (!reqBody.group || reqBody.group <= 0) {
return { valid: false, message: 'Missing or invalid group!' }
}
if (!reqBody.siteId || reqBody.siteId <= 0) {
return { valid: false, message: 'Missing or invalid site id!' }
}
if (!reqBody.payload) {
return { valid: false, message: 'Missing payload!' }
}
return { valid: true, message: '' }
}
/**
* Retrieve the private key associated with a token.
*
* Connect to the database and retrieve the auth doc in order to get the private
* key that we will need for the client connection.
*
* @param token {string} The token supplied in the request.
* @param dbClient {MongoClient} - The db client used to retrieve the private key.
*
* @return {string} The private key associated with the token.
*/
const getPrivateKey = async (token, dbClient) => {
const ad = await authDoc(token, dbClient);
if (!ad.private_key) {
return '';
}
return ad.private_key;
}
/**
* Generate a salt to be used in signing.
*
* @param pre {string} Value to prepend to the salt.
* @param count {number} Current iterations count.
*
* @return {string} The salt to be used for signing.
*/
const generateSalt = (pre = '', count = -1) => {
count++;
if (count >= 9) {
return pre;
}
if ((count === 0) || (count === 1) || (count > 7)) {
pre += (0x10000 | Math.random() * 0x10000).toString(16).substring(1);
return generateSalt(pre, count);
}
if (pre !== '') {
pre += '-';
}
pre += (0x10000 | Math.random() * 0x10000).toString(16).substring(1);
return generateSalt(pre, count);
}
/**
* Generate and return a signature for a request body.
*
* Signature generated from the SHA256 hashing of the json
* payload, the private key and a unique salt.
*
* @param json {string} Json payload of the request
* @param key {string} The private key used to uniquely sign the request
* @param salt {string} salt used to sign the request - must be passed in
* since we need to send it down
*
* @return {string} The signature
*/
const signRequest = (json, key, salt) => {
const jHash = crypto
.createHash("sha256")
.update(json)
.digest("hex");
const kHash = crypto
.createHash("sha256")
.update(jHash + key)
.digest("hex");
const signature = crypto
.createHash("sha256")
.update(kHash + salt)
.digest("hex");
return signature;
};
/**
* Encode a string as Base64.
*
* @param str {string} The string we are encoding.
*
* @return {string} Base64 encoded string.
*/
const base64Encode = (str) => {
return Buffer.from(str).toString('base64');
};
/**
* Log to console in a standard way for readability.
*
* @param text {string} the text being logged
* @param obj {Object} an optional object to logg with the text
*
* @return {undefined} no return value
*/
const log = (text, obj = undefined) => {
const now = moment().format('MMMM Do YYYY, h:mm:ss a');
if (obj) {
console.log(`${now} :: ${text}`, obj);
}
else {
console.log(`${now} :: ${text}`);
}
};
/**
* Return PubSub api from a given query string.
*
* @param query {string} the query string to extract the api from
*
* @return {string} the PubSub api
*/
const extractApiFromQuery = (query) => {
const aryQuery = query.split('/');
return (aryQuery.length > 1) ? aryQuery[1] : aryQuery[0];
};
module.exports = {
validateRequest,
validateSignature,
base64Encode,
signRequest,
generateSalt,
log,
extractApiFromQuery,
getPrivateKey
}