All files / src/utils shop-validator.ts

100% Statements 25/25
100% Branches 20/20
100% Functions 3/3
100% Lines 23/23

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55  24x 24x 24x 24x 24x                 89x 89x 89x 4x 8x     89x 89x 89x 2x   87x   24x               17x 17x 17x 17x 1x   16x   24x                    
import {InvalidHostError, InvalidShopError} from '../error';
import {Context} from '../context';
 
/**
 * Validates and sanitizes shop domain urls. If Context.CUSTOM_SHOP_DOMAINS is set, shops ending in those domains are
 * allowed. Accepts myshopify.com and myshopify.io by default.
 *
 * @param shop Shop url: {shop}.{domain}
 * @param throwOnInvalid Whether to raise an exception if the shop is invalid
 */
export function sanitizeShop(
  shop: string,
  throwOnInvalid = false,
): string | null {
  const domainsRegex = ['myshopify\\.com', 'myshopify\\.io'];
  if (Context.CUSTOM_SHOP_DOMAINS) {
    domainsRegex.push(
      ...Context.CUSTOM_SHOP_DOMAINS.map((regex) =>
        typeof regex === 'string' ? regex : regex.source,
      ),
    );
  }
 
  const shopUrlRegex = new RegExp(
    `^[a-zA-Z0-9][a-zA-Z0-9-_]*\\.(${domainsRegex.join('|')})[/]*$`,
  );
 
  const sanitizedShop = shopUrlRegex.test(shop) ? shop : null;
  if (!sanitizedShop && throwOnInvalid) {
    throw new InvalidShopError('Received invalid shop argument');
  }
 
  return sanitizedShop;
}
 
/**
 * Validates and sanitizes Shopify host arguments.
 *
 * @param host Host address
 * @param throwOnInvalid Whether to raise an exception if the host is invalid
 */
export function sanitizeHost(
  host: string,
  throwOnInvalid = false,
): string | null {
  const base64regex = /^[0-9a-zA-Z+/]+={0,2}$/;
 
  const sanitizedHost = base64regex.test(host) ? host : null;
  if (!sanitizedHost && throwOnInvalid) {
    throw new InvalidHostError('Received invalid host argument');
  }
 
  return sanitizedHost;
}