import { createCipheriv, createHmac, scryptSync, } from 'crypto' import { validateAuthKeys } from '../../helpers' import { Response, Body } from './types' export async function ServerUtils_AuthCreate({ authKeys, loginResponse, apiKey, }: Body): Promise { try { validateAuthKeys(authKeys) // Get the current authKey and create a new key from it that is 32 bits const secret = authKeys.current! const key = scryptSync(secret, apiKey, 32) // Create a hash with the new key to const hash = createHmac('sha256', key).digest('hex') const jsonToBeEncrypted = { ...loginResponse, wappiAuthKey: hash, } const loginBody = JSON.stringify(jsonToBeEncrypted) const iv = scryptSync(secret, apiKey, 16) // generate the same ciphertext everytime const algorithm = 'aes-256-cbc' // algorithm to use const cipher = createCipheriv(algorithm, key, iv) const encryptedKey = cipher.update(loginBody, 'utf8', 'hex') + cipher.final('hex') // encrypted text return { auth: encryptedKey, } } catch (err) { return new Promise((resolve) => { const response = { error: 'Fatal error in ServerUtils_AuthCreate. Investigate.', errorMessage: err.message, auth: '', } // eslint-disable-next-line no-promise-executor-return return resolve(response) }) } }