All files / src/utils safe-compare.ts

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

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 3711x   11x               11x       26x 25x 25x   25x 5x 5x   20x 20x     25x 20x     1x       5x    
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 | Record<string, string> | string[] | number[],
  strB: string | Record<string, string> | string[] | number[],
): boolean {
  if (typeof strA === typeof strB) {
    let buffA: Buffer;
    let buffB: Buffer;
 
    if (typeof strA === 'object' && typeof strB === 'object') {
      buffA = Buffer.from(JSON.stringify(strA));
      buffB = Buffer.from(JSON.stringify(strB));
    } else {
      buffA = Buffer.from(strA);
      buffB = Buffer.from(strB);
    }
 
    if (buffA.length === buffB.length) {
      return crypto.timingSafeEqual(buffA, buffB);
    }
  } else {
    throw new ShopifyErrors.SafeCompareError(
      `Mismatched data types provided: ${typeof strA} and ${typeof strB}`,
    );
  }
  return false;
}