Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(auth): read an email domain after the last at sign (#129844)

Tom Piccirelloc442dfbdc4b4
diff --git a/.semgrep/rules/devex/email-domain-after-last-at.py b/.semgrep/rules/devex/email-domain-after-last-at.py
new file mode 100644
index 000000000000..9e0f536f2095
--- /dev/null
+++ b/.semgrep/rules/devex/email-domain-after-last-at.py
@@ -0,0 +1,73 @@
+# Test cases for email-domain-after-last-at.
+# ruff: noqa
+from urllib.parse import urlparse
+
+from posthog.helpers.email_utils import email_domain
+
+
+def first_at_slices(email: str) -> list[str]:
+ return [
+ # ruleid: email-domain-after-last-at
+ email[email.index("@") + 1 :],
+ # ruleid: email-domain-after-last-at
+ email[email.find("@") + 1 :].lower(),
+ ]
+
+
+def first_at_splits(email: str, config: dict) -> list[str]:
+ return [
+ # ruleid: email-domain-after-last-at
+ email.split("@")[1],
+ # ruleid: email-domain-after-last-at
+ email.split("@", 1)[1],
+ # ruleid: email-domain-after-last-at
+ email.split("@", maxsplit=1)[1],
+ # ruleid: email-domain-after-last-at
+ email.split("@", 1)[-1],
+ # ruleid: email-domain-after-last-at
+ email.split("@", maxsplit=1)[-1],
+ # ruleid: email-domain-after-last-at
+ email.partition("@")[2],
+ # ruleid: email-domain-after-last-at
+ (config.get("email") or "").partition("@")[2].lower(),
+ ]
+
+
+def first_at_unpacks(email: str, address: str) -> tuple[str, str]:
+ # ruleid: email-domain-after-last-at
+ local_part, separator, domain = address.strip().lower().partition("@")
+ # ruleid: email-domain-after-last-at
+ user, host = email.split("@", 1)
+ # ruleid: email-domain-after-last-at
+ name, server = email.split("@")
+ return domain, host + server
+
+
+def last_at_is_fine(email: str, url: str) -> list[object]:
+ _, _, unpacked = email.rpartition("@")
+ return [
+ # ok: email-domain-after-last-at
+ email_domain(email),
+ # ok: email-domain-after-last-at
+ email.rpartition("@")[2],
+ # ok: email-domain-after-last-at
+ email.rsplit("@", 1)[-1],
+ # ok: email-domain-after-last-at
+ email.split("@")[-1],
+ # ok: email-domain-after-last-at
+ urlparse(url).netloc.rpartition("@")[2],
+ unpacked,
+ ]
+
+
+def not_a_domain_read(email: str) -> list[object]:
+ return [
+ # ok: email-domain-after-last-at
+ "@" in email,
+ # ok: email-domain-after-last-at
+ len(email.split("@")) == 2,
+ # ok: email-domain-after-last-at
+ email.split("@")[0],
+ # ok: email-domain-after-last-at
+ email.index("@"),
+ ]
diff --git a/.semgrep/rules/devex/email-domain-after-last-at.yaml b/.semgrep/rules/devex/email-domain-after-last-at.yaml
new file mode 100644
index 000000000000..dd4855f487a9
--- /dev/null
+++ b/.semgrep/rules/devex/email-domain-after-last-at.yaml
@@ -0,0 +1,50 @@
+rules:
+ - id: email-domain-after-last-at
+ message: |
+ This reads the domain of an email address from the first `@`.
+
+ The domain follows the last `@`. A quoted local part may hold an `@` of its own,
+ and Django's EmailValidator accepts one, so `"x@y"@example.com` is a valid
+ address whose domain is `example.com`. Reading from the first `@` returns
+ `y"@example.com` instead, which matches no configured domain.
+
+ Take the domain from `email_domain` in posthog/helpers/email_utils.py. It returns
+ None when the address carries no domain, rather than raising:
+
+ from posthog.helpers.email_utils import email_domain
+
+ domain = email_domain(email)
+
+ When you need the local part too, split on the last `@`:
+
+ local_part, _, domain = email.rpartition("@")
+
+ If the string is not an email address, or the code refuses a second `@` itself,
+ add `# nosemgrep: email-domain-after-last-at -- <reason>` on the line before.
+ severity: ERROR
+ languages: [python]
+ paths:
+ include:
+ - 'common/**/*.py'
+ - 'ee/**/*.py'
+ - 'posthog/**/*.py'
+ - 'products/**/*.py'
+ exclude:
+ - '**/migrations/**'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/test_*.py'
+ - '**/.semgrep/**'
+ pattern-either:
+ - pattern: $E[$E.index("@") + 1 :]
+ - pattern: $E[$E.find("@") + 1 :]
+ - pattern: $E.split("@", ...)[1]
+ - pattern: $E.split("@", 1)[-1]
+ - pattern: $E.split("@", maxsplit=1)[-1]
+ - pattern: $E.partition("@")[2]
+ - pattern: $LOCAL, $SEP, $DOMAIN = $E.partition("@")
+ - pattern: $LOCAL, $DOMAIN = $E.split("@", ...)
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit
diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.py
index 3adce0ea9fe6..c47c1ebae720 100644
--- a/posthog/api/organization_domain.py
+++ b/posthog/api/organization_domain.py
@@ -20,6 +20,7 @@ from posthog.api.utils import action
from posthog.cloud_utils import is_cloud
from posthog.constants import AvailableFeature
from posthog.event_usage import groups
+from posthog.helpers.email_utils import email_domain
from posthog.models import OrganizationDomain, User
from posthog.models.identity_provider_config import ConfigScope
from posthog.models.organization import Organization, OrganizationMembership
@@ -192,10 +193,10 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):
# the whole organization with them. Mirrors the guard on enabling the setting.
if instance.is_verified and self.organization.enforce_verified_domains:
user = cast(User, request.user)
- email_domain = user.email[user.email.index("@") + 1 :] if "@" in user.email else ""
+ acting_domain = email_domain(user.email) or ""
still_admitted = (
OrganizationDomain.objects.verified_domains()
- .filter(organization=self.organization, domain__iexact=email_domain)
+ .filter(organization=self.organization, domain__iexact=acting_domain)
.exclude(pk=instance.pk)
.exists()
)
diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.py
index 49fb856215a7..b98f8fc79a71 100644
--- a/posthog/helpers/email_utils.py
+++ b/posthog/helpers/email_utils.py
@@ -255,6 +255,19 @@ class EmailNormalizer:
return email.translate(_ASCII_UPPER_TO_LOWER)
+def email_domain(email: str) -> str | None:
+ """The domain of `email`, or None when it carries no domain.
+
+ The domain follows the last `@`. A local part may hold an `@` of its own inside a quoted
+ string, which Django's `EmailValidator` accepts, so reading from the first `@` returns part of
+ the local part and then matches no configured domain.
+ """
+ _, separator, domain = email.rpartition("@")
+ if not separator or not domain:
+ return None
+ return domain
+
+
def strip_email_alias(email: str) -> str:
"""
Strip a Gmail-style '+suffix' from the local part of an email (e.g.
@@ -297,7 +310,7 @@ GMAIL_CANONICAL_LOCAL_EXPRESSION = Replace(
def reject_plus_addressed_email(value: str) -> None:
"""Raise if the local part of `value` contains '+'."""
- local = value.split("@", 1)[0]
+ local = value.rsplit("@", 1)[0]
if "+" in local:
raise serializers.ValidationError(
"Email addresses with a '+' aren't supported. Please use your primary email address.",
diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.py
index 43c849349f06..96923056447b 100644
--- a/posthog/helpers/tests/test_email_utils.py
+++ b/posthog/helpers/tests/test_email_utils.py
@@ -230,9 +230,15 @@ class TestStripEmailAlias(SimpleTestCase):
class TestRejectPlusAddressedEmail(SimpleTestCase):
- def test_rejects_plus_in_local_part(self):
+ @parameterized.expand(
+ [
+ ("plain", "[email protected]"),
+ ("quoted_local_part_holding_an_at", '"some@user+alias"@domain.com'),
+ ]
+ )
+ def test_rejects_plus_in_local_part(self, _name: str, email: str) -> None:
with self.assertRaises(serializers.ValidationError) as ctx:
- reject_plus_addressed_email("[email protected]")
+ reject_plus_addressed_email(email)
self.assertEqual(ctx.exception.get_codes(), ["plus_addressing_not_allowed"])
def test_allows_email_without_plus(self):
diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.py
index 9a25cf0b274f..72f07a0b8d32 100644
--- a/posthog/models/integration/email.py
+++ b/posthog/models/integration/email.py
@@ -18,6 +18,7 @@ from rest_framework.exceptions import ValidationError
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from posthog.helpers.email_utils import email_domain
from posthog.integrations.contracts import IntegrationRecord
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -54,7 +55,9 @@ class EmailIntegration:
) -> model.Integration:
email_address: str = config["email"].lower()
name: str = config["name"]
- domain: str = email_address.split("@")[1]
+ domain = email_domain(email_address)
+ if domain is None:
+ raise ValidationError("Enter a valid email address, like [email protected].")
mail_from_subdomain: str = config.get("mail_from_subdomain", "feedback")
provider: str = config.get("provider", "ses")
diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.py
index 6bef1607d027..83010fe1eb5a 100644
--- a/posthog/models/organization_domain.py
+++ b/posthog/models/organization_domain.py
@@ -10,6 +10,7 @@ import dns.resolver
from posthog.constants import AvailableFeature
from posthog.dns_utils import dnssec_resolver
+from posthog.helpers.email_utils import email_domain
from posthog.models import Organization
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.identity_provider_config import ConfigScope, DomainScope, IdentityProviderConfig, saml_configured_q
@@ -41,7 +42,9 @@ class OrganizationDomainManager(models.Manager):
Returns an `OrganizationDomain` configuration for a specific email address (if it exists and is verified),
using the domain of the email address
"""
- domain = email[email.index("@") + 1 :]
+ domain = email_domain(email)
+ if domain is None:
+ return None
return self.verified_domains().filter(domain__iexact=domain).first()
def get_sso_enforcement_for_email_address(
@@ -51,7 +54,9 @@ class OrganizationDomainManager(models.Manager):
Returns the specific `sso_enforcement` applicable for an email address or an `OrganizationDomain` objects.
Validates SSO providers are properly configured and all the proper licenses exist.
"""
- domain = email[email.index("@") + 1 :]
+ domain = email_domain(email)
+ if domain is None:
+ return None
queryset = self.verified_domains().filter(domain__iexact=domain).exclude(sso_enforcement="")
if organization is not None:
@@ -108,9 +113,9 @@ class OrganizationDomainManager(models.Manager):
def is_domain_verified_for_organization(self, email: str, organization: Organization) -> bool:
"""Whether the domain of `email` is a verified domain owned by `organization`."""
- if "@" not in email:
+ domain = email_domain(email)
+ if domain is None:
return False
- domain = email[email.index("@") + 1 :]
return self.verified_domains().filter(organization=organization, domain__iexact=domain).exists()
def is_email_blocked_by_domain_enforcement(self, email: str, organization: Organization) -> bool:
diff --git a/posthog/models/test/test_organization_domain.py b/posthog/models/test/test_organization_domain.py
index 2ac3d47c4732..6800f5c6c4b7 100644
--- a/posthog/models/test/test_organization_domain.py
+++ b/posthog/models/test/test_organization_domain.py
@@ -1,9 +1,11 @@
from posthog.test.base import BaseTest
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
+from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationDomain
@@ -42,3 +44,42 @@ class TestOrganizationDomainEnforcement(BaseTest):
org = self._org_with_domain()
OrganizationDomain.objects.create(domain="pending.example.com", organization=org, verified_at=None)
self.assertTrue(OrganizationDomain.objects.is_email_blocked_by_domain_enforcement("[email protected]", org))
+
+
+@override_settings(SOCIAL_AUTH_GITHUB_KEY="github_key", SOCIAL_AUTH_GITHUB_SECRET="github_secret")
+class TestTheDomainOfAnEmailAddress(BaseTest):
+ QUOTED_LOCAL_PART = '"x@y"@hogflix.posthog.com'
+
+ def _verified_domain(self) -> Organization:
+ organization = Organization.objects.create(name="Hogflix", enforce_verified_domains=True)
+ organization.available_product_features = [{"key": AvailableFeature.SSO_ENFORCEMENT, "name": "SSO enforcement"}]
+ organization.save()
+ OrganizationDomain.objects.create(
+ domain="hogflix.posthog.com",
+ organization=organization,
+ verified_at=timezone.now(),
+ sso_enforcement="github",
+ )
+ return organization
+
+ @parameterized.expand(
+ [
+ ("plain", "[email protected]"),
+ ("quoted_local_part_holding_an_at", QUOTED_LOCAL_PART),
+ ]
+ )
+ def test_the_verified_domain_applies_to_the_address(self, _name: str, email: str) -> None:
+ organization = self._verified_domain()
+
+ self.assertTrue(OrganizationDomain.objects.is_domain_verified_for_organization(email, organization))
+ self.assertFalse(OrganizationDomain.objects.is_email_blocked_by_domain_enforcement(email, organization))
+ self.assertIsNotNone(OrganizationDomain.objects.get_verified_for_email_address(email))
+ self.assertEqual(OrganizationDomain.objects.get_sso_enforcement_for_email_address(email), "github")
+
+ @parameterized.expand([("no_at", "nobody"), ("empty_domain", "nobody@"), ("empty", "")])
+ def test_an_address_without_a_domain_matches_nothing(self, _name: str, email: str) -> None:
+ organization = self._verified_domain()
+
+ self.assertIsNone(OrganizationDomain.objects.get_verified_for_email_address(email))
+ self.assertIsNone(OrganizationDomain.objects.get_sso_enforcement_for_email_address(email))
+ self.assertFalse(OrganizationDomain.objects.is_domain_verified_for_organization(email, organization))
diff --git a/posthog/utils.py b/posthog/utils.py
index 7d4ea7015c51..d73158793dfe 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -2013,10 +2013,10 @@ class GenericEmails:
self.emails = {x.rstrip(): True for x in f}
def is_generic(self, email: str) -> bool:
- at_location = email.find("@")
- if at_location == -1:
+ _, separator, domain = email.rpartition("@")
+ if not separator:
return False
- return self.is_generic_domain(email[(at_location + 1) :])
+ return self.is_generic_domain(domain)
def is_generic_domain(self, domain: str) -> bool:
return self.emails.get(domain, False)
diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.py
index 91709d460790..320c86b6b2f8 100644
--- a/products/cdp/backend/validation.py
+++ b/products/cdp/backend/validation.py
@@ -18,6 +18,7 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.parser import parse_program, parse_string_template
from posthog.hogql.visitor import TraversingVisitor
+from posthog.helpers.email_utils import email_domain
from posthog.integrations import IntegrationManager
from posthog.models.integration import POSTHOG_CONNECT_KIND, WAREHOUSE_SOURCE_TYPE_CONFIG_KEY
from posthog.models.team.team import Team
@@ -154,7 +155,8 @@ def _validate_email_sender_override(from_value: dict, context: dict) -> None:
}
)
- if not FROM_OVERRIDE_EMAIL_REGEX.match(override):
+ override_domain = email_domain(override.lower())
+ if override_domain is None or not FROM_OVERRIDE_EMAIL_REGEX.match(override):
raise serializers.ValidationError(
{
"input": f'The custom sender address "{override}" is not a valid email address. '
@@ -166,7 +168,6 @@ def _validate_email_sender_override(from_value: dict, context: dict) -> None:
if not integration_ids:
return
- override_domain = override.split("@")[1].lower()
# An empty cached domain means the id resolved to no email integration for this team; the
# save is not blocked on it (there is no domain to compare), matching the uncached behavior.
shared_cache = context.get("email_integration_domain_cache")
@@ -175,7 +176,9 @@ def _validate_email_sender_override(from_value: dict, context: dict) -> None:
if missing_ids:
for integration in IntegrationManager.email.credentials.get_many(get_team().id, missing_ids).values():
config = integration.config or {}
- domain_cache[integration.id] = (config.get("domain") or (config.get("email") or "").split("@")[-1]).lower()
+ domain_cache[integration.id] = (
+ config.get("domain") or email_domain(config.get("email") or "") or ""
+ ).lower()
for integration_id in missing_ids:
domain_cache.setdefault(integration_id, "")
diff --git a/products/conversations/backend/api/email_settings.py b/products/conversations/backend/api/email_settings.py
index c335034ef940..c2210353fe90 100644
--- a/products/conversations/backend/api/email_settings.py
+++ b/products/conversations/backend/api/email_settings.py
@@ -24,6 +24,7 @@ from rest_framework.views import APIView
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.dataclasses import frozen
from posthog.email import EmailMessage, is_smtp_email_service_available
+from posthog.helpers.email_utils import email_domain
from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
@@ -583,7 +584,9 @@ class EmailConnectView(APIView):
if owner.id != user.id and not is_admin:
return Response({"error": "You can only connect your own email address."}, status=403)
- domain = from_email.split("@")[1]
+ domain = email_domain(from_email)
+ if domain is None:
+ return Response({"error": "Enter a valid email address, like [email protected]."}, status=400)
inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN")
if not inbound_domain:
return Response(
diff --git a/products/conversations/backend/services/mailgun_events.py b/products/conversations/backend/services/mailgun_events.py
index 16362fd244a8..9daca6684827 100644
--- a/products/conversations/backend/services/mailgun_events.py
+++ b/products/conversations/backend/services/mailgun_events.py
@@ -864,7 +864,7 @@ def _process_support_email(
def _is_outbound_capture_recipient(recipient: str) -> bool:
- local_part, separator, domain = recipient.strip().lower().partition("@")
+ local_part, separator, domain = recipient.strip().lower().rpartition("@")
return local_part == OUTBOUND_CAPTURE_LOCAL_PART and bool(separator and domain)
diff --git a/products/customer_analytics/backend/logic/account_filters.py b/products/customer_analytics/backend/logic/account_filters.py
index ba5e962c3f70..e271c9bfca5c 100644
--- a/products/customer_analytics/backend/logic/account_filters.py
+++ b/products/customer_analytics/backend/logic/account_filters.py
@@ -62,7 +62,7 @@ ACCOUNT_DIRECT_FIELDS = {
def parse_email_search(query: str) -> str | None:
normalized = query.strip().lower()
- local_part, separator, domain = normalized.partition("@")
+ local_part, separator, domain = normalized.rpartition("@")
if not separator or not local_part or "." not in domain:
return None
try:
diff --git a/products/demo/backend/logic/matrix/manager.py b/products/demo/backend/logic/matrix/manager.py
index 8203a48052f4..6338b5490592 100644
--- a/products/demo/backend/logic/matrix/manager.py
+++ b/products/demo/backend/logic/matrix/manager.py
@@ -118,7 +118,9 @@ class MatrixManager:
if existing_user is None or email_collision_handling == "disambiguate":
if existing_user is not None:
print(f"User {email} already exists, trying to find a unique email...")
- original_user, domain = email.split("@")
+ original_user, separator, domain = email.rpartition("@")
+ if not separator:
+ raise exceptions.ValidationError(f"{email} is not an email address.")
for i in range(1, 1000):
email = f"{original_user}+{i}@{domain}"
if User.objects.filter(email=email).exists():
diff --git a/products/messaging/backend/services/transactional_email.py b/products/messaging/backend/services/transactional_email.py
index 38fa12990b9f..4ef3793cee77 100644
--- a/products/messaging/backend/services/transactional_email.py
+++ b/products/messaging/backend/services/transactional_email.py
@@ -16,6 +16,7 @@ import requests
import structlog
from prometheus_client import Counter, Histogram
+from posthog.helpers.email_utils import email_domain
from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models.team import Team
from posthog.plugins.plugin_server_api import (
@@ -229,8 +230,8 @@ def sender_address_error(team_id: int, sender: dict[str, Any]) -> str | None:
config = IntegrationManager.email.credentials.get(team_id, integration_id).config or {}
except IntegrationNotFound:
config = {}
- domain = (config.get("domain") or (config.get("email") or "").partition("@")[2]).lower()
- if domain and address.partition("@")[2].lower() != domain:
+ domain = (config.get("domain") or email_domain(config.get("email") or "") or "").lower()
+ if domain and (email_domain(address) or "").lower() != domain:
return f"Use an address on {domain}, the domain this sender is verified for."
return None
diff --git a/products/security/backend/logic/rules.py b/products/security/backend/logic/rules.py
index 959e9c5b62f9..b79057387211 100644
--- a/products/security/backend/logic/rules.py
+++ b/products/security/backend/logic/rules.py
@@ -32,6 +32,7 @@ class EmailPattern:
literal domain is posthog.com. That check is not repeated here, because a decision never
blocks a posthog.com account.
"""
+ # nosemgrep: email-domain-after-last-at -- the next line refuses a second "@", so first and last agree
local, at, domain = value.partition("@")
if not at or "@" in domain or re.search(r"\s", value):
return None
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index ef749344d7ad..5078cfa367b1 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -693,6 +693,7 @@ def _pin_metadata(client, bucket: str, prefix: str, key: str) -> tuple[dict[str,
The promote job, the served pointer, the pins and the recent and challenger reads all pass this
check, so an experiment family is refused here once for every path."""
+ # nosemgrep: email-domain-after-last-at -- a model@version key, not an email address
model_name, model_version = key.split("@", 1)
if model_name in experiment_names(MODEL_FAMILIES):
return None, (
diff --git a/products/tasks/backend/facade/onboarding.py b/products/tasks/backend/facade/onboarding.py
index 0bd252d4a13a..5cbd0cba297e 100644
--- a/products/tasks/backend/facade/onboarding.py
+++ b/products/tasks/backend/facade/onboarding.py
@@ -10,6 +10,7 @@ import posthoganalytics
from posthog.constants import AvailableFeature
from posthog.event_usage import groups
+from posthog.helpers.email_utils import email_domain
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.temporal.oauth import MCP_READ_SCOPES
@@ -74,7 +75,7 @@ def _started_session_id(team_id: int, user_id: int) -> UUID | None:
def company_domain_from(email: str) -> str | None:
- _, _, domain = email.strip().lower().partition("@")
+ domain = email_domain(email.strip().lower())
if not domain or domain in PERSONAL_EMAIL_DOMAINS:
return None
return normalize_target(domain)
diff --git a/products/workflows/frontend/Channels/EmailDomain/domainInput.ts b/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
index 46c67801347e..df16470939bc 100644
--- a/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
@@ -22,10 +22,10 @@ export interface NormalizedDomainInput {
export const normalizeDomainInput = (raw: string): NormalizedDomainInput => {
let value = raw.trim().toLowerCase()
let localPart: string | null = null
- if (value.includes('@')) {
- const [local, host] = value.split('@')
- localPart = local || null
- value = host ?? ''
+ const atIndex = value.lastIndexOf('@')
+ if (atIndex !== -1) {
+ localPart = value.slice(0, atIndex) || null
+ value = value.slice(atIndex + 1)
}
value = value.replace(/^[a-z]+:\/\//, '')
value = value.split('/')[0].split('?')[0].split(':')[0]
diff --git a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
index c68a968b0d22..c25caee31752 100644
--- a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
+++ b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
@@ -279,7 +279,9 @@ export const emailSetupModalLogic = kea<emailSetupModalLogicType>([
domain: [
(s) => [s.emailSender],
(emailSender: EmailSenderFormType): string => {
- return emailSender.email?.includes('@') ? emailSender.email.split('@')[1] : ''
+ return emailSender.email?.includes('@')
+ ? emailSender.email.slice(emailSender.email.lastIndexOf('@') + 1)
+ : ''
},
],
isDomainVerified: [