Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

3.2 KB
Raw Blame
import { z } from "zod";

import { isValidEmailDomain } from "./validate-email";

const MAX_ALLOWED_EMAIL_DOMAINS_LENGTH = 255;

const getDomainEntries = (allowedDomainsConfig: string) =>
  allowedDomainsConfig
    .split(",")
    .map((domain) => domain.trim())
    .filter(Boolean);

const normalizeDomain = (domain: string) => domain.replace(/^@/, "").trim().toLowerCase();

export const normalizeAllowedEmailDomains = (allowedDomainsConfig: string): string =>
  Array.from(new Set(getDomainEntries(allowedDomainsConfig).map(normalizeDomain))).join(", ");

export const AllowedEmailDomainsSchema = z
  .string()
  .superRefine((value, context) => {
    const domainEntries = getDomainEntries(value);
    const invalidDomains = domainEntries.filter((domain) => !isValidEmailDomain(normalizeDomain(domain)));

    if (value.trim() && !domainEntries.length) {
      context.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Enter at least one valid email domain"
      });
    }

    if (invalidDomains.length) {
      context.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Invalid email domain${invalidDomains.length > 1 ? "s" : ""}: ${invalidDomains.join(", ")}`
      });
    }

    if (normalizeAllowedEmailDomains(value).length > MAX_ALLOWED_EMAIL_DOMAINS_LENGTH) {
      context.addIssue({
        code: z.ZodIssueCode.too_big,
        maximum: MAX_ALLOWED_EMAIL_DOMAINS_LENGTH,
        inclusive: true,
        type: "string",
        message: `Email domains must be ${MAX_ALLOWED_EMAIL_DOMAINS_LENGTH} characters or fewer`
      });
    }
  })
  .transform(normalizeAllowedEmailDomains);

/**
 * Checks if an email's domain matches the allowed domains configuration.
 * Supports exact domains (e.g. "example.com") and wildcard patterns (e.g. "*.example.com").
 *
 * Wildcard patterns match only the exact suffix or subdomains of it:
 * - The root domain: [email protected] matches *.acme.com
 * - Any subdomain: [email protected] matches *.acme.com
 * - Multi-level subdomains: [email protected] matches *.acme.com
 *
 * Does NOT match prefix-style abuse (e.g. *.example.com must not allow user@example.com.evil).
 * Matching is case-insensitive (email domains are case-insensitive per RFC 5321).
 */
export const matchesAllowedEmailDomain = (email: string, allowedDomainsConfig: string): boolean => {
  if (!allowedDomainsConfig?.trim()) {
    return true;
  }

  const emailParts = email.split("@");
  if (emailParts.length !== 2 || !emailParts[1]?.trim()) {
    return false;
  }

  const emailDomain = emailParts[1].trim().toLowerCase();
  const patterns = allowedDomainsConfig
    .split(/,\s*/)
    .map((p) => p.trim())
    .filter(Boolean);

  for (const pattern of patterns) {
    const patternLower = normalizeDomain(pattern);

    if (patternLower.startsWith("*.")) {
      // Wildcard: *.suffix - matches exact suffix or subdomains only (domain === suffix or domain ends with .suffix)
      // Avoids prefix abuse: *.example.com must not allow example.com.evil
      const suffix = patternLower.slice(2).trim(); // everything after "*."
      if (suffix && (emailDomain === suffix || emailDomain.endsWith(`.${suffix}`))) {
        return true;
      }
    } else if (emailDomain === patternLower) {
      return true;
    }
  }

  return false;
};