Language: TypeScript
Label: safe
CWE: CWE-346 \u2014 Origin Validation Error
The product does not properly verify that the source of data or communication is valid.

Code:
export function authenticateOrigin(req: express.Request): boolean {
  // A missing origin probably means the source is non-browser.  Not sure we
  // have a use case for this but let it through.
  const originRaw = getFirstHeader(req, "origin")
  if (!originRaw) {
    return true
  }

  let origin: string
  try {
    origin = new URL(originRaw).host.trim().toLowerCase()
  } catch (error) {
    return false // Malformed URL.
  }

  // Honor Forwarded if present.
  const forwardedRaw = getFirstHeader(req, "forwarded")
  if (forwardedRaw) {
    const parts = forwardedRaw.split(/[;,]/)
    for (let i = 0; i < parts.length; ++i) {
      const [key, value] = splitOnFirstEquals(parts[i])
      if (key.trim().toLowerCase() === "host" && value) {
        return origin === value.trim().toLowerCase()
      }
    }
  }

  // Honor X-Forwarded-Host if present.
  const xHost = getFirstHeader(req, "x-forwarded-host")
  if (xHost) {
    return origin === xHost.trim().toLowerCase()
  }

  // A missing host likely means the reverse proxy has not been configured to
  // forward the host which means we cannot perform the check.  Emit a warning
  // so an admin can fix the issue.
  const host = getFirstHeader(req, "host")
  if (!host) {
    logger.warn(`no host headers found; blocking request to ${req.originalUrl}`)
    return false
  }

  return origin === host.trim().toLowerCase()
}