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.

feat(messaging): send supabase auth emails through transactional templates (#123966)

Luke Belton7f0e3e6f7afb
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 5070bd99772b..cfde8cf80855 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -439,6 +439,7 @@ rules:
|PlatformAlertDeliveryPath
|PlatformAlertThread
|AlertDestination
+ |SupabaseAuthEmailConfig
|Survey
|SurveyResponseArchive
|TableCertification
@@ -926,6 +927,7 @@ rules:
|PlatformAlertDeliveryPath
|PlatformAlertThread
|AlertDestination
+ |SupabaseAuthEmailConfig
|Survey
|SurveyResponseArchive
|TableCertification
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index ea64ea02cf6c..1f6a104dbe52 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -142,6 +142,9 @@ class HmacSignature:
timestamp_max_future_seconds: int = 300
# Cheap shape gate run before the HMAC, so a probe cannot drive digest CPU.
signature_pattern: re.Pattern[str] | None = None
+ # Set when the header can carry several signatures, such as one per secret while a secret rotates.
+ # Any one of them matching verifies the delivery.
+ signature_separator: str | None = None
def _timestamp_is_fresh(self, timestamp: str) -> bool:
try:
@@ -220,7 +223,13 @@ class HmacSignature:
delivery_id = header_value(headers, self.delivery_id_header) if self.delivery_id_header is not None else None
expected = self._expected_signature(secret, self._signed_bytes(body, timestamp, delivery_id))
- if signatures_match(expected, provided):
+ # Senders differ on punctuation around the separator: Supabase joins its signatures with ", ".
+ candidates = (
+ [part.strip().rstrip(",") for part in provided.split(self.signature_separator) if part.strip()]
+ if self.signature_separator
+ else [provided]
+ )
+ if any(signatures_match(expected, candidate) for candidate in candidates):
return VerificationOutcome.VERIFIED
return VerificationOutcome.INVALID
@@ -242,6 +251,26 @@ class HmacSha256(HmacSignature):
digest: HmacDigest = field(default="sha256", init=False)
+def standard_webhooks_scheme(
+ secret_getter: Callable[[], str | bytes | None], *, tolerance_seconds: int = 300
+) -> HmacSha256:
+ """The Standard Webhooks signature (https://www.standardwebhooks.com): `webhook-signature: v1,<base64>`
+ over `{webhook-id}.{webhook-timestamp}.{body}`. The getter returns the key, already base64-decoded from the
+ sender's `whsec_` secret, because each sender formats and validates that secret its own way."""
+ return HmacSha256(
+ secret_getter=secret_getter,
+ signature_header="webhook-signature",
+ prefix="v1,",
+ encoding="base64",
+ signed_input="id_timestamp_body",
+ delivery_id_header="webhook-id",
+ timestamp_header="webhook-timestamp",
+ timestamp_max_age_seconds=tolerance_seconds,
+ timestamp_max_future_seconds=tolerance_seconds,
+ signature_separator=" ",
+ )
+
+
@frozen
class SnsSignature:
"""AWS SNS message signature plus a topic-ARN allowlist.
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index 4176b4f87395..071ff89c4d5f 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -272,14 +272,16 @@ def _mint_transactional_email_jwt(team_id: int, hog_flow_id: str) -> str:
return WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_PURPOSE.mint({"team_id": team_id, "hog_flow_id": hog_flow_id})
-def send_transactional_email(team_id: int, hog_flow_id: str, payload: dict) -> requests.Response:
+def send_transactional_email(
+ team_id: int, hog_flow_id: str, payload: dict, *, timeout: float = 10
+) -> requests.Response:
"""Run a transactional email's workflow once. `payload` carries the recipient, the recipient's distinct_id and
the template variables. 202 means queued, 429 means the team is over its email quota."""
return internal_requests.post(
CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/transactional_email",
json=payload,
headers={"Authorization": f"Bearer {_mint_transactional_email_jwt(team_id, hog_flow_id)}"},
- timeout=10,
+ timeout=timeout,
)
diff --git a/products/account_audits/backend/presentation/views.py b/products/account_audits/backend/presentation/views.py
index dd69b0ed4d42..0f87d381369f 100644
--- a/products/account_audits/backend/presentation/views.py
+++ b/products/account_audits/backend/presentation/views.py
@@ -16,7 +16,7 @@ from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
-from posthog.ingress.verify.schemes import HmacSha256, VerificationOutcome
+from posthog.ingress.verify.schemes import VerificationOutcome, standard_webhooks_scheme
from posthog.rate_limit import IPThrottle
from products.account_audits.backend.facade import api as account_audits
@@ -165,15 +165,7 @@ class AccountAuditStartViewSet(viewsets.ViewSet):
signing_key = base64.b64decode(secret, validate=True)
except (ValueError, binascii.Error):
return False
- scheme = HmacSha256(
- secret_getter=lambda: signing_key,
- signature_header="webhook-signature",
- prefix="v1,",
- encoding="base64",
- signed_input="id_timestamp_body",
- delivery_id_header="webhook-id",
- timestamp_header="webhook-timestamp",
- timestamp_max_age_seconds=int(SIGNATURE_TOLERANCE.total_seconds()),
- timestamp_max_future_seconds=int(SIGNATURE_TOLERANCE.total_seconds()),
+ scheme = standard_webhooks_scheme(
+ lambda: signing_key, tolerance_seconds=int(SIGNATURE_TOLERANCE.total_seconds())
)
return scheme.verify(body=raw_body, headers=headers).outcome == VerificationOutcome.VERIFIED
diff --git a/products/messaging/backend/facade/contracts.py b/products/messaging/backend/facade/contracts.py
index 666cdc1dea14..f6ecabcad672 100644
--- a/products/messaging/backend/facade/contracts.py
+++ b/products/messaging/backend/facade/contracts.py
@@ -3,6 +3,7 @@ from typing import Any
from uuid import UUID
from posthog.dataclasses import frozen
+from posthog.enums import LabeledStrEnum
class UnlayerError(Exception):
@@ -105,3 +106,55 @@ class QueuedEmail:
message_id: str
# True when an earlier request with the same idempotency key already queued this email.
replayed: bool = False
+
+
+class SupabaseEmailActionType(LabeledStrEnum):
+ """The `email_action_type` values Supabase's Send Email Hook sends."""
+
+ SIGNUP = "signup", "Confirm sign up"
+ INVITE = "invite", "Invite user"
+ MAGICLINK = "magiclink", "Magic link"
+ EMAIL = "email", "Email sign-in code"
+ RECOVERY = "recovery", "Reset password"
+ EMAIL_CHANGE = "email_change", "Change email address"
+ REAUTHENTICATION = "reauthentication", "Reauthentication"
+ PASSWORD_CHANGED_NOTIFICATION = "password_changed_notification", "Password changed"
+ EMAIL_CHANGED_NOTIFICATION = "email_changed_notification", "Email address changed"
+ PHONE_CHANGED_NOTIFICATION = "phone_changed_notification", "Phone number changed"
+ IDENTITY_LINKED_NOTIFICATION = "identity_linked_notification", "Sign-in method linked"
+ IDENTITY_UNLINKED_NOTIFICATION = "identity_unlinked_notification", "Sign-in method removed"
+ MFA_FACTOR_ENROLLED_NOTIFICATION = "mfa_factor_enrolled_notification", "MFA method added"
+ MFA_FACTOR_UNENROLLED_NOTIFICATION = "mfa_factor_unenrolled_notification", "MFA method removed"
+
+
+@frozen
+class SupabaseAuthEmailSettings:
+ supabase_url: str
+ # The secret is write-only, so callers only learn whether one is stored.
+ has_hook_secret: bool
+ # Supabase email action type -> message template id.
+ templates: dict[str, UUID]
+
+
+class SupabaseAuthEmailSettingsInvalid(Exception):
+ """The settings can't be saved as given. The message says which field to fix."""
+
+ def __init__(self, field: str, message: str) -> None:
+ super().__init__(message)
+ self.field = field
+
+
+@frozen
+class SupabaseHookResult:
+ """What to answer Supabase. A `status` of 300 or more fails the user's auth request: Supabase returns that status
+ and `message` to the client."""
+
+ status: int
+ message: str = ""
+ email_action_type: str = ""
+ # True when no email went out on purpose, such as an unmapped notification.
+ skipped: bool = False
+ # Why a send failed, for tracking. The user only sees `message`, which stays neutral.
+ error_code: str = ""
+ # How many emails went out. Email change can send two.
+ sent_count: int = 0
diff --git a/products/messaging/backend/facade/supabase_auth_emails.py b/products/messaging/backend/facade/supabase_auth_emails.py
new file mode 100644
index 000000000000..f2070223dc60
--- /dev/null
+++ b/products/messaging/backend/facade/supabase_auth_emails.py
@@ -0,0 +1,33 @@
+"""Supabase auth emails: Supabase's Send Email Hook sends each auth email through a transactional email template."""
+
+from products.messaging.backend.facade.contracts import (
+ SupabaseAuthEmailSettings,
+ SupabaseAuthEmailSettingsInvalid,
+ SupabaseEmailActionType,
+ SupabaseHookResult,
+)
+from products.messaging.backend.services.supabase_auth_email_templates import STARTER_EMAIL_TYPES
+from products.messaging.backend.services.supabase_auth_emails import (
+ MAX_HOOK_BODY_BYTES,
+ create_starter_templates,
+ delete_settings,
+ get_settings,
+ handle_send_email_hook,
+ save_settings,
+ template_workflow_ids,
+)
+
+__all__ = [
+ "MAX_HOOK_BODY_BYTES",
+ "STARTER_EMAIL_TYPES",
+ "SupabaseAuthEmailSettings",
+ "SupabaseAuthEmailSettingsInvalid",
+ "SupabaseEmailActionType",
+ "SupabaseHookResult",
+ "create_starter_templates",
+ "delete_settings",
+ "get_settings",
+ "handle_send_email_hook",
+ "save_settings",
+ "template_workflow_ids",
+]
diff --git a/products/messaging/backend/migrations/0010_supabase_auth_email_config.py b/products/messaging/backend/migrations/0010_supabase_auth_email_config.py
new file mode 100644
index 000000000000..17194e8256d1
--- /dev/null
+++ b/products/messaging/backend/migrations/0010_supabase_auth_email_config.py
@@ -0,0 +1,70 @@
+# Generated by Django 5.2.18 on 2026-10-27 11:04
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("messaging", "0009_provider_import_run"),
+ ("posthog", "1409_activitylog_team_user_created_at_index"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SupabaseAuthEmailConfig",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("supabase_url", models.URLField(blank=True, default="")),
+ (
+ "hook_secret",
+ posthog.helpers.encrypted_fields.EncryptedTextField(blank=True, null=True),
+ ),
+ ("templates", models.JSONField(default=dict)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_messaging_supabase_auth_email_config",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team",),
+ name="unique_supabase_auth_email_config_per_team",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/messaging/backend/migrations/max_migration.txt b/products/messaging/backend/migrations/max_migration.txt
index e548ada71880..3512088bfe35 100644
--- a/products/messaging/backend/migrations/max_migration.txt
+++ b/products/messaging/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_provider_import_run
+0010_supabase_auth_email_config
diff --git a/products/messaging/backend/models/__init__.py b/products/messaging/backend/models/__init__.py
index 2e0f1492f947..c09870b3b017 100644
--- a/products/messaging/backend/models/__init__.py
+++ b/products/messaging/backend/models/__init__.py
@@ -4,6 +4,7 @@ from .message_suppression import MessageSuppression, SuppressionSource
from .message_template import MessageTemplate
from .optout_sync_config import OptOutSyncConfig
from .provider_import_run import ProviderImportRun
+from .supabase_auth_email_config import SupabaseAuthEmailConfig
__all__ = [
"ALL_MESSAGE_PREFERENCE_CATEGORY_ID",
@@ -15,5 +16,6 @@ __all__ = [
"OptOutSyncConfig",
"PreferenceStatus",
"ProviderImportRun",
+ "SupabaseAuthEmailConfig",
"SuppressionSource",
]
diff --git a/products/messaging/backend/models/supabase_auth_email_config.py b/products/messaging/backend/models/supabase_auth_email_config.py
new file mode 100644
index 000000000000..eab121c34e2c
--- /dev/null
+++ b/products/messaging/backend/models/supabase_auth_email_config.py
@@ -0,0 +1,32 @@
+from django.db import models
+
+from posthog.helpers.encrypted_fields import EncryptedTextField
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class SupabaseAuthEmailConfig(TeamScopedRootMixin, UUIDModel):
+ """Sends a Supabase project's auth emails through the team's transactional email templates.
+
+ Supabase posts every auth email to the team's Send Email Hook endpoint, signed with `hook_secret`.
+ `templates` maps each Supabase email action type to the message template that sends it.
+ """
+
+ # db_constraint=False so CreateModel takes no lock on posthog_team / posthog_user.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+ # The Supabase project URL, such as https://abcdefgh.supabase.co. Confirmation links point at its verify endpoint.
+ supabase_url = models.URLField(max_length=200, blank=True, default="")
+ # The Standard Webhooks secret Supabase signs the hook with, as `v1,whsec_<base64>`.
+ hook_secret = EncryptedTextField(null=True, blank=True)
+ # Supabase email action type -> message template id.
+ templates = models.JSONField(default=dict)
+
+ class Meta:
+ app_label = "messaging"
+ db_table = "posthog_messaging_supabase_auth_email_config"
+ constraints = [models.UniqueConstraint(fields=["team"], name="unique_supabase_auth_email_config_per_team")]
diff --git a/products/messaging/backend/presentation/views/supabase_auth_emails.py b/products/messaging/backend/presentation/views/supabase_auth_emails.py
new file mode 100644
index 000000000000..86870cc2bd39
--- /dev/null
+++ b/products/messaging/backend/presentation/views/supabase_auth_emails.py
@@ -0,0 +1,348 @@
+import time
+from typing import Any
+
+from django.conf import settings
+from django.urls import reverse
+
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from prometheus_client import Counter, Histogram
+from rest_framework import exceptions, serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.permissions import AllowAny
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.documentation import _FallbackSerializer
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_team_action, report_user_action
+from posthog.models import Team
+from posthog.ph_client import feature_enabled_or_false
+
+from products.messaging.backend.facade.contracts import TransactionalEmailError
+from products.messaging.backend.facade.supabase_auth_emails import (
+ MAX_HOOK_BODY_BYTES,
+ STARTER_EMAIL_TYPES,
+ SupabaseAuthEmailSettings,
+ SupabaseAuthEmailSettingsInvalid,
+ SupabaseEmailActionType,
+ SupabaseHookResult,
+ create_starter_templates,
+ delete_settings,
+ get_settings,
+ handle_send_email_hook,
+ save_settings,
+ template_workflow_ids,
+)
+from products.workflows.backend.facade.api import WorkflowAccessDenied, WorkflowNotFound
+from products.workflows.backend.facade.workflows import get_workflow
+
+logger = structlog.get_logger(__name__)
+
+# pinned: feature flag key, a rename makes a new flag
+SUPABASE_AUTH_EMAILS_FLAG = "workflows-supabase-auth-emails"
+
+# Every hook call is counted here rather than as an analytics event, because calls scale with the sign-ups and
+# log-ins of each customer's own app.
+HOOK_CALLS = Counter(
+ "messaging_supabase_auth_email_hook_total",
+ "Supabase Send Email Hook calls, by the status PostHog answered and why a send failed.",
+ labelnames=["status", "email_action_type", "error_code"],
+)
+# Supabase fails the sign-up when the hook takes over 5 seconds.
+HOOK_DURATION = Histogram(
+ "messaging_supabase_auth_email_hook_duration_seconds",
+ "Time to verify a Supabase Send Email Hook call and send its emails.",
+ buckets=(0.25, 0.5, 1, 2, 3, 4, 5, 7.5, 10),
+)
+
+# Current Supabase sends email sign-in codes as `magiclink`, so `email` only comes from older self-hosted versions.
+# The hook still accepts it and an existing mapping still saves, but the mapping table doesn't offer it.
+HIDDEN_EMAIL_TYPES = frozenset({SupabaseEmailActionType.EMAIL})
+
+
+def supabase_auth_emails_enabled(team: Team) -> bool:
+ return feature_enabled_or_false(
+ SUPABASE_AUTH_EMAILS_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ send_feature_flag_events=False,
+ )
+
+
+class SupabaseEmailTypeSerializer(serializers.Serializer):
+ value = serializers.ChoiceField(
+ choices=SupabaseEmailActionType.choices, help_text="The `email_action_type` Supabase sends for this email."
+ )
+ label = serializers.CharField(help_text="What the email is for, in words a person reads.") # type: ignore[assignment]
+ has_starter_template = serializers.BooleanField(
+ help_text="Whether creating starter templates makes a template for this email."
+ )
+
+
+class SupabaseAuthEmailSettingsSerializer(serializers.Serializer):
+ supabase_url = serializers.CharField(
+ help_text="The Supabase project URL, such as https://abcdefgh.supabase.co. Confirmation links point at its "
+ "/auth/v1/verify endpoint."
+ )
+ has_hook_secret = serializers.BooleanField(
+ help_text="Whether a Send Email Hook secret is stored. The secret itself is never returned."
+ )
+ templates = serializers.DictField(
+ child=serializers.UUIDField(),
+ help_text="Supabase email action type (such as `signup` or `recovery`) to the transactional message "
+ "template that sends it. An auth email with no template fails in Supabase.",
+ )
+ hook_url = serializers.CharField(
+ help_text="The URL to paste into Supabase as the HTTPS endpoint of the Send Email Hook."
+ )
+ email_types = SupabaseEmailTypeSerializer(
+ many=True, help_text="Every email Supabase can send through the hook, core auth emails first."
+ )
+
+
+class SupabaseAuthEmailSettingsUpdateSerializer(serializers.Serializer):
+ supabase_url = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=200,
+ help_text="The Supabase project URL, such as https://abcdefgh.supabase.co.",
+ )
+ hook_secret = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ write_only=True,
+ max_length=500,
+ help_text="The Send Email Hook secret from Supabase, starting with v1,whsec_. Leave it out to keep the "
+ "stored secret.",
+ )
+ templates = serializers.DictField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text="Supabase email action type to transactional message template id. Replaces the whole mapping. "
+ f"Valid action types: {', '.join(SupabaseEmailActionType.values)}.",
+ )
+
+
+class SupabaseAuthEmailsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Send a Supabase project's auth emails through transactional email templates."""
+
+ scope_object = "hog_flow"
+ scope_object_read_actions = ["get_settings"]
+ scope_object_write_actions = ["update_settings", "disconnect", "starter_templates"]
+ serializer_class = _FallbackSerializer
+
+ def _require_flag(self) -> None:
+ if not supabase_auth_emails_enabled(self.team):
+ raise NotFound()
+
+ def _require_editor(self) -> None:
+ # Team-wide settings with no per-workflow object, so a grant on one workflow is not enough.
+ if not self.user_access_control.check_access_level_for_resource("hog_flow", "editor"):
+ raise PermissionDenied("You need workflow editor access to change the Supabase auth emails.")
+
+ def _require_workflow_editor(self, templates: dict[str, Any]) -> None:
+ # Whoever saves these settings can sign hook calls that send every mapped template, so they need the same
+ # workflow access as sending each template directly. A save that keeps a mapping still counts.
+ for hog_flow_id in template_workflow_ids(self.team_id, set(templates.values())):
+ try:
+ get_workflow(
+ team_id=self.team_id,
+ workflow_id=str(hog_flow_id),
+ user_access_control=self.user_access_control,
+ required_level="editor",
+ )
+ except WorkflowAccessDenied:
+ raise PermissionDenied(
+ "You need editor access to the transactional email workflow of every mapped template."
+ ) from None
+ except WorkflowNotFound:
+ continue
+
+ def _response(self, current: SupabaseAuthEmailSettings) -> Response:
+ hook_path = reverse("messaging_supabase_send_email_hook", kwargs={"team_id": self.team_id})
+ data = {
+ "supabase_url": current.supabase_url,
+ "has_hook_secret": current.has_hook_secret,
+ "templates": current.templates,
+ "hook_url": f"{settings.SITE_URL}{hook_path}",
+ "email_types": [
+ {"value": t.value, "label": t.label, "has_starter_template": t in STARTER_EMAIL_TYPES}
+ for t in SupabaseEmailActionType
+ if t not in HIDDEN_EMAIL_TYPES
+ ],
+ }
+ return Response(SupabaseAuthEmailSettingsSerializer(data).data)
+
+ @extend_schema(
+ responses={200: SupabaseAuthEmailSettingsSerializer},
+ summary="Get the Supabase auth email settings",
+ )
+ @action(detail=False, methods=["GET"], url_path="settings")
+ def get_settings(self, request: Request, **kwargs: Any) -> Response:
+ self._require_flag()
+ return self._response(get_settings(self.team_id))
+
+ @validated_request(
+ SupabaseAuthEmailSettingsUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=SupabaseAuthEmailSettingsSerializer, description="The saved settings"),
+ 400: OpenApiResponse(description="A field is invalid. The error names the field to fix."),
+ },
+ summary="Update the Supabase auth email settings",
+ )
+ @get_settings.mapping.patch
+ def update_settings(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ self._require_flag()
+ self._require_editor()
+ self._require_workflow_editor(request.validated_data.get("templates", get_settings(self.team_id).templates))
+ try:
+ saved = save_settings(self.team_id, request.user.id, **request.validated_data)
+ except SupabaseAuthEmailSettingsInvalid as e:
+ raise exceptions.ValidationError({e.field: str(e)}) from None
+ try:
+ # pinned: analytics event name, renaming breaks dashboards
+ report_user_action(
+ request.user,
+ "supabase auth emails settings saved",
+ {
+ "fields": sorted(request.validated_data),
+ "has_hook_secret": saved.has_hook_secret,
+ "mapped_email_types": sorted(saved.templates),
+ },
+ team=self.team,
+ request=request,
+ )
+ except Exception as e:
+ logger.warning("Failed to capture Supabase auth email usage event", error=str(e))
+ return self._response(saved)
+
+ @extend_schema(
+ request=None,
+ responses={
+ 200: OpenApiResponse(response=SupabaseAuthEmailSettingsSerializer, description="The empty settings")
+ },
+ summary="Disconnect the Supabase project",
+ description="Remove the project URL, hook secret and template mappings. The hook then refuses every call, so "
+ "turn off the Send Email hook in Supabase first. The templates themselves stay.",
+ )
+ @get_settings.mapping.delete
+ def disconnect(self, request: Request, **kwargs: Any) -> Response:
+ self._require_flag()
+ self._require_editor()
+ cleared = delete_settings(self.team_id)
+ try:
+ # pinned: analytics event name, renaming breaks dashboards
+ report_user_action(request.user, "supabase auth emails disconnected", {}, team=self.team, request=request)
+ except Exception as e:
+ logger.warning("Failed to capture Supabase auth email usage event", error=str(e))
+ return self._response(cleared)
+
+ @extend_schema(
+ request=None,
+ responses={
+ 200: OpenApiResponse(response=SupabaseAuthEmailSettingsSerializer, description="The saved settings"),
+ 400: OpenApiResponse(description="The team has no verified email sender"),
+ },
+ summary="Create starter templates for the Supabase auth emails",
+ description="Create a transactional template for each core Supabase auth email that has no template yet, "
+ "and map it. Needs a verified email sender.",
+ )
+ @action(detail=False, methods=["POST"])
+ def starter_templates(self, request: Request, **kwargs: Any) -> Response:
+ self._require_flag()
+ self._require_editor()
+ mapped_before = len(get_settings(self.team_id).templates)
+ try:
+ saved = create_starter_templates(self.team_id, request.user.id)
+ except TransactionalEmailError as e:
+ raise exceptions.ValidationError({"detail": str(e)}) from None
+ try:
+ # pinned: analytics event name, renaming breaks dashboards
+ report_user_action(
+ request.user,
+ "supabase auth emails starter templates created",
+ {"created_count": len(saved.templates) - mapped_before},
+ team=self.team,
+ request=request,
+ )
+ except Exception as e:
+ logger.warning("Failed to capture Supabase auth email usage event", error=str(e))
+ return self._response(saved)
+
+
+class SupabaseSendEmailHookView(APIView):
+ """Supabase's Send Email Hook. Supabase signs each request with the team's hook secret, so no session or API
+ key applies here."""
+
+ authentication_classes: list[type] = []
+ permission_classes = [AllowAny]
+ # Hosted Supabase projects share outbound IPs, so the default anonymous IP buckets would let one project's
+ # sign-ups refuse another's. The HMAC check is cheap, like the other inbound webhooks, which aren't throttled.
+ throttle_classes: list[type] = []
+
+ @staticmethod
+ def _answer(result: SupabaseHookResult, *, verified: bool) -> Response:
+ if result.status < 300:
+ # Supabase's hook contract fixes this body, and the hook is not part of the OpenAPI schema.
+ return Response({}, status=200) # nosemgrep: api-response-must-match-schema
+ # Supabase replaces the message of any non-2xx answer with a generic one. It passes on an error body that
+ # comes with a 200, and answers the client with its `http_code`. A request that isn't verified as
+ # Supabase's gets the real status, so an unsigned caller never gets a 200.
+ body = {"error": {"http_code": result.status, "message": result.message}}
+ return Response(body, status=200 if verified and result.status != 401 else result.status)
+
+ def post(self, request: Request, team_id: str) -> Response:
+ try:
+ if int(request.META.get("CONTENT_LENGTH") or 0) > MAX_HOOK_BODY_BYTES:
+ return self._answer(
+ SupabaseHookResult(status=413, message="The hook payload is too large."), verified=False
+ )
+ except ValueError:
+ return self._answer(
+ SupabaseHookResult(status=400, message="The hook payload isn't a Send Email Hook payload."),
+ verified=False,
+ )
+ team = Team.objects.filter(id=team_id).first()
+ # No flag check here: a config only exists if the flag was on when it was saved, and a flag that rolls back
+ # or fails to evaluate would fail every connected project's sign-ups.
+ if team is None:
+ return self._answer(
+ SupabaseHookResult(status=401, message="The hook signature doesn't match. Check the hook secret."),
+ verified=False,
+ )
+ started = time.monotonic()
+ result = handle_send_email_hook(team, request.body, request.headers)
+ duration = time.monotonic() - started
+ # The payload sets this, so an unknown value must not become a new metric series.
+ action = result.email_action_type if result.email_action_type in SupabaseEmailActionType.values else "other"
+ HOOK_DURATION.observe(duration)
+ HOOK_CALLS.labels(status=str(result.status), email_action_type=action, error_code=result.error_code).inc()
+ # A request that isn't verified as Supabase's could come from anyone, so it records no usage for the team.
+ if result.status == 401:
+ return self._answer(result, verified=False)
+ if result.status < 300:
+ return self._answer(result, verified=True)
+ try:
+ # Only failures, so the event volume doesn't grow with the customer's traffic. Each template tracks its sends.
+ # The hook has no user, so the event is tracked against the team. A 401 here usually means a wrong secret.
+ # pinned: analytics event name, renaming breaks dashboards
+ report_team_action(
+ team,
+ "supabase auth email hook",
+ {
+ "status": result.status,
+ "email_action_type": action,
+ "skipped": result.skipped,
+ "error_code": result.error_code,
+ "sent_count": result.sent_count,
+ "duration_ms": round(duration * 1000),
+ },
+ )
+ except Exception as e:
+ logger.warning("Failed to capture Supabase auth email usage event", error=str(e))
+ return self._answer(result, verified=True)
diff --git a/products/messaging/backend/routes.py b/products/messaging/backend/routes.py
index 87b8d2b8e9ba..9b74b67834af 100644
--- a/products/messaging/backend/routes.py
+++ b/products/messaging/backend/routes.py
@@ -1,3 +1,5 @@
+from django.urls import URLPattern, re_path
+
from posthog.api.routing import RouterRegistry
from products.messaging.backend.presentation.views.message_categories import MessageCategoryViewSet
@@ -8,6 +10,18 @@ from products.messaging.backend.presentation.views.message_templates import (
MessagingSendViewSet,
)
from products.messaging.backend.presentation.views.provider_imports import ProviderImportViewSet
+from products.messaging.backend.presentation.views.supabase_auth_emails import (
+ SupabaseAuthEmailsViewSet,
+ SupabaseSendEmailHookView,
+)
+
+webhook_urlpatterns: list[URLPattern] = [
+ re_path(
+ r"^supabase/(?P<team_id>\d+)/send-email/?$",
+ SupabaseSendEmailHookView.as_view(),
+ name="messaging_supabase_send_email_hook",
+ ),
+]
def register_routes(routers: RouterRegistry) -> None:
@@ -28,3 +42,9 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"messaging_provider_imports", ProviderImportViewSet, "project_messaging_provider_imports", ["team_id"]
)
+ routers.projects.register(
+ r"messaging_supabase_auth_emails",
+ SupabaseAuthEmailsViewSet,
+ "project_messaging_supabase_auth_emails",
+ ["team_id"],
+ )
diff --git a/products/messaging/backend/services/supabase_auth_email_templates.py b/products/messaging/backend/services/supabase_auth_email_templates.py
new file mode 100644
index 000000000000..640b971e181d
--- /dev/null
+++ b/products/messaging/backend/services/supabase_auth_email_templates.py
@@ -0,0 +1,230 @@
+"""Starter templates for the Supabase auth emails, written against the variables the Send Email Hook passes."""
+
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.messaging.backend.facade.contracts import SupabaseEmailActionType
+
+
+@frozen
+class StarterTemplate:
+ name: str
+ subject: str
+ preheader: str
+ heading: str
+ body: str
+ # Without a button the email shows the one-time code instead.
+ button_label: str | None
+
+
+STARTER_TEMPLATES: dict[SupabaseEmailActionType, StarterTemplate] = {
+ SupabaseEmailActionType.SIGNUP: StarterTemplate(
+ name="Supabase: confirm sign up",
+ subject="Confirm your email address",
+ preheader="Confirm your email address to finish signing up.",
+ heading="Confirm your email address",
+ body="Confirm your email address to finish signing up.",
+ button_label="Confirm email address",
+ ),
+ SupabaseEmailActionType.INVITE: StarterTemplate(
+ name="Supabase: invite user",
+ subject="You have been invited",
+ preheader="Accept the invite to create your account.",
+ heading="You have been invited",
+ body="You have been invited to create an account. Accept the invite to set it up.",
+ button_label="Accept invite",
+ ),
+ SupabaseEmailActionType.MAGICLINK: StarterTemplate(
+ name="Supabase: magic link",
+ subject="Your sign-in link",
+ preheader="Use this link to sign in.",
+ heading="Sign in",
+ body="Use the button below to sign in. If you didn't ask for this link, you can ignore this email.",
+ button_label="Sign in",
+ ),
+ SupabaseEmailActionType.RECOVERY: StarterTemplate(
+ name="Supabase: reset password",
+ subject="Reset your password",
+ preheader="Use this link to choose a new password.",
+ heading="Reset your password",
+ body="Use the button below to choose a new password. If you didn't ask to reset it, you can ignore this email.",
+ button_label="Reset password",
+ ),
+ SupabaseEmailActionType.EMAIL_CHANGE: StarterTemplate(
+ name="Supabase: change email address",
+ subject="Confirm your new email address",
+ preheader="Confirm the change to your email address.",
+ heading="Confirm your email address change",
+ body="Confirm that you want to change your email address from {{ variables.email }} to {{ variables.new_email }}.",
+ button_label="Confirm change",
+ ),
+ SupabaseEmailActionType.REAUTHENTICATION: StarterTemplate(
+ name="Supabase: reauthentication",
+ subject="Your verification code",
+ preheader="Enter this code to confirm it's you.",
+ heading="Confirm it's you",
+ body="Enter this code to continue. If you didn't ask for it, you can ignore this email.",
+ button_label=None,
+ ),
+}
+
+STARTER_EMAIL_TYPES = frozenset(STARTER_TEMPLATES)
+
+
+def _html(template: StarterTemplate) -> str:
+ if template.button_label:
+ action = (
+ '<p style="margin:24px 0">'
+ '<a href="{{ variables.confirmation_url }}" style="background:#1d4aff;border-radius:6px;color:#ffffff;'
+ f'display:inline-block;font-weight:600;padding:12px 20px;text-decoration:none">{template.button_label}</a>'
+ "</p>"
+ '<p style="color:#6b7280;font-size:13px">Or enter this code: <strong>{{ variables.token }}</strong></p>'
+ )
+ else:
+ action = '<p style="font-size:28px;font-weight:600;letter-spacing:4px;margin:24px 0">{{ variables.token }}</p>'
+ return (
+ '<div style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif;'
+ 'color:#111827;line-height:1.5;max-width:480px;margin:0 auto;padding:24px">'
+ f'<h1 style="font-size:20px;margin:0 0 16px">{template.heading}</h1>'
+ f"<p>{template.body}</p>"
+ f"{action}"
+ "</div>"
+ )
+
+
+def _block(block_id: str, block_type: str, number: int, values: dict[str, Any]) -> dict[str, Any]:
+ html_class = f"u_content_{block_type}"
+ return {
+ "id": block_id,
+ "type": block_type,
+ "values": {
+ "textAlign": "left",
+ **values,
+ "_meta": {"htmlID": f"{html_class}_{number}", "htmlClassNames": html_class},
+ },
+ }
+
+
+def _paragraph(block_id: str, number: int, text: str, **values: str) -> dict[str, Any]:
+ return _block(
+ block_id,
+ "text",
+ number,
+ {"text": f"<p>{text}</p>", "fontSize": "16px", "lineHeight": "150%", "containerPadding": "8px 24px", **values},
+ )
+
+
+def _design(template: StarterTemplate) -> dict[str, Any]:
+ """The same email as `_html`, built from native Unlayer blocks so each part opens as its own editable block.
+ Ids are fixed, so every starter set gets the same design."""
+ contents = [
+ _block(
+ "heading",
+ "heading",
+ 1,
+ {
+ "headingType": "h1",
+ "text": template.heading,
+ "fontSize": "22px",
+ "fontWeight": 600,
+ "lineHeight": "130%",
+ "containerPadding": "32px 24px 8px",
+ },
+ ),
+ _paragraph("text-body", 1, template.body),
+ ]
+ if template.button_label:
+ contents += [
+ _block(
+ "button-confirm",
+ "button",
+ 1,
+ {
+ "text": template.button_label,
+ "href": {"name": "web", "values": {"href": "{{ variables.confirmation_url }}", "target": "_blank"}},
+ "buttonColors": {
+ "color": "#ffffff",
+ "backgroundColor": "#1d4aff",
+ "hoverColor": "#ffffff",
+ "hoverBackgroundColor": "#1d4aff",
+ },
+ "fontSize": "16px",
+ "padding": "12px 20px",
+ "borderRadius": "6px",
+ "containerPadding": "16px 24px",
+ },
+ ),
+ _paragraph(
+ "text-code",
+ 2,
+ "Or enter this code: <strong>{{ variables.token }}</strong>",
+ fontSize="13px",
+ color="#6b7280",
+ ),
+ ]
+ else:
+ contents.append(
+ _paragraph(
+ "text-code",
+ 2,
+ "<strong>{{ variables.token }}</strong>",
+ fontSize="28px",
+ lineHeight="130%",
+ containerPadding="16px 24px 32px",
+ )
+ )
+
+ counters = {"u_row": 1, "u_column": 1}
+ for content in contents:
+ key = f"u_content_{content['type']}"
+ counters[key] = counters.get(key, 0) + 1
+ return {
+ "counters": counters,
+ "schemaVersion": 16,
+ "body": {
+ "id": "supabase-auth-email",
+ "headers": [],
+ "footers": [],
+ "values": {
+ "backgroundColor": "#ffffff",
+ "contentWidth": "480px",
+ "textColor": "#111827",
+ "fontFamily": {"label": "Helvetica", "value": "helvetica,arial,sans-serif"},
+ },
+ "rows": [
+ {
+ "id": "row-main",
+ "cells": [1],
+ "values": {"padding": "0px", "_meta": {"htmlID": "u_row_1", "htmlClassNames": "u_row"}},
+ "columns": [
+ {
+ "id": "column-main",
+ "values": {"_meta": {"htmlID": "u_column_1", "htmlClassNames": "u_column"}},
+ "contents": contents,
+ }
+ ],
+ }
+ ],
+ },
+ }
+
+
+def _text(template: StarterTemplate) -> str:
+ if template.button_label:
+ action = f"{template.button_label}: {{{{ variables.confirmation_url }}}}\n\nOr enter this code: {{{{ variables.token }}}}"
+ else:
+ action = "Your code: {{ variables.token }}"
+ return f"{template.heading}\n\n{template.body}\n\n{action}\n"
+
+
+def starter_template_content(template: StarterTemplate) -> dict:
+ return {
+ "email": {
+ "subject": template.subject,
+ "preheader": template.preheader,
+ "html": _html(template),
+ "text": _text(template),
+ "design": _design(template),
+ }
+ }
diff --git a/products/messaging/backend/services/supabase_auth_emails.py b/products/messaging/backend/services/supabase_auth_emails.py
new file mode 100644
index 000000000000..cb48aa44e59c
--- /dev/null
+++ b/products/messaging/backend/services/supabase_auth_emails.py
@@ -0,0 +1,392 @@
+"""Supabase auth emails: Supabase's Send Email Hook posts each auth email here, and each one goes out as a
+transactional email from the template mapped to its email action type.
+
+The hook is synchronous. Supabase waits for the answer before it finishes the user's sign up or sign in, and gives
+up after 5 seconds, so the hook only queues the sends and never waits for delivery. A failed or timed-out hook rolls
+the sign up back in Supabase."""
+
+import json
+import time
+import base64
+import binascii
+from collections.abc import Mapping
+from functools import partial
+from typing import Any
+from urllib.parse import urlencode, urlsplit
+from uuid import UUID
+
+from django.conf import settings
+from django.core.exceptions import ObjectDoesNotExist
+from django.db import transaction
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.ingress.verify.schemes import VerificationOutcome, standard_webhooks_scheme
+from posthog.models.team import Team
+
+from products.messaging.backend.facade.contracts import (
+ DeliveryUnavailable,
+ IdempotencyKeyInFlight,
+ QuotaLimited,
+ SupabaseAuthEmailSettings,
+ SupabaseAuthEmailSettingsInvalid,
+ SupabaseEmailActionType,
+ SupabaseHookResult,
+ TransactionalEmailError,
+)
+from products.messaging.backend.models import MessageTemplate, SupabaseAuthEmailConfig
+from products.messaging.backend.services.message_templates import create_template
+from products.messaging.backend.services.supabase_auth_email_templates import (
+ STARTER_TEMPLATES,
+ starter_template_content,
+)
+from products.messaging.backend.services.transactional_email import make_transactional, send_transactional_email
+
+logger = structlog.get_logger(__name__)
+
+MAX_HOOK_BODY_BYTES = 256 * 1024
+# The Standard Webhooks spec asks for at least 24 bytes. A shorter key is almost always a truncated paste.
+MIN_SECRET_KEY_BYTES = 24
+SIGNATURE_TOLERANCE_SECONDS = 5 * 60
+LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
+SEND_FAILED_MESSAGE = "We couldn't send your email. Try again in a few minutes."
+# Supabase gives up on the hook after 5 seconds, so every send shares this budget and the answer still arrives.
+SEND_BUDGET_SECONDS = 4.0
+MIN_SEND_SECONDS = 0.25
+
+
+def _signing_key(hook_secret: str) -> bytes | None:
+ encoded = hook_secret.strip().removeprefix("v1,").removeprefix("whsec_")
+ try:
+ key = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error):
+ return None
+ return key if len(key) >= MIN_SECRET_KEY_BYTES else None
+
+
+def _normalized_supabase_url(supabase_url: str) -> str:
+ url = supabase_url.strip().rstrip("/")
+ parts = urlsplit(url)
+ # A local Supabase stack serves plain http, which only a development instance can reach anyway.
+ local_http = settings.DEBUG and parts.scheme == "http" and parts.hostname in LOOPBACK_HOSTS
+ if (
+ (parts.scheme != "https" and not local_http)
+ or not parts.hostname
+ or parts.path
+ or parts.query
+ or parts.fragment
+ ):
+ raise SupabaseAuthEmailSettingsInvalid(
+ "supabase_url", "Enter your Supabase project URL, such as https://abcdefgh.supabase.co."
+ )
+ return url
+
+
+def _config(team_id: int) -> SupabaseAuthEmailConfig | None:
+ return SupabaseAuthEmailConfig.objects.for_team(team_id).first()
+
+
+def _settings(config: SupabaseAuthEmailConfig | None) -> SupabaseAuthEmailSettings:
+ if config is None:
+ return SupabaseAuthEmailSettings(supabase_url="", has_hook_secret=False, templates={})
+ return SupabaseAuthEmailSettings(
+ supabase_url=config.supabase_url,
+ has_hook_secret=bool(config.hook_secret),
+ templates={action: UUID(template_id) for action, template_id in config.templates.items()},
+ )
+
+
+def get_settings(team_id: int) -> SupabaseAuthEmailSettings:
+ return _settings(_config(team_id))
+
+
+def _sendable_template_ids(team_id: int, template_ids: set[UUID]) -> set[UUID]:
+ # Auth emails carry sign-in codes and reset links, and only a sensitive template keeps them out of stored
+ # sends and click tracking.
+ return set(
+ MessageTemplate.objects.filter(
+ team_id=team_id,
+ id__in=template_ids,
+ deleted=False,
+ transactional_hog_flow_id__isnull=False,
+ sensitive=True,
+ ).values_list("id", flat=True)
+ )
+
+
+def template_workflow_ids(team_id: int, template_ids: set[UUID]) -> set[UUID]:
+ """The transactional workflows the given templates send through."""
+ workflow_ids = MessageTemplate.objects.filter(
+ team_id=team_id, id__in=template_ids, transactional_hog_flow_id__isnull=False
+ ).values_list("transactional_hog_flow_id", flat=True)
+ return {workflow_id for workflow_id in workflow_ids if workflow_id is not None}
+
+
+def _check_templates(team_id: int, templates: Mapping[str, UUID]) -> None:
+ for action in templates:
+ if action not in SupabaseEmailActionType.values:
+ raise SupabaseAuthEmailSettingsInvalid("templates", f"{action} isn't a Supabase email type.")
+ found = _sendable_template_ids(team_id, set(templates.values()))
+ missing = [action for action, template_id in templates.items() if template_id not in found]
+ if missing:
+ labels = ", ".join(SupabaseEmailActionType(action).label for action in missing)
+ raise SupabaseAuthEmailSettingsInvalid(
+ "templates",
+ f"Pick a transactional template marked sensitive for: {labels}. Sensitive templates keep sign-in codes "
+ "and reset links out of stored emails.",
+ )
+
+
+def save_settings(
+ team_id: int,
+ user_id: int | None,
+ *,
+ supabase_url: str | None = None,
+ hook_secret: str | None = None,
+ templates: Mapping[str, UUID] | None = None,
+) -> SupabaseAuthEmailSettings:
+ """Update the fields that are passed."""
+ if supabase_url:
+ supabase_url = _normalized_supabase_url(supabase_url)
+ if hook_secret and _signing_key(hook_secret) is None:
+ raise SupabaseAuthEmailSettingsInvalid(
+ "hook_secret", "Paste the full hook secret from Supabase. It starts with v1,whsec_."
+ )
+ if templates is not None:
+ _check_templates(team_id, templates)
+
+ with transaction.atomic():
+ config, _ = (
+ SupabaseAuthEmailConfig.objects.for_team(team_id)
+ .select_for_update()
+ .get_or_create(team_id=team_id, defaults={"created_by_id": user_id})
+ )
+ if supabase_url is not None:
+ config.supabase_url = supabase_url
+ if hook_secret:
+ config.hook_secret = hook_secret.strip()
+ if templates is not None:
+ config.templates = {action: str(template_id) for action, template_id in templates.items()}
+ config.save()
+ return _settings(config)
+
+
+def delete_settings(team_id: int) -> SupabaseAuthEmailSettings:
+ """Remove the project URL, hook secret and template mappings, so the hook refuses every call. The templates stay."""
+ SupabaseAuthEmailConfig.objects.for_team(team_id).delete()
+ return _settings(None)
+
+
+def create_starter_templates(team_id: int, user_id: int | None) -> SupabaseAuthEmailSettings:
+ """Create a transactional template for each core auth email that has none mapped yet, and map it.
+ Raises SenderUnavailable when the team has no verified sender."""
+ # One transaction, so a missing sender leaves no half-made templates behind.
+ with transaction.atomic():
+ # Locks the config first, so two concurrent calls can't both create a full set of templates.
+ SupabaseAuthEmailConfig.objects.for_team(team_id).select_for_update().get_or_create(
+ team_id=team_id, defaults={"created_by_id": user_id}
+ )
+ mapped = get_settings(team_id).templates
+ # A mapping whose template was deleted or stopped being transactional counts as unmapped, so it gets a
+ # starter template instead of failing the whole call.
+ sendable = _sendable_template_ids(team_id, set(mapped.values()))
+ templates = {action: template_id for action, template_id in mapped.items() if template_id in sendable}
+ for action, starter in STARTER_TEMPLATES.items():
+ if action in templates:
+ continue
+ template = create_template(
+ team_id,
+ user_id,
+ {
+ "name": starter.name,
+ "type": "email",
+ "content": starter_template_content(starter),
+ "sensitive": True,
+ },
+ )
+ make_transactional(team_id, template.id, user_id=user_id, from_integration_id=None)
+ templates[action] = template.id
+ return save_settings(team_id, user_id, templates=templates)
+
+
+@frozen
+class _HookUser:
+ id: str
+ email: str
+ new_email: str
+ user_metadata: dict[str, Any]
+
+
+@frozen
+class _HookEmailData:
+ # Supabase keeps this id when it retries, but gives every attempt a new `webhook-id`.
+ request_id: str
+ email_action_type: str
+ token: str
+ token_hash: str
+ token_new: str
+ token_hash_new: str
+ redirect_to: str
+ # The address a user changed away from, set on the email-changed notification.
+ old_email: str
+
+
+@frozen
+class _Send:
+ to: str
+ token: str
+ token_hash: str
+
+
+def _str(data: Mapping[str, Any], key: str) -> str:
+ value = data.get(key)
+ return value if isinstance(value, str) else ""
+
+
+def _parse_payload(body: bytes) -> tuple[_HookUser, _HookEmailData] | None:
+ try:
+ payload = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ user, email_data, request_metadata = payload.get("user"), payload.get("email_data"), payload.get("metadata")
+ if not isinstance(user, dict) or not isinstance(email_data, dict) or not isinstance(request_metadata, dict):
+ return None
+ metadata = user.get("user_metadata")
+ hook_user = _HookUser(
+ id=_str(user, "id"),
+ email=_str(user, "email"),
+ new_email=_str(user, "new_email"),
+ user_metadata=metadata if isinstance(metadata, dict) else {},
+ )
+ hook_email_data = _HookEmailData(
+ request_id=_str(request_metadata, "uuid"),
+ email_action_type=_str(email_data, "email_action_type"),
+ token=_str(email_data, "token"),
+ token_hash=_str(email_data, "token_hash"),
+ token_new=_str(email_data, "token_new"),
+ token_hash_new=_str(email_data, "token_hash_new"),
+ redirect_to=_str(email_data, "redirect_to"),
+ old_email=_str(email_data, "old_email"),
+ )
+ # A phone-only user adding an email address has no current address yet, only the new one.
+ has_recipient = bool(hook_user.email or hook_user.new_email)
+ if not hook_email_data.request_id or not hook_user.id or not has_recipient or not hook_email_data.email_action_type:
+ return None
+ return hook_user, hook_email_data
+
+
+def _sends(user: _HookUser, data: _HookEmailData) -> list[_Send]:
+ if data.email_action_type == SupabaseEmailActionType.EMAIL_CHANGED_NOTIFICATION:
+ # The alert has to reach the address that was replaced, in case the change was not the owner's.
+ return [_Send(to=data.old_email or user.email, token=data.token, token_hash=data.token_hash)]
+ if data.email_action_type != SupabaseEmailActionType.EMAIL_CHANGE:
+ return [_Send(to=user.email or user.new_email, token=data.token, token_hash=data.token_hash)]
+ if data.token_hash_new and not user.email:
+ # Only the new address exists, so it gets its own pair: `token_new` with the plain hash.
+ return [_Send(to=user.new_email, token=data.token_new, token_hash=data.token_hash)]
+ if data.token_hash_new:
+ # Secure email change sends one email to each address. Supabase keeps the old field names, so the
+ # current address gets the `_new` hash and the new address gets the plain one.
+ return [
+ _Send(to=user.email, token=data.token, token_hash=data.token_hash_new),
+ _Send(to=user.new_email or user.email, token=data.token_new, token_hash=data.token_hash),
+ ]
+ return [
+ _Send(
+ to=user.new_email or user.email,
+ token=data.token or data.token_new,
+ token_hash=data.token_hash or data.token_hash_new,
+ )
+ ]
+
+
+def _confirmation_url(supabase_url: str, data: _HookEmailData, token_hash: str) -> str:
+ # Reauthentication has no verify link. The user types the code instead.
+ if not token_hash or data.email_action_type == SupabaseEmailActionType.REAUTHENTICATION:
+ return ""
+ query = urlencode({"token": token_hash, "type": data.email_action_type, "redirect_to": data.redirect_to})
+ return f"{supabase_url}/auth/v1/verify?{query}"
+
+
+def _message_data(config: SupabaseAuthEmailConfig, user: _HookUser, data: _HookEmailData, send: _Send) -> dict:
+ return {
+ "email_action_type": data.email_action_type,
+ "confirmation_url": _confirmation_url(config.supabase_url, data, send.token_hash),
+ "token": send.token,
+ "token_hash": send.token_hash,
+ "redirect_to": data.redirect_to,
+ "email": user.email,
+ "new_email": user.new_email,
+ "user_metadata": user.user_metadata,
+ }
+
+
+def _verified(config: SupabaseAuthEmailConfig, body: bytes, headers: Mapping[str, str]) -> bool:
+ signing_key = _signing_key(config.hook_secret or "")
+ if signing_key is None:
+ return False
+ scheme = standard_webhooks_scheme(lambda: signing_key, tolerance_seconds=SIGNATURE_TOLERANCE_SECONDS)
+ return scheme.verify(body=body, headers=headers).outcome == VerificationOutcome.VERIFIED
+
+
+def handle_send_email_hook(team: Team, body: bytes, headers: Mapping[str, str]) -> SupabaseHookResult:
+ deadline = time.monotonic() + SEND_BUDGET_SECONDS
+ config = _config(team.id)
+ if config is None or not config.hook_secret or not _verified(config, body, headers):
+ return SupabaseHookResult(status=401, message="The hook signature doesn't match. Check the hook secret.")
+
+ parsed = _parse_payload(body)
+ if parsed is None:
+ return SupabaseHookResult(status=400, message="The hook payload isn't a Send Email Hook payload.")
+ user, data = parsed
+
+ action = data.email_action_type
+ result = partial(SupabaseHookResult, email_action_type=action)
+ # Confirmation links point at the project's verify endpoint, so without the URL every link would be broken.
+ if not config.supabase_url:
+ return result(status=400, message=SEND_FAILED_MESSAGE, error_code="project_url_missing")
+ template_id = config.templates.get(action)
+ if template_id is None:
+ # A missing notification only loses a heads-up, so it must not fail the user's request. A missing auth
+ # email would leave the user without their link or code, so Supabase has to show the failure.
+ if action.endswith("_notification"):
+ return result(status=200, skipped=True)
+ return result(status=400, message=f"No PostHog template is set for the {action} email.")
+ # The template can change after it was mapped. A send through one that is no longer sensitive would store
+ # sign-in codes and reset links.
+ if UUID(template_id) not in _sendable_template_ids(team.id, {UUID(template_id)}):
+ logger.warning("supabase_auth_email_template_not_sendable", team_id=team.id, email_action_type=action)
+ return result(status=400, message=SEND_FAILED_MESSAGE, error_code="template_not_sendable")
+
+ sends = _sends(user, data)
+ for index, send in enumerate(sends):
+ remaining = deadline - time.monotonic()
+ if remaining < MIN_SEND_SECONDS:
+ return result(status=503, message=SEND_FAILED_MESSAGE, error_code="deadline_exceeded", sent_count=index)
+ try:
+ send_transactional_email(
+ team,
+ UUID(template_id),
+ to=send.to,
+ distinct_id=user.id,
+ message_data=_message_data(config, user, data, send),
+ # A retry of the same request never sends an email twice, even when only one of two sends failed.
+ idempotency_key=f"supabase-{data.request_id}-{index}"[:255],
+ timeout=remaining,
+ )
+ # Supabase shows `message` to the person signing in, so it never carries the setup advice the errors hold.
+ except (QuotaLimited, IdempotencyKeyInFlight) as e:
+ return result(status=429, message=SEND_FAILED_MESSAGE, error_code=e.code, sent_count=index)
+ except TransactionalEmailError as e:
+ logger.warning("supabase_auth_email_rejected", team_id=team.id, error_code=e.code)
+ return result(status=400, message=SEND_FAILED_MESSAGE, error_code=e.code, sent_count=index)
+ except ObjectDoesNotExist:
+ # The mapped template was deleted after it was mapped.
+ logger.warning("supabase_auth_email_template_missing", team_id=team.id, email_action_type=action)
+ return result(status=400, message=SEND_FAILED_MESSAGE, error_code="template_missing", sent_count=index)
+ except DeliveryUnavailable:
+ return result(status=503, message=SEND_FAILED_MESSAGE, error_code="delivery_unavailable", sent_count=index)
+ return result(status=200, sent_count=len(sends))
diff --git a/products/messaging/backend/services/transactional_email.py b/products/messaging/backend/services/transactional_email.py
index e899d1abdde2..938afdfa4c8d 100644
--- a/products/messaging/backend/services/transactional_email.py
+++ b/products/messaging/backend/services/transactional_email.py
@@ -304,6 +304,7 @@ def send_transactional_email(
distinct_id: str | None,
message_data: dict[str, Any],
idempotency_key: str | None = None,
+ timeout: float = 10,
) -> QueuedEmail:
if idempotency_key is not None and not IDEMPOTENCY_KEY_PATTERN.fullmatch(idempotency_key):
raise InvalidIdempotencyKey(
@@ -324,7 +325,7 @@ def send_transactional_email(
# The CDP service holds the key, because only it knows whether the email was queued.
payload["idempotency_key"] = idempotency_key
try:
- response = run_transactional_workflow(team.id, str(hog_flow_id), payload)
+ response = run_transactional_workflow(team.id, str(hog_flow_id), payload, timeout=timeout)
except Exception as e:
logger.exception("transactional_email_queue_failed", team_id=team.id, template_id=str(template_id))
raise DeliveryUnavailable() from e
diff --git a/products/messaging/backend/tests/api/test_supabase_auth_emails.py b/products/messaging/backend/tests/api/test_supabase_auth_emails.py
new file mode 100644
index 000000000000..0b2b30809366
--- /dev/null
+++ b/products/messaging/backend/tests/api/test_supabase_auth_emails.py
@@ -0,0 +1,383 @@
+import hmac
+import json
+import time
+import base64
+import hashlib
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.messaging.backend.models import MessageTemplate, SupabaseAuthEmailConfig
+from products.messaging.backend.services.design_validation import validate_design
+from products.messaging.backend.services.supabase_auth_emails import SEND_BUDGET_SECONDS
+from products.messaging.backend.services.transactional_email import make_transactional
+from products.workflows.backend.facade.api import set_default_email_sender_if_unset
+
+SIGNING_KEY = b"k" * 32
+HOOK_SECRET = "v1,whsec_" + base64.b64encode(SIGNING_KEY).decode()
+
+
+def _signed_headers(
+ body: bytes, *, webhook_id: str = "msg_1", key: bytes = SIGNING_KEY, signing_keys: list[bytes] | None = None
+) -> dict[str, str]:
+ timestamp = str(int(time.time()))
+ signed = f"{webhook_id}.{timestamp}.".encode() + body
+ signatures = [
+ "v1," + base64.b64encode(hmac.new(k, signed, hashlib.sha256).digest()).decode() for k in (signing_keys or [key])
+ ]
+ return {
+ "webhook-id": webhook_id,
+ "webhook-timestamp": timestamp,
+ # Supabase joins the signatures with ", ".
+ "webhook-signature": ", ".join(signatures),
+ }
+
+
+REQUEST_ID = "5f0e7a52-0000-4000-8000-000000000002"
+
+
+def _payload(action: str, user_email: str = "[email protected]", **email_data: str) -> dict[str, Any]:
+ return {
+ "metadata": {"uuid": REQUEST_ID, "name": "send-email"},
+ "user": {
+ "id": "8d0c0b6e-0000-4000-8000-000000000001",
+ "email": user_email,
+ "new_email": "[email protected]",
+ "user_metadata": {"first_name": "Jane"},
+ },
+ "email_data": {
+ "email_action_type": action,
+ "token": "123456",
+ "token_hash": "hash-plain",
+ "token_new": "",
+ "token_hash_new": "",
+ "redirect_to": "https://app.example.com/welcome?from=email",
+ **email_data,
+ },
+ }
+
+
+@patch("posthoganalytics.capture")
+@patch("posthoganalytics.feature_enabled", return_value=True)
+@patch("posthog.plugins.plugin_server_api.internal_requests.post")
+class TestSupabaseAuthEmails(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sender = Integration.objects.create(
+ team=self.team, kind="email", integration_id="[email protected]", config={"verified": True}
+ )
+ set_default_email_sender_if_unset(self.team.id, sender.id)
+ self.template = self._template("Supabase sign up")
+ make_transactional(self.team.id, self.template.id, user_id=self.user.id, from_integration_id=None)
+ self.config = SupabaseAuthEmailConfig.objects.for_team(self.team.id).create(
+ team=self.team,
+ supabase_url="https://abcdefgh.supabase.co",
+ hook_secret=HOOK_SECRET,
+ templates={
+ "signup": str(self.template.id),
+ "email_change": str(self.template.id),
+ "reauthentication": str(self.template.id),
+ "email_changed_notification": str(self.template.id),
+ },
+ )
+ self.hook_url = f"/webhooks/messaging/supabase/{self.team.id}/send-email"
+ self.settings_url = f"/api/projects/{self.team.id}/messaging_supabase_auth_emails/settings/"
+ self.starter_url = f"/api/projects/{self.team.id}/messaging_supabase_auth_emails/starter_templates/"
+
+ def _template(self, name: str, *, sensitive: bool = True) -> MessageTemplate:
+ return MessageTemplate.objects.create(
+ team=self.team,
+ name=name,
+ content={"email": {"subject": "Confirm", "html": "<a href='{{ variables.confirmation_url }}'>Go</a>"}},
+ type="email",
+ sensitive=sensitive,
+ )
+
+ def _post_hook(
+ self,
+ payload: dict[str, Any],
+ *,
+ key: bytes = SIGNING_KEY,
+ webhook_id: str = "msg_1",
+ signing_keys: list[bytes] | None = None,
+ ):
+ body = json.dumps(payload).encode()
+ self.client.logout()
+ return self.client.post(
+ self.hook_url,
+ data=body,
+ content_type="application/json",
+ headers=_signed_headers(body, key=key, webhook_id=webhook_id, signing_keys=signing_keys),
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "signup",
+ _payload("signup"),
+ [("[email protected]", "123456", "hash-plain")],
+ ),
+ (
+ # Secure email change: Supabase swaps the hashes, so the current address gets the `_new` one.
+ "secure_email_change",
+ _payload("email_change", token_new="654321", token_hash_new="hash-new"),
+ [("[email protected]", "123456", "hash-new"), ("[email protected]", "654321", "hash-plain")],
+ ),
+ (
+ "email_change",
+ _payload("email_change"),
+ [("[email protected]", "123456", "hash-plain")],
+ ),
+ # Reauthentication has no verify link, only the code.
+ ("reauthentication", _payload("reauthentication"), [("[email protected]", "123456", "hash-plain")]),
+ # An unmapped notification is skipped rather than failing the user's request.
+ ("unmapped_notification", _payload("password_changed_notification"), []),
+ # The alert goes to the replaced address, so the owner hears about a takeover.
+ (
+ "email_changed_notification",
+ _payload("email_changed_notification", user_email="[email protected]", old_email="[email protected]"),
+ [("[email protected]", "123456", "hash-plain")],
+ ),
+ # A phone-only user adding an email has no current address.
+ (
+ "phone_only_email_change",
+ _payload("email_change", user_email=""),
+ [("[email protected]", "123456", "hash-plain")],
+ ),
+ ]
+ )
+ def test_sends_each_auth_email_through_its_template(self, mock_post, _flag, capture, _name, payload, expected):
+ mock_post.return_value = MagicMock(status_code=202, json=lambda: {"invocation_id": "invocation-1"})
+
+ response = self._post_hook(payload)
+ # Supabase retries with a new webhook id, so the sends must still share their idempotency keys.
+ retry = self._post_hook(payload, webhook_id="msg_2")
+
+ assert response.status_code == retry.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {}
+ calls = [call.kwargs["json"] for call in mock_post.call_args_list]
+ sent, resent = calls[: len(expected)], calls[len(expected) :]
+ assert [(s["to"], s["variables"]["token"], s["variables"]["token_hash"]) for s in sent] == expected
+ assert [s["idempotency_key"] for s in resent] == [s["idempotency_key"] for s in sent]
+ # Supabase drops the hook after 5 seconds, so no send may wait longer than the shared budget.
+ assert all(call.kwargs["timeout"] <= SEND_BUDGET_SECONDS for call in mock_post.call_args_list)
+ action = payload["email_data"]["email_action_type"]
+ for index, (send, (_to, _token, token_hash)) in enumerate(zip(sent, expected)):
+ assert send["distinct_id"] == "8d0c0b6e-0000-4000-8000-000000000001"
+ assert send["idempotency_key"] == f"supabase-{REQUEST_ID}-{index}"
+ assert send["variables"]["confirmation_url"] == (
+ ""
+ if action == "reauthentication"
+ else f"https://abcdefgh.supabase.co/auth/v1/verify?token={token_hash}&type={action}"
+ "&redirect_to=https%3A%2F%2Fapp.example.com%2Fwelcome%3Ffrom%3Demail"
+ )
+ assert send["variables"]["user_metadata"] == {"first_name": "Jane"}
+ # Only failures are tracked, so the event volume doesn't grow with the customer's traffic.
+ assert not any(c.kwargs.get("event") == "supabase auth email hook" for c in capture.call_args_list)
+
+ @parameterized.expand(
+ [
+ ("wrong_secret", "signup", {"key": b"x" * 32}, {}, None, 401, "other"),
+ ("no_template_for_the_email", "signup", {}, {"templates": {}}, None, 400, "signup"),
+ ("no_project_url", "signup", {}, {"supabase_url": ""}, None, 400, "signup"),
+ # The payload names the email type, so an unknown one is reported as "other".
+ ("unknown_email_type", "made_up_type", {}, {}, None, 400, "other"),
+ ("over_quota", "signup", {}, {}, 429, 429, "signup"),
+ ("pipeline_down", "signup", {}, {}, 500, 503, "signup"),
+ ]
+ )
+ def test_answers_an_error_supabase_can_show_the_user(
+ self,
+ mock_post,
+ _flag,
+ capture,
+ _name,
+ action,
+ sign_with,
+ config_changes,
+ cdp_status,
+ expected_code,
+ reported_action,
+ ):
+ for field, value in config_changes.items():
+ setattr(self.config, field, value)
+ self.config.save()
+ if cdp_status:
+ mock_post.return_value = MagicMock(
+ status_code=cdp_status, json=lambda: {"error": "quota_limited"} if cdp_status == 429 else {}
+ )
+
+ response = self._post_hook(_payload(action), **sign_with)
+
+ # Supabase only passes our message on when it comes with a 200. An unverified request still gets a 401.
+ assert response.status_code == (401 if expected_code == 401 else 200)
+ assert response.json()["error"]["http_code"] == expected_code
+ assert response.json()["error"]["message"]
+ assert mock_post.called == bool(cdp_status)
+ hook_events = [
+ c.kwargs["properties"]
+ for c in capture.call_args_list
+ if c.kwargs.get("event") == "supabase auth email hook"
+ ]
+ # An unverified request could come from anyone, so it records no usage for the team.
+ assert [(e["status"], e["email_action_type"]) for e in hook_events] == (
+ [] if expected_code == 401 else [(expected_code, reported_action)]
+ )
+
+ def test_settings_keep_the_secret_write_only_and_take_only_transactional_templates(
+ self, _mock_post, _flag, _capture
+ ):
+ response = self.client.patch(
+ self.settings_url, {"supabase_url": "https://abcdefgh.supabase.co/"}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["supabase_url"] == "https://abcdefgh.supabase.co"
+ assert response.json()["has_hook_secret"] is True
+ assert "hook_secret" not in response.json()
+ assert "email" not in {t["value"] for t in response.json()["email_types"]}
+ assert response.json()["hook_url"].endswith(self.hook_url)
+
+ not_transactional = self._template("Newsletter")
+ not_sensitive = self._template("Plain reset", sensitive=False)
+ make_transactional(self.team.id, not_sensitive.id, user_id=self.user.id, from_integration_id=None)
+ for template in (not_transactional, not_sensitive):
+ response = self.client.patch(
+ self.settings_url, {"templates": {"recovery": str(template.id)}}, format="json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "templates"
+
+ response = self.client.patch(self.settings_url, {"hook_secret": "whsec_short"}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "hook_secret"
+
+ def test_starter_templates_cover_the_core_auth_emails_once(self, _mock_post, _flag, _capture):
+ response = self.client.post(self.starter_url)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ templates = response.json()["templates"]
+ assert set(templates) == {
+ "signup",
+ "invite",
+ "magiclink",
+ "recovery",
+ "email_change",
+ "reauthentication",
+ "email_changed_notification",
+ }
+ # Mapped types keep their template.
+ assert templates["signup"] == str(self.template.id)
+ created = MessageTemplate.objects.filter(team=self.team, name__startswith="Supabase: ")
+ assert created.count() == 3
+ assert all(t.sensitive and t.transactional_hog_flow_id for t in created)
+ for template in created:
+ design = template.content["email"]["design"]
+ assert validate_design(design) == []
+ # Native blocks, so each part opens on its own in the editor rather than as one raw HTML block.
+ block_types = [c["type"] for c in design["body"]["rows"][0]["columns"][0]["contents"]]
+ assert "html" not in block_types and "heading" in block_types
+
+ again = self.client.post(self.starter_url)
+ assert again.json()["templates"] == templates
+
+ def test_mapping_a_template_needs_editor_access_to_its_workflow(self, _mock_post, _flag, _capture):
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ # Admins bypass object-level access, so the check needs a plain member.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ restricted = self._template("Supabase invite")
+ # The creator of a workflow keeps access to it, so another user creates this one.
+ make_transactional(self.team.id, restricted.id, user_id=None, from_integration_id=None)
+ restricted.refresh_from_db()
+ AccessControl.objects.create(
+ team=self.team,
+ resource="hog_flow",
+ resource_id=str(restricted.transactional_hog_flow_id),
+ access_level="none",
+ )
+ mapped = {**self.config.templates, "invite": str(restricted.id)}
+
+ denied_mapping = self.client.patch(self.settings_url, {"templates": mapped}, format="json")
+ self.config.templates = mapped
+ self.config.save()
+ # Once an admin maps it, a new secret would let the member sign hook calls that send it.
+ denied_secret = self.client.patch(self.settings_url, {"hook_secret": HOOK_SECRET}, format="json")
+
+ assert denied_mapping.status_code == status.HTTP_403_FORBIDDEN, denied_mapping.json()
+ assert denied_secret.status_code == status.HTTP_403_FORBIDDEN, denied_secret.json()
+
+ def test_hides_the_settings_but_keeps_sending_while_the_flag_is_off(self, mock_post, flag, _capture):
+ flag.return_value = False
+ mock_post.return_value = MagicMock(status_code=202, json=lambda: {"invocation_id": "invocation-1"})
+
+ assert self.client.get(self.settings_url).status_code == status.HTTP_404_NOT_FOUND
+ # A connected project's sign-ups must not break when the flag rolls back.
+ assert self._post_hook(_payload("signup")).json() == {}
+ assert mock_post.called
+
+ def test_disconnect_clears_the_settings_so_the_hook_refuses_calls(self, mock_post, _flag, _capture):
+ response = self.client.delete(self.settings_url)
+ hook = self._post_hook(_payload("signup"))
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert (response.json()["supabase_url"], response.json()["has_hook_secret"], response.json()["templates"]) == (
+ "",
+ False,
+ {},
+ )
+ assert hook.status_code == status.HTTP_401_UNAUTHORIZED
+ assert not mock_post.called
+
+ def test_first_save_works_before_a_secret_is_stored(self, _mock_post, _flag, _capture):
+ self.config.delete()
+
+ starter = self.client.post(self.starter_url)
+ saved = self.client.patch(self.settings_url, {"supabase_url": "https://abcdefgh.supabase.co"}, format="json")
+
+ assert starter.status_code == status.HTTP_200_OK, starter.json()
+ assert saved.status_code == status.HTTP_200_OK, saved.json()
+ assert saved.json()["has_hook_secret"] is False
+
+ @parameterized.expand([("deleted", {"deleted": True}), ("no_longer_sensitive", {"sensitive": False})])
+ def test_a_mapped_template_that_cannot_send_fails_cleanly_and_gets_a_starter_replacement(
+ self, mock_post, _flag, _capture, _name, change
+ ):
+ MessageTemplate.objects.filter(id=self.template.id).update(**change)
+
+ response = self._post_hook(_payload("signup"))
+ self.client.force_login(self.user)
+ starter = self.client.post(self.starter_url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["error"]["http_code"] == 400
+ assert "template" not in response.json()["error"]["message"].lower()
+ assert not mock_post.called
+ assert starter.status_code == status.HTTP_200_OK, starter.json()
+ assert starter.json()["templates"]["signup"] != str(self.template.id)
+
+ # While a secret rotates, Supabase signs with each one, so the stored secret can sign either position.
+ @parameterized.expand([("stored_secret_last", True), ("stored_secret_first", False)])
+ def test_accepts_a_header_signed_with_an_old_and_a_new_secret(self, mock_post, _flag, _capture, _name, other_first):
+ mock_post.return_value = MagicMock(status_code=202, json=lambda: {"invocation_id": "invocation-1"})
+ other = b"o" * 32
+
+ response = self._post_hook(
+ _payload("signup"), signing_keys=[other, SIGNING_KEY] if other_first else [SIGNING_KEY, other]
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {}
+ assert mock_post.called
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index c2f9677bb93f..2aa414b86e9b 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -365,6 +365,104 @@ export interface ImportProviderOptionApi {
steps: ImportStepOptionApi[]
}
+/**
+ * Supabase email action type (such as `signup` or `recovery`) to the transactional message template that sends it. An auth email with no template fails in Supabase.
+ */
+export type SupabaseAuthEmailSettingsApiTemplates = { [key: string]: string }
+
+/**
+ * * `signup` - Confirm sign up
+ * * `invite` - Invite user
+ * * `magiclink` - Magic link
+ * * `email` - Email sign-in code
+ * * `recovery` - Reset password
+ * * `email_change` - Change email address
+ * * `reauthentication` - Reauthentication
+ * * `password_changed_notification` - Password changed
+ * * `email_changed_notification` - Email address changed
+ * * `phone_changed_notification` - Phone number changed
+ * * `identity_linked_notification` - Sign-in method linked
+ * * `identity_unlinked_notification` - Sign-in method removed
+ * * `mfa_factor_enrolled_notification` - MFA method added
+ * * `mfa_factor_unenrolled_notification` - MFA method removed
+ */
+export type SupabaseEmailActionTypeEnumApi =
+ (typeof SupabaseEmailActionTypeEnumApi)[keyof typeof SupabaseEmailActionTypeEnumApi]
+
+export const SupabaseEmailActionTypeEnumApi = {
+ Signup: 'signup',
+ Invite: 'invite',
+ Magiclink: 'magiclink',
+ Email: 'email',
+ Recovery: 'recovery',
+ EmailChange: 'email_change',
+ Reauthentication: 'reauthentication',
+ PasswordChangedNotification: 'password_changed_notification',
+ EmailChangedNotification: 'email_changed_notification',
+ PhoneChangedNotification: 'phone_changed_notification',
+ IdentityLinkedNotification: 'identity_linked_notification',
+ IdentityUnlinkedNotification: 'identity_unlinked_notification',
+ MfaFactorEnrolledNotification: 'mfa_factor_enrolled_notification',
+ MfaFactorUnenrolledNotification: 'mfa_factor_unenrolled_notification',
+} as const
+
+export interface SupabaseEmailTypeApi {
+ /** The `email_action_type` Supabase sends for this email.
+ *
+ * * `signup` - Confirm sign up
+ * * `invite` - Invite user
+ * * `magiclink` - Magic link
+ * * `email` - Email sign-in code
+ * * `recovery` - Reset password
+ * * `email_change` - Change email address
+ * * `reauthentication` - Reauthentication
+ * * `password_changed_notification` - Password changed
+ * * `email_changed_notification` - Email address changed
+ * * `phone_changed_notification` - Phone number changed
+ * * `identity_linked_notification` - Sign-in method linked
+ * * `identity_unlinked_notification` - Sign-in method removed
+ * * `mfa_factor_enrolled_notification` - MFA method added
+ * * `mfa_factor_unenrolled_notification` - MFA method removed */
+ value: SupabaseEmailActionTypeEnumApi
+ /** What the email is for, in words a person reads. */
+ label: string
+ /** Whether creating starter templates makes a template for this email. */
+ has_starter_template: boolean
+}
+
+export interface SupabaseAuthEmailSettingsApi {
+ /** The Supabase project URL, such as https://abcdefgh.supabase.co. Confirmation links point at its /auth/v1/verify endpoint. */
+ supabase_url: string
+ /** Whether a Send Email Hook secret is stored. The secret itself is never returned. */
+ has_hook_secret: boolean
+ /** Supabase email action type (such as `signup` or `recovery`) to the transactional message template that sends it. An auth email with no template fails in Supabase. */
+ templates: SupabaseAuthEmailSettingsApiTemplates
+ /** The URL to paste into Supabase as the HTTPS endpoint of the Send Email Hook. */
+ hook_url: string
+ /** Every email Supabase can send through the hook, core auth emails first. */
+ email_types: SupabaseEmailTypeApi[]
+}
+
+/**
+ * Supabase email action type to transactional message template id. Replaces the whole mapping. Valid action types: signup, invite, magiclink, email, recovery, email_change, reauthentication, password_changed_notification, email_changed_notification, phone_changed_notification, identity_linked_notification, identity_unlinked_notification, mfa_factor_enrolled_notification, mfa_factor_unenrolled_notification.
+ */
+export type PatchedSupabaseAuthEmailSettingsUpdateApiTemplates = { [key: string]: string }
+
+export interface PatchedSupabaseAuthEmailSettingsUpdateApi {
+ /**
+ * The Supabase project URL, such as https://abcdefgh.supabase.co.
+ * @maxLength 200
+ */
+ supabase_url?: string
+ /**
+ * The Send Email Hook secret from Supabase, starting with v1,whsec_. Leave it out to keep the stored secret.
+ * @maxLength 500
+ */
+ hook_secret?: string
+ /** Supabase email action type to transactional message template id. Replaces the whole mapping. Valid action types: signup, invite, magiclink, email, recovery, email_change, reauthentication, password_changed_notification, email_changed_notification, phone_changed_notification, identity_linked_notification, identity_unlinked_notification, mfa_factor_enrolled_notification, mfa_factor_unenrolled_notification. */
+ templates?: PatchedSupabaseAuthEmailSettingsUpdateApiTemplates
+}
+
export interface AddSuppressionRequestApi {
/**
* The email address to suppress. Will not receive any messages until removed.
diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.ts
index b8c0fd15c926..524043639bae 100644
--- a/products/messaging/frontend/generated/api.ts
+++ b/products/messaging/frontend/generated/api.ts
@@ -32,6 +32,7 @@ import type {
PatchedDesignPatchApi,
PatchedMessageCategoryApi,
PatchedMessageTemplateApi,
+ PatchedSupabaseAuthEmailSettingsUpdateApi,
PreferencesLinkApi,
ProviderImportRunApi,
RemoveOptOutRequestApi,
@@ -39,6 +40,7 @@ import type {
SendTransactionalEmailApi,
SendTransactionalEmailResponseApi,
StartProviderImportApi,
+ SupabaseAuthEmailSettingsApi,
WebhookUrlApi,
} from './api.schemas'
@@ -624,6 +626,84 @@ export const messagingProviderImportsProvidersList = async (
})
}
+export const getMessagingSupabaseAuthEmailsSettingsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/messaging_supabase_auth_emails/settings/`
+}
+
+/**
+ * Send a Supabase project's auth emails through transactional email templates.
+ * @summary Get the Supabase auth email settings
+ */
+export const messagingSupabaseAuthEmailsSettingsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SupabaseAuthEmailSettingsApi> => {
+ return apiMutator<SupabaseAuthEmailSettingsApi>(getMessagingSupabaseAuthEmailsSettingsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMessagingSupabaseAuthEmailsSettingsPartialUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/messaging_supabase_auth_emails/settings/`
+}
+
+/**
+ * Send a Supabase project's auth emails through transactional email templates.
+ * @summary Update the Supabase auth email settings
+ */
+export const messagingSupabaseAuthEmailsSettingsPartialUpdate = async (
+ projectId: string,
+ patchedSupabaseAuthEmailSettingsUpdateApi?: PatchedSupabaseAuthEmailSettingsUpdateApi,
+ options?: RequestInit
+): Promise<SupabaseAuthEmailSettingsApi> => {
+ return apiMutator<SupabaseAuthEmailSettingsApi>(getMessagingSupabaseAuthEmailsSettingsPartialUpdateUrl(projectId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedSupabaseAuthEmailSettingsUpdateApi),
+ })
+}
+
+export const getMessagingSupabaseAuthEmailsSettingsDestroyUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/messaging_supabase_auth_emails/settings/`
+}
+
+/**
+ * Remove the project URL, hook secret and template mappings. The hook then refuses every call, so turn off the Send Email hook in Supabase first. The templates themselves stay.
+ * @summary Disconnect the Supabase project
+ */
+export const messagingSupabaseAuthEmailsSettingsDestroy = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SupabaseAuthEmailSettingsApi> => {
+ return apiMutator<SupabaseAuthEmailSettingsApi>(getMessagingSupabaseAuthEmailsSettingsDestroyUrl(projectId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getMessagingSupabaseAuthEmailsStarterTemplatesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/messaging_supabase_auth_emails/starter_templates/`
+}
+
+/**
+ * Create a transactional template for each core Supabase auth email that has no template yet, and map it. Needs a verified email sender.
+ * @summary Create starter templates for the Supabase auth emails
+ */
+export const messagingSupabaseAuthEmailsStarterTemplatesCreate = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SupabaseAuthEmailSettingsApi> => {
+ return apiMutator<SupabaseAuthEmailSettingsApi>(
+ getMessagingSupabaseAuthEmailsStarterTemplatesCreateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
export const getMessagingSuppressionsAddSuppressionCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/messaging_suppressions/add_suppression/`
}
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index b9c5ae980c9e..79bd590cd7fc 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -425,6 +425,35 @@ export const MessagingProviderImportsCreateBody = /* @__PURE__ */ zod.object({
.describe("The provider's API key. For Customer.io, an App API key. Leave it out to reuse the stored key."),
})
+/**
+ * Send a Supabase project's auth emails through transactional email templates.
+ * @summary Update the Supabase auth email settings
+ */
+export const messagingSupabaseAuthEmailsSettingsPartialUpdateBodySupabaseUrlMax = 200
+
+export const messagingSupabaseAuthEmailsSettingsPartialUpdateBodyHookSecretMax = 500
+
+export const MessagingSupabaseAuthEmailsSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ supabase_url: zod
+ .string()
+ .max(messagingSupabaseAuthEmailsSettingsPartialUpdateBodySupabaseUrlMax)
+ .optional()
+ .describe('The Supabase project URL, such as https:\/\/abcdefgh.supabase.co.'),
+ hook_secret: zod
+ .string()
+ .max(messagingSupabaseAuthEmailsSettingsPartialUpdateBodyHookSecretMax)
+ .optional()
+ .describe(
+ 'The Send Email Hook secret from Supabase, starting with v1,whsec_. Leave it out to keep the stored secret.'
+ ),
+ templates: zod
+ .record(zod.string(), zod.uuid())
+ .optional()
+ .describe(
+ 'Supabase email action type to transactional message template id. Replaces the whole mapping. Valid action types: signup, invite, magiclink, email, recovery, email_change, reauthentication, password_changed_notification, email_changed_notification, phone_changed_notification, identity_linked_notification, identity_unlinked_notification, mfa_factor_enrolled_notification, mfa_factor_unenrolled_notification.'
+ ),
+})
+
/**
* Manually suppress an email address so no workflow sends to it.
* @summary Manually add an email address to the suppression list
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 07b315746920..949ca3182b81 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -92256,6 +92256,26 @@ export namespace Schemas {
delivery_config?: DeliveryConfig;
}
+ /**
+ * Supabase email action type to transactional message template id. Replaces the whole mapping. Valid action types: signup, invite, magiclink, email, recovery, email_change, reauthentication, password_changed_notification, email_changed_notification, phone_changed_notification, identity_linked_notification, identity_unlinked_notification, mfa_factor_enrolled_notification, mfa_factor_unenrolled_notification.
+ */
+ export type PatchedSupabaseAuthEmailSettingsUpdateTemplates = {[key: string]: string};
+
+ export interface PatchedSupabaseAuthEmailSettingsUpdate {
+ /**
+ * The Supabase project URL, such as https://abcdefgh.supabase.co.
+ * @maxLength 200
+ */
+ supabase_url?: string;
+ /**
+ * The Send Email Hook secret from Supabase, starting with v1,whsec_. Leave it out to keep the stored secret.
+ * @maxLength 500
+ */
+ hook_secret?: string;
+ /** Supabase email action type to transactional message template id. Replaces the whole mapping. Valid action types: signup, invite, magiclink, email, recovery, email_change, reauthentication, password_changed_notification, email_changed_notification, phone_changed_notification, identity_linked_notification, identity_unlinked_notification, mfa_factor_enrolled_notification, mfa_factor_unenrolled_notification. */
+ templates?: PatchedSupabaseAuthEmailSettingsUpdateTemplates;
+ }
+
/**
* * `once` - once
* * `recurring` - recurring
@@ -116933,6 +116953,84 @@ export namespace Schemas {
metadata?: unknown;
}
+ /**
+ * Supabase email action type (such as `signup` or `recovery`) to the transactional message template that sends it. An auth email with no template fails in Supabase.
+ */
+ export type SupabaseAuthEmailSettingsTemplates = {[key: string]: string};
+
+ /**
+ * * `signup` - Confirm sign up
+ * * `invite` - Invite user
+ * * `magiclink` - Magic link
+ * * `email` - Email sign-in code
+ * * `recovery` - Reset password
+ * * `email_change` - Change email address
+ * * `reauthentication` - Reauthentication
+ * * `password_changed_notification` - Password changed
+ * * `email_changed_notification` - Email address changed
+ * * `phone_changed_notification` - Phone number changed
+ * * `identity_linked_notification` - Sign-in method linked
+ * * `identity_unlinked_notification` - Sign-in method removed
+ * * `mfa_factor_enrolled_notification` - MFA method added
+ * * `mfa_factor_unenrolled_notification` - MFA method removed
+ */
+ export type SupabaseEmailActionTypeEnum = typeof SupabaseEmailActionTypeEnum[keyof typeof SupabaseEmailActionTypeEnum];
+
+
+ export const SupabaseEmailActionTypeEnum = {
+ Signup: 'signup',
+ Invite: 'invite',
+ Magiclink: 'magiclink',
+ Email: 'email',
+ Recovery: 'recovery',
+ EmailChange: 'email_change',
+ Reauthentication: 'reauthentication',
+ PasswordChangedNotification: 'password_changed_notification',
+ EmailChangedNotification: 'email_changed_notification',
+ PhoneChangedNotification: 'phone_changed_notification',
+ IdentityLinkedNotification: 'identity_linked_notification',
+ IdentityUnlinkedNotification: 'identity_unlinked_notification',
+ MfaFactorEnrolledNotification: 'mfa_factor_enrolled_notification',
+ MfaFactorUnenrolledNotification: 'mfa_factor_unenrolled_notification',
+ } as const;
+
+ export interface SupabaseEmailType {
+ /** The `email_action_type` Supabase sends for this email.
+ *
+ * * `signup` - Confirm sign up
+ * * `invite` - Invite user
+ * * `magiclink` - Magic link
+ * * `email` - Email sign-in code
+ * * `recovery` - Reset password
+ * * `email_change` - Change email address
+ * * `reauthentication` - Reauthentication
+ * * `password_changed_notification` - Password changed
+ * * `email_changed_notification` - Email address changed
+ * * `phone_changed_notification` - Phone number changed
+ * * `identity_linked_notification` - Sign-in method linked
+ * * `identity_unlinked_notification` - Sign-in method removed
+ * * `mfa_factor_enrolled_notification` - MFA method added
+ * * `mfa_factor_unenrolled_notification` - MFA method removed */
+ value: SupabaseEmailActionTypeEnum;
+ /** What the email is for, in words a person reads. */
+ label: string;
+ /** Whether creating starter templates makes a template for this email. */
+ has_starter_template: boolean;
+ }
+
+ export interface SupabaseAuthEmailSettings {
+ /** The Supabase project URL, such as https://abcdefgh.supabase.co. Confirmation links point at its /auth/v1/verify endpoint. */
+ supabase_url: string;
+ /** Whether a Send Email Hook secret is stored. The secret itself is never returned. */
+ has_hook_secret: boolean;
+ /** Supabase email action type (such as `signup` or `recovery`) to the transactional message template that sends it. An auth email with no template fails in Supabase. */
+ templates: SupabaseAuthEmailSettingsTemplates;
+ /** The URL to paste into Supabase as the HTTPS endpoint of the Send Email Hook. */
+ hook_url: string;
+ /** Every email Supabase can send through the hook, core auth emails first. */
+ email_types: SupabaseEmailType[];
+ }
+
/**
* A support ticket linked to an account, sourced from the conversations product (read-only).
*/