environmentGuard.mjs 1.46 KB
const ALLOWED_BASE = 'http://dj.test.glsx.com.cn/rop-dj-car-boutique'
const allowedUrl = new URL(ALLOWED_BASE)
const sensitiveKeyPattern = /mobile|code|session|sign|secret|appKey/i

const notAllowed = () =>
  new Error('E2E base URL is not allowlisted for order lifecycle tests')

export function assertAllowedE2EEnvironment({ baseUrl, enabled }) {
  if (enabled !== true) {
    throw new Error('RUN_ORDER_E2E=1 is required for real order lifecycle tests')
  }

  let url
  try {
    url = new URL(baseUrl)
  } catch {
    throw notAllowed()
  }

  const exactBase =
    url.protocol === allowedUrl.protocol &&
    url.hostname === allowedUrl.hostname &&
    url.port === allowedUrl.port &&
    url.pathname === allowedUrl.pathname &&
    url.search === '' &&
    url.hash === '' &&
    url.username === '' &&
    url.password === ''

  if (!exactBase) {
    throw notAllowed()
  }
  return url
}

const isPlainObject = value => {
  if (value === null || typeof value !== 'object') return false
  const prototype = Object.getPrototypeOf(value)
  return prototype === Object.prototype || prototype === null
}

export function redactSensitive(value) {
  if (Array.isArray(value)) {
    return value.map(item => redactSensitive(item))
  }
  if (!isPlainObject(value)) {
    return value
  }

  return Object.fromEntries(
    Object.entries(value).map(([key, item]) => [
      key,
      sensitiveKeyPattern.test(key) ? '[REDACTED]' : redactSensitive(item)
    ])
  )
}

export { ALLOWED_BASE }