environmentGuard.mjs 1.62 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,
  allowedBases = [ALLOWED_BASE]
}) {
  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 = allowedBases.some(base => {
    const allowed = base === ALLOWED_BASE ? allowedUrl : new URL(base)
    return (
      url.protocol === allowed.protocol &&
      url.hostname === allowed.hostname &&
      url.port === allowed.port &&
      url.pathname === allowed.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 }