All files / src/utils safe-compare.ts

100% Statements 16/16
100% Branches 8/8
100% Functions 1/1
100% Lines 16/16

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  11x 11x 11x 11x                   35x 1x   34x 5x     29x   34x 5x     29x   34x 28x   6x   11x          
import crypto from 'crypto';
 
import * as ShopifyErrors from '../error';
 
/**
 * A timing safe string comparison utility.
 *
 * @param strA any string, array of strings, or object with string values
 * @param strB any string, array of strings, or object with string values
 */
export default function safeCompare(
  strA: string | {[key: string]: string} | string[] | number[],
  strB: string | {[key: string]: string} | string[] | number[],
): boolean {
  let buffA: Buffer;
  let buffB: Buffer;
 
  if (typeof strA !== typeof strB) {
    throw new ShopifyErrors.SafeCompareError(
      `Mismatched data types provided: ${typeof strA} and ${typeof strB}`,
    );
  }
 
  if (typeof strA === 'object') {
    buffA = Buffer.from(JSON.stringify(strA));
  } else {
    buffA = Buffer.from(strA);
  }
  if (typeof strB === 'object') {
    buffB = Buffer.from(JSON.stringify(strB));
  } else {
    buffB = Buffer.from(strB);
  }
 
  if (buffA.length === buffB.length) {
    return crypto.timingSafeEqual(buffA, buffB);
  }
  return false;
}