All files / apis/shared hmac.ts

33.33% Statements 2/6
0% Branches 0/2
0% Functions 0/2
40% Lines 2/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421x                                                             1x                    
import { createHmac, timingSafeEqual } from "crypto";
 
// For compatibility with NodeJS v10 typings
type BinaryAlike = string | NodeJS.ArrayBufferView;
 
/**
 *
 *
 * @param {BinaryAlike} data
 * @return {NodeJS.ArrayBufferView}  {NodeJS.ArrayBufferView}
 */
function parseBinaryAlike(data: BinaryAlike): NodeJS.ArrayBufferView {
  Iif (typeof data === "string") return Buffer.from(data, "hex");
  /* istanbul ignore next */
  return data;
}
 
export type HmacOptions = {
  algorithm?: string;
  key: BinaryAlike;
  data: BinaryAlike;
  digest: BinaryAlike;
};
 
/**
 *
 *
 * @export
 * @param {HmacOptions} options
 * @return {boolean}
 */
export function compareHmac({
  algorithm = "sha256",
  data,
  digest,
  key
}: HmacOptions) {
  const hash = createHmac(algorithm, key).update(data).digest();
 
  return timingSafeEqual(hash, parseBinaryAlike(digest));
}