: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(messaging): add remove_opt_out and open preferences API to keys (#74632)
posthog[bot]b6f1064fe0ed
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 977b8ce64584..711af4df0191 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -252,7 +252,6 @@ import type {TaskRunCreateRequestSchemaApi,} from 'products/tasks/frontend/generated/api.schemas'import type { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'-import type { OptOutEntry } from 'products/workflows/frontend/OptOuts/types'import type { MessageTemplate } from 'products/workflows/frontend/TemplateLibrary/types'import type { HogflowTestResult } from 'products/workflows/frontend/Workflows/hogflows/steps/types'import type {@@ -1993,14 +1992,6 @@ export class ApiRequest {return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('generate_link')}- public messagingPreferencesOptOuts(): ApiRequest {- return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('opt_outs')- }-- public messagingPreferencesAddOptOut(): ApiRequest {- return this.environments().current().addPathComponent('messaging_preferences').addPathComponent('add_opt_out')- }-public messagingPreferencesExportOptOutsCsv(): ApiRequest {return this.environments().current()@@ -6692,20 +6683,6 @@ const api = {})return response.preferences_url || null},- async getMessageOptOuts(categoryKey?: string, page?: number): Promise<CountedPaginatedResponse<OptOutEntry>> {- return await new ApiRequest()- .messagingPreferencesOptOuts()- .withQueryString({- category_key: categoryKey,- page: page || 1,- })- .get()- },- async addOptOut(identifier: string, categoryKey?: string): Promise<OptOutEntry> {- return await new ApiRequest().messagingPreferencesAddOptOut().create({- data: { identifier, category_key: categoryKey },- })- },async exportOptOutsCsv(categoryKey?: string): Promise<Blob> {const response = await new ApiRequest().messagingPreferencesExportOptOutsCsv()diff --git a/products/messaging/backend/api/message_preferences.py b/products/messaging/backend/api/message_preferences.pyindex a6581b013419..f8408c8e6576 100644--- a/products/messaging/backend/api/message_preferences.py+++ b/products/messaging/backend/api/message_preferences.py@@ -1,10 +1,15 @@import re+from typing import Any, Literal++from django.db import transactionfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.pagination import PageNumberPagination+from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializer@@ -12,13 +17,14 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.streaming import streaming_responsefrom posthog.plugins import plugin_server_api-from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryTypefrom products.messaging.backend.models.message_preferences import (ALL_MESSAGE_PREFERENCE_CATEGORY_ID,MessageRecipientPreference,PreferenceStatus,)from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, OptOutService, UnknownCategoryError+from products.messaging.backend.tasks import sync_preferences_to_customerio_taskMAX_BULK_OPT_OUT_ENTRIES = 1000UNSAFE_FILENAME_CHARACTERS = re.compile(r"[^A-Za-z0-9_-]+")@@ -33,7 +39,10 @@ class OptOutsPagination(PageNumberPagination):class MessagePreferencesSerializer(serializers.ModelSerializer):identifier = serializers.CharField(help_text="The recipient identifier (e.g. email address).")updated_at = serializers.DateTimeField(help_text="When the preference was last updated.")- preferences = serializers.JSONField(help_text="Map of category ID to preference status.")+ preferences = serializers.JSONField(+ help_text="Map of category ID to preference status (`OPTED_IN`, `OPTED_OUT` or `NO_PREFERENCE`). "+ "The reserved `$all` key covers every marketing message."+ )class Meta:model = MessageRecipientPreference@@ -50,6 +59,9 @@ class MessagePreferencesSerializer(serializers.ModelSerializer):"updated_at","created_by",]+ extra_kwargs = {+ "id": {"help_text": "Server-assigned UUID for this recipient's preference record."},+ }class AddOptOutRequestSerializer(serializers.Serializer):@@ -63,6 +75,35 @@ class AddOptOutRequestSerializer(serializers.Serializer):)+class RemoveOptOutRequestSerializer(serializers.Serializer):+ identifier = serializers.CharField(+ max_length=512,+ help_text="The recipient identifier to opt back in (e.g. email address).",+ )+ category_key = serializers.CharField(+ required=False,+ help_text="Optional message category key. If omitted, the recipient is opted back in to all marketing messages.",+ )+++class GenerateLinkRequestSerializer(serializers.Serializer):+ recipient = serializers.CharField(+ required=False,+ max_length=512,+ help_text="Recipient to generate the link for. Defaults to the requesting user's own email address.",+ )+++class PreferencesLinkSerializer(serializers.Serializer):+ preferences_url = serializers.URLField(+ help_text="Token-gated URL where the recipient can manage their preferences."+ )+++class WebhookUrlSerializer(serializers.Serializer):+ url = serializers.URLField(help_text="URL to register in Customer.io so it posts subscription changes to PostHog.")++class MessagingErrorSerializer(serializers.Serializer):error = serializers.CharField(help_text="Human-readable description of what went wrong.")@@ -120,13 +161,32 @@ class BulkAddOptOutsResultSerializer(serializers.Serializer):class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """+ Per-team messaging preferences for recipients.++ Preferences are stored per message category, plus a reserved `$all` key covering every+ marketing message. A send is skipped when either the category or `$all` is opted out, so a+ two-way preference center needs both `add_opt_out` and `remove_opt_out`.+ """+scope_object = "hog_flow"- # Only the opt-out list endpoints are reachable with API keys (and therefore MCP);- # webhook_url and generate_link stay session-only by being listed in neither.+ # Every action here is a custom @action, so none of them match the default read/write action+ # names — an action listed in neither gets no scope mapping and APIScopePermission rejects+ # personal API key requests for it. Only the opt-out list endpoints are reachable with API+ # keys (and therefore MCP); webhook_url and generate_link stay session-only by being listed+ # in neither.scope_object_read_actions = ["opt_outs", "export_opt_outs_csv"]- scope_object_write_actions = ["add_opt_out", "bulk_add_opt_outs"]+ scope_object_write_actions = ["add_opt_out", "bulk_add_opt_outs", "remove_opt_out"]serializer_class = _FallbackSerializer+ def _require_resource_access(self, required_level: Literal["viewer", "editor"], message: str) -> None:+ # Resource-level check: `AccessControlPermission` only guarantees the caller has some+ # hog_flow object access. These endpoints act on team-wide data with no per-workflow+ # object, so require project-wide hog_flow access — otherwise a member granted access to+ # a single workflow could read or rewrite the whole team's opt-out list.+ if not self.user_access_control.check_access_level_for_resource("hog_flow", required_level):+ raise PermissionDenied(message)+@extend_schema(parameters=[OpenApiParameter(@@ -146,26 +206,23 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):summary="List recipients opted out of a message category",)@action(detail=False, methods=["get"])- def opt_outs(self, request, **kwargs):+ def opt_outs(self, request: Request, **kwargs: Any) -> Response:"""Get opt-outs filtered by category or overall opt-outs if no category specified"""+ self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")+category_key = request.query_params.get("category_key")+ # Find recipients who have opted out of this specific category, or use the derived $all category if no specific category is provided+ preference_key = ALL_MESSAGE_PREFERENCE_CATEGORY_IDif category_key:- # Get opt-outs for a specific category- try:- category = MessageCategory.objects.get(key=category_key, team_id=self.team_id)- except MessageCategory.DoesNotExist:+ category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()+ if category is None:return Response({"error": "Category not found"}, status=404)-- # Find recipients who have opted out of this specific category, or use the derived $all category if no specific category is provided- category_id = category.id if category_key else ALL_MESSAGE_PREFERENCE_CATEGORY_ID- query_filters = {}-- query_filters[f"preferences__{str(category_id)}"] = PreferenceStatus.OPTED_OUT.value+ preference_key = str(category.id)opt_outs = MessageRecipientPreference.objects.filter(team_id=self.team_id,- **query_filters,+ **{f"preferences__{preference_key}": PreferenceStatus.OPTED_OUT.value},).order_by("-updated_at") # Order by most recently updated first# Apply pagination@@ -185,22 +242,23 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):summary="Manually add a recipient to the opt-out list",)@action(detail=False, methods=["post"])- def add_opt_out(self, request, **kwargs):+ def add_opt_out(self, request: Request, **kwargs: Any) -> Response:"""Manually add a recipient to the opt-out list for a specific category or all marketing messages."""+ self._require_resource_access("editor", "You need hog_flow editor access to modify the opt-out list.")+serializer = AddOptOutRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)identifier = serializer.validated_data["identifier"]category_key = serializer.validated_data.get("category_key")+ category = Noneif category_key:- try:- category = MessageCategory.objects.get(key=category_key, team_id=self.team_id)- except MessageCategory.DoesNotExist:+ category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()+ if category is None:return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)- category_id = str(category.id)- else:- category_id = ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ category_id = str(category.id) if category else ALL_MESSAGE_PREFERENCE_CATEGORY_IDpreference, created = MessageRecipientPreference.objects.get_or_create(team_id=self.team_id,@@ -209,9 +267,86 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)preference.set_preference(category_id, PreferenceStatus.OPTED_OUT)+ # Customer.io round-trips can take tens of seconds, so sync off the request path+ # once the preference write has committed.+ transaction.on_commit(lambda: sync_preferences_to_customerio_task.delay(self.team_id, identifier))+response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OKreturn Response(MessagePreferencesSerializer(preference).data, status=response_status)+ @extend_schema(+ request=RemoveOptOutRequestSerializer,+ responses={201: MessagePreferencesSerializer},+ summary="Remove a recipient from the opt-out list",+ )+ @action(detail=False, methods=["post"])+ def remove_opt_out(self, request: Request, **kwargs: Any) -> Response:+ """Opt a recipient back in to a specific category, or to all marketing messages."""+ self._require_resource_access("editor", "You need hog_flow editor access to modify the opt-out list.")++ serializer = RemoveOptOutRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ identifier = serializer.validated_data["identifier"]+ category_key = serializer.validated_data.get("category_key")++ category = None+ if category_key:+ category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()+ if category is None:+ return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)++ preference, created = MessageRecipientPreference.objects.get_or_create(+ team_id=self.team_id,+ identifier=identifier,+ defaults={"created_by": request.user},+ )+ preferences = dict(preference.preferences or {})++ if category is None:+ preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value+ else:+ self._lift_global_opt_out(preferences, category)+ preferences[str(category.id)] = PreferenceStatus.OPTED_IN.value++ preference.preferences = preferences+ preference.save(update_fields=["preferences", "updated_at"])++ transaction.on_commit(lambda: sync_preferences_to_customerio_task.delay(self.team_id, identifier))++ response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK+ return Response(MessagePreferencesSerializer(preference).data, status=response_status)++ def _lift_global_opt_out(self, preferences: dict[str, Any], category: MessageCategory) -> None:+ """Clear a `$all` opt-out that would otherwise swallow a per-category resubscribe.++ Sends check the category and `$all` together, so opting someone back in to one category+ does nothing while `$all` stays opted out. Pin the team's other marketing categories to+ opted out first, so lifting `$all` resubscribes only the category the caller named+ instead of silently widening consent to everything.++ The pinning overwrites even an explicit OPTED_IN on a sibling category (e.g. one a+ Customer.io webhook recorded): while `$all` was opted out that opt-in was inert, so+ preserving the recipient's effective state means opting the sibling out, not letting+ the stale opt-in spring back to life.+ """+ if category.category_type != MessageCategoryType.MARKETING:+ return+ if preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) != PreferenceStatus.OPTED_OUT.value:+ return++ other_category_ids = (+ MessageCategory.objects.filter(+ team_id=self.team_id, category_type=MessageCategoryType.MARKETING, deleted=False+ )+ .exclude(id=category.id)+ .values_list("id", flat=True)+ )+ for other_category_id in other_category_ids:+ preferences[str(other_category_id)] = PreferenceStatus.OPTED_OUT.value++ preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value+@extend_schema(parameters=[OpenApiParameter(@@ -231,6 +366,8 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@action(detail=False, methods=["get"])def export_opt_outs_csv(self, request, **kwargs):"""Stream the opt-out list for a category as a CSV file that can be re-imported as-is."""+ self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")+category_key = request.query_params.get("category_key")service = OptOutService(team_id=self.team_id, user=request.user)@@ -259,6 +396,8 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@action(detail=False, methods=["post"])def bulk_add_opt_outs(self, request, **kwargs):"""Opt every recipient in the list out of the category named on their entry, or a default category."""+ self._require_resource_access("editor", "You need hog_flow editor access to modify the opt-out list.")+serializer = BulkAddOptOutsRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)@@ -275,20 +414,37 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response(BulkAddOptOutsResultSerializer(result).data, status=status.HTTP_200_OK)+ @extend_schema(+ responses={200: WebhookUrlSerializer},+ summary="Get the Customer.io webhook URL for the team",+ )@action(detail=False, methods=["get"])- def webhook_url(self, request, **kwargs):+ def webhook_url(self, request: Request, **kwargs: Any) -> Response:"""Return the webhook URL for Customer.io integration setup."""+ self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")+base = request.build_absolute_uri("/")[:-1]return Response({"url": f"{base}/api/environments/{self.team_id}/messaging/customerio/webhook/"})+ @extend_schema(+ request=GenerateLinkRequestSerializer,+ responses={200: PreferencesLinkSerializer},+ summary="Generate a preferences page link for a recipient",+ )@action(detail=False, methods=["post"])- def generate_link(self, request, **kwargs):+ def generate_link(self, request: Request, **kwargs: Any) -> Response:"""Generate an unsubscribe link for the current user's email address"""- user = request.user- if not user or not user.email:+ # The minted token lets whoever holds it rewrite that recipient's preferences, so this+ # action is gated as a write despite being read-shaped.+ self._require_resource_access("editor", "You need hog_flow editor access to generate a preferences link.")++ user_email = getattr(request.user, "email", None)+ if not user_email:return Response({"error": "User email not found"}, status=400)- identifier = request.data.get("recipient", user.email)+ serializer = GenerateLinkRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ identifier = serializer.validated_data.get("recipient", user_email)token = plugin_server_api.generate_messaging_preferences_token(self.team_id, identifier)diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.pyindex 9738d160069f..7c21f97ed2ae 100644--- a/products/messaging/backend/api/test/test_message_preferences.py+++ b/products/messaging/backend/api/test/test_message_preferences.py@@ -8,10 +8,13 @@ from django.urls import reversefrom parameterized import parameterizedfrom requests import Response+from rest_framework import statusimport posthog.plugins.plugin_server_api as plugin_server_api+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value-from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryTypefrom products.messaging.backend.models.message_preferences import (ALL_MESSAGE_PREFERENCE_CATEGORY_ID,EMAIL_TRACKING_PREFERENCE_ID,@@ -692,3 +695,197 @@ class TestMessagePreferencesAPIViewSet(APIBaseTest):self.assertFalse(MessageRecipientPreference.objects.filter(team=other_team, identifier="[email protected]").exists())++ def _remove_opt_out(self, payload: dict):+ return self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/remove_opt_out/",+ payload,+ content_type="application/json",+ )++ def test_remove_opt_out_global_clears_the_all_block(self):+ recipient = MessageRecipientPreference.objects.create(+ team=self.team,+ identifier="[email protected]",+ preferences={+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value,+ str(self.category.id): PreferenceStatus.OPTED_OUT.value,+ },+ )++ response = self._remove_opt_out({"identifier": "[email protected]"})++ self.assertEqual(response.status_code, 200)+ recipient.refresh_from_db()+ self.assertEqual(+ recipient.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID),+ PreferenceStatus.OPTED_IN,+ )+ # A per-category opt-out the recipient never lifted stays in place+ self.assertEqual(recipient.get_preference(str(self.category.id)), PreferenceStatus.OPTED_OUT)++ listed = self.client.get(f"/api/environments/{self.team.id}/messaging_preferences/opt_outs/")+ self.assertEqual(listed.json()["count"], 0)++ def test_remove_opt_out_for_unknown_recipient_records_the_opt_in(self):+ response = self._remove_opt_out({"identifier": "[email protected]"})++ self.assertEqual(response.status_code, 201)+ preference = MessageRecipientPreference.objects.get(team=self.team, identifier="[email protected]")+ self.assertEqual(+ preference.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID),+ PreferenceStatus.OPTED_IN,+ )++ @parameterized.expand(+ [+ ("sibling_without_stored_preference", None),+ ("sibling_with_stale_opt_in", PreferenceStatus.OPTED_IN.value),+ ]+ )+ def test_remove_opt_out_for_category_lifts_all_without_widening_consent(self, _name, sibling_status):+ # A globally unsubscribed recipient: opting them back in to one category has to clear+ # $all (or the send is still blocked) without turning the other marketing categories+ # back on. That includes a sibling holding a stale explicit opt-in (e.g. recorded by a+ # Customer.io webhook before the global unsubscribe): it was inert while $all was opted+ # out, so it must be pinned to opted out rather than resurrected.+ preferences = {ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value}+ if sibling_status is not None:+ preferences[str(self.category2.id)] = sibling_status+ recipient = MessageRecipientPreference.objects.create(+ team=self.team,+ identifier="[email protected]",+ preferences=preferences,+ )++ response = self._remove_opt_out({"identifier": "[email protected]", "category_key": self.category.key})++ self.assertEqual(response.status_code, 200)+ recipient.refresh_from_db()+ prefs = recipient.get_all_preferences()+ self.assertEqual(prefs[str(self.category.id)], PreferenceStatus.OPTED_IN)+ self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_IN)+ self.assertEqual(prefs[str(self.category2.id)], PreferenceStatus.OPTED_OUT)++ def test_remove_opt_out_for_transactional_category_leaves_all_block_alone(self):+ transactional = MessageCategory.objects.create(+ team=self.team,+ key="receipts",+ name="Receipts",+ category_type=MessageCategoryType.TRANSACTIONAL,+ )+ recipient = MessageRecipientPreference.objects.create(+ team=self.team,+ identifier="[email protected]",+ preferences={ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value},+ )++ response = self._remove_opt_out({"identifier": "[email protected]", "category_key": transactional.key})++ self.assertEqual(response.status_code, 200)+ recipient.refresh_from_db()+ prefs = recipient.get_all_preferences()+ self.assertEqual(prefs[str(transactional.id)], PreferenceStatus.OPTED_IN)+ self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)++ def test_remove_opt_out_nonexistent_category(self):+ response = self._remove_opt_out({"identifier": "[email protected]", "category_key": "does_not_exist"})++ self.assertEqual(response.status_code, 404)+ self.assertEqual(response.json()["error"], "Category not found")++ @parameterized.expand(+ [+ ("add_opt_out", PreferenceStatus.OPTED_OUT),+ ("remove_opt_out", PreferenceStatus.OPTED_IN),+ ]+ )+ @patch("products.messaging.backend.tasks.sync_preferences_to_customerio")+ def test_opt_out_writes_are_synced_to_customerio(self, endpoint, expected_status, mock_sync):+ # Exercises the whole dispatch chain: the view enqueues the task on commit, and the+ # task (eager in tests) reads the row back and calls the sync service.+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/{endpoint}/",+ {"identifier": "[email protected]"},+ content_type="application/json",+ )++ self.assertEqual(response.status_code, 201)+ mock_sync.assert_called_once_with(+ self.team.id,+ "[email protected]",+ {ALL_MESSAGE_PREFERENCE_CATEGORY_ID: expected_status.value},+ )++ @patch("posthog.plugins.plugin_server_api.generate_messaging_preferences_token", return_value="tok-123")+ def test_generate_link_defaults_to_the_callers_email(self, mock_token):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/generate_link/",+ {},+ content_type="application/json",+ )++ self.assertEqual(response.status_code, 200)+ self.assertTrue(response.json()["preferences_url"].endswith("/messaging-preferences/tok-123/"))+ mock_token.assert_called_once_with(self.team.id, self.user.email)++ @parameterized.expand(+ [+ ("too_long", "a" * 513),+ ("not_a_string", ["not", "a", "string"]),+ ]+ )+ @patch("posthog.plugins.plugin_server_api.generate_messaging_preferences_token")+ def test_generate_link_rejects_invalid_recipient(self, _name, recipient, mock_token):+ response = self.client.post(+ f"/api/environments/{self.team.id}/messaging_preferences/generate_link/",+ {"recipient": recipient},+ content_type="application/json",+ )++ self.assertEqual(response.status_code, 400)+ mock_token.assert_not_called()+++class TestMessagePreferencesAPIKeyAccess(APIBaseTest):+ """+ The opt-out endpoints were `scope_object = "INTERNAL"`, a scope no personal API key can ever+ be granted, so an app with its own subscribe toggle had no way to record a preference change.+ """++ def _create_api_key(self, scopes: list[str]) -> str:+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=scopes,+ )+ return key_value++ @parameterized.expand(+ [+ (["insight:read"], "get", "opt_outs", status.HTTP_403_FORBIDDEN),+ (["hog_flow:read"], "get", "opt_outs", status.HTTP_200_OK),+ (["hog_flow:read"], "post", "remove_opt_out", status.HTTP_403_FORBIDDEN),+ (["hog_flow:write"], "post", "add_opt_out", status.HTTP_201_CREATED),+ (["hog_flow:write"], "post", "remove_opt_out", status.HTTP_201_CREATED),+ ]+ )+ def test_personal_api_key_access(self, scopes, http_method, endpoint, expected_status):+ api_key = self._create_api_key(scopes)+ self.client.logout()++ url = f"/api/projects/{self.team.id}/messaging_preferences/{endpoint}/"+ if http_method == "post":+ response = self.client.post(+ url,+ {"identifier": "[email protected]"},+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {api_key}",+ )+ else:+ response = self.client.get(url, HTTP_AUTHORIZATION=f"Bearer {api_key}")++ self.assertEqual(response.status_code, expected_status)diff --git a/products/messaging/backend/services/customerio_sync_service.py b/products/messaging/backend/services/customerio_sync_service.pyindex d3fbfca479fb..b781027bac48 100644--- a/products/messaging/backend/services/customerio_sync_service.py+++ b/products/messaging/backend/services/customerio_sync_service.py@@ -1,7 +1,7 @@import loggingfrom typing import Any-from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryTypefrom products.messaging.backend.models.message_preferences import ALL_MESSAGE_PREFERENCE_CATEGORY_ID, PreferenceStatusfrom products.messaging.backend.models.optout_sync_config import OptOutSyncConfigfrom products.messaging.backend.services.customerio_client import CustomerIOAPIError, CustomerIOTrackClient@@ -10,8 +10,18 @@ logger = logging.getLogger(__name__)def _build_category_to_topic_map(team_id: int) -> dict[str, str]:- """Map PostHog category UUID -> Customer.io topic key for customerio_* categories only."""- categories = MessageCategory.objects.filter(team_id=team_id, key__startswith="customerio_", deleted=False)+ """Map PostHog category UUID -> Customer.io topic key for customerio_* categories only.++ Restricted to marketing categories: transactional sends bypass opt-outs on our side, so a+ stored preference on a transactional category must not be pushed to Customer.io, where it+ would take effect as a real subscription-topic change.+ """+ categories = MessageCategory.objects.filter(+ team_id=team_id,+ key__startswith="customerio_",+ category_type=MessageCategoryType.MARKETING,+ deleted=False,+ )return {str(cat.id): cat.key.removeprefix("customerio_") for cat in categories}diff --git a/products/messaging/backend/tasks.py b/products/messaging/backend/tasks.pynew file mode 100644index 000000000000..5e9e082695d9--- /dev/null+++ b/products/messaging/backend/tasks.py@@ -0,0 +1,21 @@+from celery import shared_task++from posthog.scoping_audit import skip_team_scope_audit++from products.messaging.backend.models.message_preferences import MessageRecipientPreference+from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio+++@shared_task(ignore_result=True)+@skip_team_scope_audit # MessageRecipientPreference is still on the default manager+def sync_preferences_to_customerio_task(team_id: int, identifier: str) -> None:+ """Push a recipient's current preference state to Customer.io off the request path.++ Reads the row fresh instead of taking a preferences snapshot as an argument, so two+ rapid writes to the same recipient can't sync out of order and leave Customer.io on+ the older state.+ """+ preference = MessageRecipientPreference.objects.filter(team_id=team_id, identifier=identifier).first()+ if preference is None:+ return+ sync_preferences_to_customerio(team_id, identifier, preference.preferences)diff --git a/products/messaging/backend/tests/test_customerio_sync_service.py b/products/messaging/backend/tests/test_customerio_sync_service.pynew file mode 100644index 000000000000..50079d6bd4e4--- /dev/null+++ b/products/messaging/backend/tests/test_customerio_sync_service.py@@ -0,0 +1,48 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.models.integration import Integration++from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType+from products.messaging.backend.models.message_preferences import PreferenceStatus+from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig+from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio+++class TestCustomerIOSyncService(BaseTest):+ def setUp(self):+ super().setUp()+ integration = Integration.objects.create(+ team=self.team,+ kind="customerio-track",+ config={"region": "us"},+ sensitive_config={"site_id": "site", "api_key": "key"},+ created_by=self.user,+ )+ OptOutSyncConfig.objects.create(team=self.team, track_integration=integration, track_enabled=True)++ @patch("products.messaging.backend.services.customerio_sync_service.CustomerIOTrackClient")+ def test_transactional_categories_are_not_pushed_as_topic_changes(self, mock_client_cls):+ # Transactional sends bypass opt-outs, so a stored preference on a transactional+ # category must not reach Customer.io, where it would unsubscribe the recipient from+ # a real topic.+ marketing = MessageCategory.objects.create(team=self.team, key="customerio_newsletter", name="Newsletter")+ transactional = MessageCategory.objects.create(+ team=self.team,+ key="customerio_receipts",+ name="Receipts",+ category_type=MessageCategoryType.TRANSACTIONAL,+ )++ sync_preferences_to_customerio(+ self.team.id,+ "[email protected]",+ {+ str(marketing.id): PreferenceStatus.OPTED_OUT.value,+ str(transactional.id): PreferenceStatus.OPTED_OUT.value,+ },+ )++ mock_client_cls.return_value.update_subscription_preferences.assert_called_once_with(+ "[email protected]", {"newsletter": False}+ )diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex d17a8839a2b3..ec6a368b7b04 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -70,12 +70,13 @@ export interface AddOptOutRequestApi {}export interface MessagePreferencesApi {+ /** Server-assigned UUID for this recipient's preference record. */readonly id: string/** The recipient identifier (e.g. email address). */identifier: string/** When the preference was last updated. */updated_at: string- /** Map of category ID to preference status. */+ /** Map of category ID to preference status (`OPTED_IN`, `OPTED_OUT` or `NO_PREFERENCE`). The reserved `$all` key covers every marketing message. */preferences: unknown}@@ -112,6 +113,19 @@ export interface MessagingErrorApi {error: string}+export interface GenerateLinkRequestApi {+ /**+ * Recipient to generate the link for. Defaults to the requesting user's own email address.+ * @maxLength 512+ */+ recipient?: string+}++export interface PreferencesLinkApi {+ /** Token-gated URL where the recipient can manage their preferences. */+ preferences_url: string+}+/*** OpenAPI shape for the paginated opt-outs response, so the generated clients get the* {count, next, previous, results} envelope instead of an untyped object.@@ -132,6 +146,21 @@ export interface PaginatedOptOutsApi {results: MessagePreferencesApi[]}+export interface RemoveOptOutRequestApi {+ /**+ * The recipient identifier to opt back in (e.g. email address).+ * @maxLength 512+ */+ identifier: string+ /** Optional message category key. If omitted, the recipient is opted back in to all marketing messages. */+ category_key?: string+}++export interface WebhookUrlApi {+ /** URL to register in Customer.io so it posts subscription changes to PostHog. */+ url: string+}+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.tsindex 76360a3d740f..01d6acf9acae 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -13,6 +13,7 @@ import type {AddSuppressionRequestApi,BulkAddOptOutsRequestApi,BulkAddOptOutsResultApi,+ GenerateLinkRequestApi,MessageCategoryApi,MessagePreferencesApi,MessageSuppressionApi,@@ -29,6 +30,9 @@ import type {PatchedDesignPatchApi,PatchedMessageCategoryApi,PatchedMessageTemplateApi,+ PreferencesLinkApi,+ RemoveOptOutRequestApi,+ WebhookUrlApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -420,14 +424,18 @@ export const getMessagingPreferencesGenerateLinkCreateUrl = (projectId: string)/*** Generate an unsubscribe link for the current user's email address+ * @summary Generate a preferences page link for a recipient*/export const messagingPreferencesGenerateLinkCreate = async (projectId: string,+ generateLinkRequestApi?: GenerateLinkRequestApi,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getMessagingPreferencesGenerateLinkCreateUrl(projectId), {+): Promise<PreferencesLinkApi> => {+ return apiMutator<PreferencesLinkApi>(getMessagingPreferencesGenerateLinkCreateUrl(projectId), {...options,method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(generateLinkRequestApi),})}@@ -465,18 +473,40 @@ export const messagingPreferencesOptOutsRetrieve = async (})}+export const getMessagingPreferencesRemoveOptOutCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/messaging_preferences/remove_opt_out/`+}++/**+ * Opt a recipient back in to a specific category, or to all marketing messages.+ * @summary Remove a recipient from the opt-out list+ */+export const messagingPreferencesRemoveOptOutCreate = async (+ projectId: string,+ removeOptOutRequestApi: RemoveOptOutRequestApi,+ options?: RequestInit+): Promise<MessagePreferencesApi> => {+ return apiMutator<MessagePreferencesApi>(getMessagingPreferencesRemoveOptOutCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(removeOptOutRequestApi),+ })+}+export const getMessagingPreferencesWebhookUrlRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/messaging_preferences/webhook_url/`}/*** Return the webhook URL for Customer.io integration setup.+ * @summary Get the Customer.io webhook URL for the team*/export const messagingPreferencesWebhookUrlRetrieve = async (projectId: string,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getMessagingPreferencesWebhookUrlRetrieveUrl(projectId), {+): Promise<WebhookUrlApi> => {+ return apiMutator<WebhookUrlApi>(getMessagingPreferencesWebhookUrlRetrieveUrl(projectId), {...options,method: 'GET',})diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex 51d956bd05b8..3b514b3bce10 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -192,6 +192,39 @@ export const MessagingPreferencesBulkAddOptOutsCreateBody = /* @__PURE__ */ zod.),})+/**+ * Generate an unsubscribe link for the current user's email address+ * @summary Generate a preferences page link for a recipient+ */+export const messagingPreferencesGenerateLinkCreateBodyRecipientMax = 512++export const MessagingPreferencesGenerateLinkCreateBody = /* @__PURE__ */ zod.object({+ recipient: zod+ .string()+ .max(messagingPreferencesGenerateLinkCreateBodyRecipientMax)+ .optional()+ .describe("Recipient to generate the link for. Defaults to the requesting user's own email address."),+})++/**+ * Opt a recipient back in to a specific category, or to all marketing messages.+ * @summary Remove a recipient from the opt-out list+ */+export const messagingPreferencesRemoveOptOutCreateBodyIdentifierMax = 512++export const MessagingPreferencesRemoveOptOutCreateBody = /* @__PURE__ */ zod.object({+ identifier: zod+ .string()+ .max(messagingPreferencesRemoveOptOutCreateBodyIdentifierMax)+ .describe('The recipient identifier to opt back in (e.g. email address).'),+ category_key: zod+ .string()+ .optional()+ .describe(+ 'Optional message category key. If omitted, the recipient is opted back in to all marketing messages.'+ ),+})+/*** Manually suppress an email address so no workflow sends to it.* @summary Manually add an email address to the suppression listdiff --git a/products/messaging/mcp/tools.yaml b/products/messaging/mcp/tools.yamlindex 2a65519145c8..c981a94f1cbb 100644--- a/products/messaging/mcp/tools.yaml+++ b/products/messaging/mcp/tools.yaml@@ -120,3 +120,16 @@ tools:description: >List recipients opted out of a message category, most recently updated first. Omit category_key to listrecipients opted out of all marketing messages.+ opt-outs-remove:+ operation: messaging_preferences_remove_opt_out_create+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Remove a recipient from the opt-out list+ description: >+ Opt a recipient back in to the message category named by category_key, or to all marketing messages if+ omitted. Use to honor a resubscribe recorded in your own app. Repeating a call is safe.diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tsindex 4613638ad52c..a5246591b7a8 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -52,6 +52,7 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set(['inbox-reports-set-state','llma-prompt-label-set','opt-outs-add',+ 'opt-outs-remove','organization-enforce-2fa','organization-enforce-2fa-execute','posthog-connection-forward-execute',diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 2ece4b7b2735..4954187bc816 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -187,6 +187,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = ("inbox-reports-set-state","llma-prompt-label-set","opt-outs-add",+ "opt-outs-remove","organization-enforce-2fa","organization-enforce-2fa-execute","posthog-connection-forward-execute",diff --git a/products/workflows/backend/api/test/test_message_preferences_access_control.py b/products/workflows/backend/api/test/test_message_preferences_access_control.pynew file mode 100644index 000000000000..2d3f83fabcae--- /dev/null+++ b/products/workflows/backend/api/test/test_message_preferences_access_control.py@@ -0,0 +1,112 @@+import uuid++import pytest+from posthog.test.base import APIBaseTest++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+++class TestMessagePreferencesAccessControl(APIBaseTest):+ """+ Guards the resource-level RBAC gate on `/api/projects/:id/messaging_preferences/`.++ The endpoints act on team-wide data (every opted-out recipient, every add/remove) but carry+ no per-workflow object. `AccessControlPermission` alone falls back to "does the user have+ access to any single hog_flow object?" — which would let a member granted access to one+ workflow read or rewrite the entire team's opt-out list.++ Test lives under products/workflows because the RBAC gate is a hog_flow concern; the viewset+ itself lives in products/messaging (tach forbids messaging from importing ee/workflows).+ """++ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ self.object_editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.resource_viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.resource_editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ # Project-wide default of `none` — without this, org members have implicit editor access+ # on every resource and the resource-level check trivially passes.+ AccessControl.objects.create(+ team=self.team,+ resource="hog_flow",+ resource_id=None,+ access_level="none",+ organization_member=None,+ role=None,+ )++ # The object-level grant uses an arbitrary UUID — the resource-level check runs before any+ # per-object lookup, so a real HogFlow row isn't needed to prove the regression.+ self._grant(self.object_editor, access_level="editor", resource_id=str(uuid.uuid4()))+ self._grant(self.resource_viewer, access_level="viewer", resource_id=None)+ self._grant(self.resource_editor, access_level="editor", resource_id=None)++ def _grant(self, user: User, *, access_level: str, resource_id: str | None) -> None:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="hog_flow",+ resource_id=resource_id,+ access_level=access_level,+ organization_member=membership,+ )++ def _url(self, action: str) -> str:+ return f"/api/projects/{self.team.id}/messaging_preferences/{action}/"++ @parameterized.expand(+ [+ # (grant_type, list_status, add_status, remove_status)+ # Regression case: an object-level grant on one workflow must not unlock team-wide endpoints.+ ("object_editor", status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),+ # Resource-level viewer reads but can't mutate.+ ("resource_viewer", status.HTTP_200_OK, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),+ # Resource-level editor is fully authorized end-to-end.+ ("resource_editor", status.HTTP_200_OK, status.HTTP_201_CREATED, status.HTTP_200_OK),+ ]+ )+ def test_access_matrix(self, grant_type: str, list_status: int, add_status: int, remove_status: int) -> None:+ user = getattr(self, grant_type)+ self.client.force_login(user)++ assert self.client.get(self._url("opt_outs")).status_code == list_status+ assert self.client.get(self._url("export_opt_outs_csv")).status_code == list_status+ assert (+ self.client.post(+ self._url("add_opt_out"), {"identifier": f"{grant_type}@example.com"}, format="json"+ ).status_code+ == add_status+ )+ assert (+ self.client.post(+ self._url("remove_opt_out"), {"identifier": f"{grant_type}@example.com"}, format="json"+ ).status_code+ == remove_status+ )+ bulk_status = status.HTTP_200_OK if add_status != status.HTTP_403_FORBIDDEN else status.HTTP_403_FORBIDDEN+ assert (+ self.client.post(+ self._url("bulk_add_opt_outs"),+ {"opt_outs": [{"identifier": f"bulk-{grant_type}@example.com"}]},+ format="json",+ ).status_code+ == bulk_status+ )diff --git a/products/workflows/frontend/OptOuts/OptOutList.tsx b/products/workflows/frontend/OptOuts/OptOutList.tsxindex 1c351fe61780..7f43e5b5aa74 100644--- a/products/workflows/frontend/OptOuts/OptOutList.tsx+++ b/products/workflows/frontend/OptOuts/OptOutList.tsx@@ -7,6 +7,7 @@ import {IconExternal,IconPlus,IconRefresh,+ IconRevert,IconUpload,} from '@posthog/icons'import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'@@ -18,9 +19,10 @@ import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'import { DataTable } from '~/queries/nodes/DataTable/DataTable'import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'+import type { MessagePreferencesApi } from 'products/messaging/frontend/generated/api.schemas'+import type { MessageCategory } from './optOutCategoriesLogic'import { optOutListLogic } from './optOutListLogic'-import type { OptOutEntry } from './types'export function OptOutList({ category }: { category?: MessageCategory }): JSX.Element {const logic = optOutListLogic({ category })@@ -33,6 +35,7 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.ElsetShowAddOptOutModal,setNewOptOutIdentifier,addOptOut,+ removeOptOut,setShowImportCsvModal,setCsvFile,importCsv,@@ -47,6 +50,8 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.ElcurrentPage,showAddOptOutModal,addOptOutLoading,+ removeOptOutLoading,+ pendingRemoveIdentifier,newOptOutIdentifier,showImportCsvModal,csvFile,@@ -77,7 +82,7 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El}: null- const columns: LemonTableColumns<OptOutEntry> = [+ const columns: LemonTableColumns<MessagePreferencesApi> = [{title: 'Recipient',dataIndex: 'identifier',@@ -91,7 +96,8 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El},{width: 0,- render: function Render(_, optOutEntry: OptOutEntry): JSX.Element {+ render: function Render(_, optOutEntry: MessagePreferencesApi): JSX.Element {+ const removingThisRow = removeOptOutLoading && pendingRemoveIdentifier === optOutEntry.identifierreturn (<Moreoverlay={@@ -107,6 +113,15 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El>Manage</LemonButton>+ <LemonButton+ onClick={() => removeOptOut(optOutEntry.identifier)}+ loading={removingThisRow}+ disabledReason={removingThisRow ? 'Removing…' : undefined}+ fullWidth+ icon={<IconRevert />}+ >+ Remove opt-out+ </LemonButton></>}/>@@ -254,7 +269,9 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.ElonChange={setNewOptOutIdentifier}autoFocusonPressEnter={() => {- if (newOptOutIdentifier.trim()) {+ // Guard against a second Enter mid-flight firing a duplicate POST — the+ // footer button already disables while loading; mirror that here.+ if (newOptOutIdentifier.trim() && !addOptOutLoading) {addOptOut(newOptOutIdentifier.trim())}}}diff --git a/products/workflows/frontend/OptOuts/optOutListLogic.ts b/products/workflows/frontend/OptOuts/optOutListLogic.tsindex 44da14e766bc..8dd371bf7d39 100644--- a/products/workflows/frontend/OptOuts/optOutListLogic.ts+++ b/products/workflows/frontend/OptOuts/optOutListLogic.ts@@ -4,15 +4,25 @@ import Papa from 'papaparse'import { lemonToast } from '@posthog/lemon-ui'-import api, { CountedPaginatedResponse } from 'lib/api'+import api from 'lib/api'import { downloadFile } from 'lib/utils/dom'+import { projectLogic } from 'scenes/projectLogic'-import type { BulkAddOptOutsResultApi } from 'products/messaging/frontend/generated/api.schemas'+import {+ messagingPreferencesAddOptOutCreate,+ messagingPreferencesOptOutsRetrieve,+ messagingPreferencesRemoveOptOutCreate,+} from 'products/messaging/frontend/generated/api'+import type {+ BulkAddOptOutsResultApi,+ MessagePreferencesApi,+ PaginatedOptOutsApi,+} from 'products/messaging/frontend/generated/api.schemas'import { MessageCategory } from './optOutCategoriesLogic'import { BULK_OPT_OUT_CHUNK_SIZE, MAX_REPORTED_ERRORS, parseOptOutRows, remapEntryErrors } from './optOutCsvImport'import { optOutSceneLogic } from './optOutSceneLogic'-import type { OptOutEntry, OptOutPersonPreference } from './types'+import type { OptOutPersonPreference } from './types'async function parseCsvFile(file: File): Promise<string[][]> {return new Promise((resolve, reject) => {@@ -24,9 +34,9 @@ async function parseCsvFile(file: File): Promise<string[][]> {})}-export type { OptOutEntry, OptOutPersonPreference }+export type { OptOutPersonPreference }-export type PaginatedOptOuts = CountedPaginatedResponse<OptOutEntry>+const EMPTY_OPT_OUTS: PaginatedOptOutsApi = { count: 0, next: null, previous: null, results: [] }export type OptOutListLogicProps = {category?: MessageCategory@@ -35,7 +45,8 @@ export type OptOutListLogicProps = {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface optOutListLogicValues {preferencesUrlLoading: boolean // optOutSceneLogic- addOptOut: OptOutEntry | null+ currentProjectId: number | null // projectLogic+ addOptOut: MessagePreferencesApi | nulladdOptOutLoading: booleancsvExport: nullcsvExportLoading: boolean@@ -46,9 +57,12 @@ export interface optOutListLogicValues {currentPage: numbermanagePreferencesModalOpen: booleannewOptOutIdentifier: string- optOutPersons: PaginatedOptOuts+ optOutPersons: PaginatedOptOutsApioptOutPersonsLoading: boolean+ pendingRemoveIdentifier: string | nullpersonsModalOpen: boolean+ removeOptOut: string | null+ removeOptOutLoading: booleanselectedIdentifier: string | nullshowAddOptOutModal: booleanshowImportCsvModal: boolean@@ -66,10 +80,10 @@ export interface optOutListLogicActions {errorObject?: any}addOptOutSuccess: (- addOptOut: OptOutEntry,+ addOptOut: MessagePreferencesApi,payload?: string) => {- addOptOut: OptOutEntry+ addOptOut: MessagePreferencesApipayload?: string}clearCsvImportResult: () => any@@ -128,12 +142,12 @@ export interface optOutListLogicActions {errorObject?: any}loadNextPageSuccess: (- optOutPersons: PaginatedOptOuts,+ optOutPersons: PaginatedOptOutsApi,payload?: {value: true}) => {- optOutPersons: PaginatedOptOuts+ optOutPersons: PaginatedOptOutsApipayload?: {value: true}@@ -147,10 +161,10 @@ export interface optOutListLogicActions {errorObject?: any}loadOptOutPersonsSuccess: (- optOutPersons: PaginatedOptOuts,+ optOutPersons: PaginatedOptOutsApi,payload?: any) => {- optOutPersons: PaginatedOptOuts+ optOutPersons: PaginatedOptOutsApipayload?: any}loadPreviousPage: () => {@@ -164,12 +178,12 @@ export interface optOutListLogicActions {errorObject?: any}loadPreviousPageSuccess: (- optOutPersons: PaginatedOptOuts,+ optOutPersons: PaginatedOptOutsApi,payload?: {value: true}) => {- optOutPersons: PaginatedOptOuts+ optOutPersons: PaginatedOptOutsApipayload?: {value: true}@@ -177,6 +191,21 @@ export interface optOutListLogicActions {loadUnsubscribeLink: () => {value: true}+ removeOptOut: (identifier: string) => string+ removeOptOutFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ removeOptOutSuccess: (+ removeOptOut: string,+ payload?: string+ ) => {+ removeOptOut: string+ payload?: string+ }setCsvFile: (file: File | null) => {file: File | null}@@ -223,7 +252,7 @@ export const optOutListLogic = kea<optOutListLogicType>([path(['products', 'workflows', 'frontend', 'OptOuts', 'optOutListLogic']),props({} as OptOutListLogicProps),connect(() => ({- values: [optOutSceneLogic, ['preferencesUrlLoading']],+ values: [optOutSceneLogic, ['preferencesUrlLoading'], projectLogic, ['currentProjectId']],actions: [optOutSceneLogic, ['openPreferencesPage']],})),actions({@@ -295,6 +324,16 @@ export const optOutListLogic = kea<optOutListLogicType>([setShowAddOptOutModal: (state, { show }) => (show ? state : ''),},],+ pendingRemoveIdentifier: [+ // Which row's removal is in flight: removeOptOutLoading alone is one boolean for the+ // whole table, so every row's Remove button would show "Removing…" during any removal.+ null as string | null,+ {+ removeOptOut: (_, identifier) => identifier,+ removeOptOutSuccess: () => null,+ removeOptOutFailure: () => null,+ },+ ],showImportCsvModal: [false,{@@ -321,133 +360,170 @@ export const optOutListLogic = kea<optOutListLogicType>([},],}),- loaders(({ props, values, actions }) => ({- addOptOut: {- __default: null as OptOutEntry | null,- addOptOut: async (identifier: string): Promise<OptOutEntry> => {- try {- const result = await api.messaging.addOptOut(identifier, props.category?.key)- lemonToast.success(`${identifier} added to opt-out list`)- actions.loadOptOutPersons()- return result- } catch (e) {- lemonToast.error('Failed to add opt-out')- throw e- }- },- },- optOutPersons: {- __default: { count: 0, next: null, previous: null, results: [] } as PaginatedOptOuts,- loadOptOutPersons: async (): Promise<PaginatedOptOuts> => {- try {- return await api.messaging.getMessageOptOuts(props.category?.key, 1)- } catch {- lemonToast.error('Failed to load opt-out persons')- return { count: 0, next: null, previous: null, results: [] }- }- },- loadNextPage: async (): Promise<PaginatedOptOuts> => {- const nextPage = values.currentPage + 1- try {- const result = await api.messaging.getMessageOptOuts(props.category?.key, nextPage)- return result- } catch {- lemonToast.error('Failed to load next page')- return values.optOutPersons- }+ loaders(({ props, values, actions }) => {+ const fetchPage = async (page: number): Promise<PaginatedOptOutsApi> => {+ if (values.currentProjectId === null) {+ return EMPTY_OPT_OUTS+ }+ return await messagingPreferencesOptOutsRetrieve(String(values.currentProjectId), {+ category_key: props.category?.key,+ page,+ })+ }++ return {+ addOptOut: {+ __default: null as MessagePreferencesApi | null,+ addOptOut: async (identifier: string): Promise<MessagePreferencesApi> => {+ if (values.currentProjectId === null) {+ throw new Error('No current project')+ }+ try {+ const result = await messagingPreferencesAddOptOutCreate(String(values.currentProjectId), {+ identifier,+ category_key: props.category?.key,+ })+ lemonToast.success(`${identifier} added to opt-out list`)+ actions.loadOptOutPersons()+ return result+ } catch (e) {+ lemonToast.error('Failed to add opt-out')+ throw e+ }+ },},- loadPreviousPage: async (): Promise<PaginatedOptOuts> => {- const prevPage = Math.max(1, values.currentPage - 1)- try {- const result = await api.messaging.getMessageOptOuts(props.category?.key, prevPage)- return result- } catch {- lemonToast.error('Failed to load previous page')- return values.optOutPersons- }+ removeOptOut: {+ __default: null as string | null,+ removeOptOut: async (identifier: string): Promise<string> => {+ if (values.currentProjectId === null) {+ throw new Error('No current project')+ }+ try {+ await messagingPreferencesRemoveOptOutCreate(String(values.currentProjectId), {+ identifier,+ category_key: props.category?.key,+ })+ lemonToast.success(`${identifier} removed from opt-out list`)+ actions.loadOptOutPersons()+ return identifier+ } catch (e) {+ lemonToast.error('Failed to remove opt-out')+ throw e+ }+ },},- },- csvExport: {- __default: null as null,- exportCsv: async (): Promise<null> => {- try {- const blob = await api.messaging.exportOptOutsCsv(props.category?.key)- downloadFile(new File([blob], `opt-outs-${props.category?.key ?? 'all-marketing'}.csv`))- } catch {- lemonToast.error('Failed to export opt-outs')- }- return null+ optOutPersons: {+ __default: EMPTY_OPT_OUTS,+ loadOptOutPersons: async (): Promise<PaginatedOptOutsApi> => {+ try {+ return await fetchPage(1)+ } catch (e) {+ lemonToast.error('Failed to load opt-out persons')+ // Rethrow so kea-loaders emits a *Failure action: optOutPersons keeps its+ // previous value instead of rendering a failed fetch as "no opt-outs found",+ // and the currentPage reducer (which only moves on *Success) stays put.+ throw e+ }+ },+ loadNextPage: async (): Promise<PaginatedOptOutsApi> => {+ try {+ return await fetchPage(values.currentPage + 1)+ } catch (e) {+ lemonToast.error('Failed to load next page')+ throw e+ }+ },+ loadPreviousPage: async (): Promise<PaginatedOptOutsApi> => {+ try {+ return await fetchPage(Math.max(1, values.currentPage - 1))+ } catch (e) {+ lemonToast.error('Failed to load previous page')+ throw e+ }+ },},- },- csvImportResult: {- __default: null as BulkAddOptOutsResultApi | null,- clearCsvImportResult: (): BulkAddOptOutsResultApi | null => null,- importCsv: async (): Promise<BulkAddOptOutsResultApi | null> => {- const file = values.csvFile- if (!file) {+ csvExport: {+ __default: null as null,+ exportCsv: async (): Promise<null> => {+ try {+ const blob = await api.messaging.exportOptOutsCsv(props.category?.key)+ downloadFile(new File([blob], `opt-outs-${props.category?.key ?? 'all-marketing'}.csv`))+ } catch {+ lemonToast.error('Failed to export opt-outs')+ }return null- }+ },+ },+ csvImportResult: {+ __default: null as BulkAddOptOutsResultApi | null,+ clearCsvImportResult: (): BulkAddOptOutsResultApi | null => null,+ importCsv: async (): Promise<BulkAddOptOutsResultApi | null> => {+ const file = values.csvFile+ if (!file) {+ return null+ }- let rows: string[][]- try {- rows = await parseCsvFile(file)- } catch {- lemonToast.error("Couldn't read the file. Check that it's a valid CSV and try again.")- return null- }+ let rows: string[][]+ try {+ rows = await parseCsvFile(file)+ } catch {+ lemonToast.error("Couldn't read the file. Check that it's a valid CSV and try again.")+ return null+ }- const parsed = parseOptOutRows(rows)- const result: BulkAddOptOutsResultApi = {- total: parsed.total,- opted_out: 0,- skipped: parsed.skipped,- errors: [...parsed.errors],- }+ const parsed = parseOptOutRows(rows)+ const result: BulkAddOptOutsResultApi = {+ total: parsed.total,+ opted_out: 0,+ skipped: parsed.skipped,+ errors: [...parsed.errors],+ }- if (parsed.entries.length > 0) {- actions.setCsvImportProgress({ processed: 0, total: parsed.entries.length })- }- for (let start = 0; start < parsed.entries.length; start += BULK_OPT_OUT_CHUNK_SIZE) {- const chunk = parsed.entries.slice(start, start + BULK_OPT_OUT_CHUNK_SIZE)- try {- const chunkResult = await api.messaging.bulkAddOptOuts(- chunk.map(({ identifier, category_key }) => ({ identifier, category_key })),- props.category?.key- )- result.opted_out += chunkResult.opted_out- result.skipped += chunkResult.skipped- for (const error of remapEntryErrors(chunkResult.errors, chunk)) {- if (result.errors.length < MAX_REPORTED_ERRORS) {- result.errors.push(error)+ if (parsed.entries.length > 0) {+ actions.setCsvImportProgress({ processed: 0, total: parsed.entries.length })+ }+ for (let start = 0; start < parsed.entries.length; start += BULK_OPT_OUT_CHUNK_SIZE) {+ const chunk = parsed.entries.slice(start, start + BULK_OPT_OUT_CHUNK_SIZE)+ try {+ const chunkResult = await api.messaging.bulkAddOptOuts(+ chunk.map(({ identifier, category_key }) => ({ identifier, category_key })),+ props.category?.key+ )+ result.opted_out += chunkResult.opted_out+ result.skipped += chunkResult.skipped+ for (const error of remapEntryErrors(chunkResult.errors, chunk)) {+ if (result.errors.length < MAX_REPORTED_ERRORS) {+ result.errors.push(error)+ }}+ } catch (e: any) {+ // Already-applied chunks stay applied; re-uploading is safe because+ // importing only ever opts recipients out.+ const remaining = parsed.entries.length - start+ result.errors.push(+ e?.error ||+ e?.detail ||+ `The import stopped with ${remaining.toLocaleString()} recipients left. Upload the same file again to finish. Recipients that were already imported stay opted out.`+ )+ break}- } catch (e: any) {- // Already-applied chunks stay applied; re-uploading is safe because- // importing only ever opts recipients out.- const remaining = parsed.entries.length - start- result.errors.push(- e?.error ||- e?.detail ||- `The import stopped with ${remaining.toLocaleString()} recipients left. Upload the same file again to finish. Recipients that were already imported stay opted out.`- )- break+ actions.setCsvImportProgress({+ processed: Math.min(start + BULK_OPT_OUT_CHUNK_SIZE, parsed.entries.length),+ total: parsed.entries.length,+ })}- actions.setCsvImportProgress({- processed: Math.min(start + BULK_OPT_OUT_CHUNK_SIZE, parsed.entries.length),- total: parsed.entries.length,- })- }- if (result.opted_out > 0) {- lemonToast.success(`Added ${result.opted_out.toLocaleString()} opt-outs`)- actions.loadOptOutPersons()- } else {- lemonToast.warning('No opt-outs were added. Check the file and try again.')- }- return result+ if (result.opted_out > 0) {+ lemonToast.success(`Added ${result.opted_out.toLocaleString()} opt-outs`)+ actions.loadOptOutPersons()+ } else {+ lemonToast.warning('No opt-outs were added. Check the file and try again.')+ }+ return result+ },},- },- })),+ }+ }),afterMount(({ props, actions }) => {// If no category is provided or it's a marketing category, load opt-out personsif (!props.category?.id || props.category?.category_type === 'marketing') {diff --git a/products/workflows/frontend/OptOuts/types.ts b/products/workflows/frontend/OptOuts/types.tsindex df207931e6fb..c3f532755eb8 100644--- a/products/workflows/frontend/OptOuts/types.ts+++ b/products/workflows/frontend/OptOuts/types.ts@@ -1,9 +1,3 @@-export type OptOutEntry = {- identifier: string- source: string- updated_at: string-}-export type OptOutPersonPreference = {identifier: stringpreferences: Record<string, boolean>diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex d354733831b1..39371826503e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7011,6 +7011,20 @@"readOnlyHint": true}},+ "opt-outs-remove": {+ "description": "Opt a recipient back in to the message category named by category_key, or to all marketing messages if omitted. Use to honor a resubscribe recorded in your own app. Repeating a call is safe.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "Remove a recipient from the opt-out list",+ "title": "Remove a recipient from the opt-out list",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"org-member-get-github-login": {"description": "Resolve the GitHub username (login) for a single organization member, given their PostHog user UUID (obtainable from org-members-list, or \"@me\" for the current user). Returns null if the member has no GitHub identity linked. Use this when you know which member you want and need their GitHub handle — for example to set suggested reviewers.","category": "Platform Features",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f9c694d000b0..399853ec8fe7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7537,6 +7537,20 @@"readOnlyHint": true}},+ "opt-outs-remove": {+ "description": "Opt a recipient back in to the message category named by category_key, or to all marketing messages if omitted. Use to honor a resubscribe recorded in your own app. Repeating a call is safe.",+ "category": "Messaging",+ "feature": "messaging",+ "summary": "Remove a recipient from the opt-out list",+ "title": "Remove a recipient from the opt-out list",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"org-member-get-github-login": {"description": "Resolve the GitHub username (login) for a single organization member, given their PostHog user UUID (obtainable from org-members-list, or \"@me\" for the current user). Returns null if the member has no GitHub identity linked. Use this when you know which member you want and need their GitHub handle — for example to set suggested reviewers.","category": "Platform Features",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 05a12c463966..0c134cd534c7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34706,6 +34706,14 @@ export namespace Schemas {period?: Period;}+ export interface GenerateLinkRequest {+ /**+ * Recipient to generate the link for. Defaults to the requesting user's own email address.+ * @maxLength 512+ */+ recipient?: string;+ }+export interface SuggestedRule {/** re2 pattern matching the dynamic path segment. */regex: string;@@ -43772,12 +43780,13 @@ export namespace Schemas {}export interface MessagePreferences {+ /** Server-assigned UUID for this recipient's preference record. */readonly id: string;/** The recipient identifier (e.g. email address). */identifier: string;/** When the preference was last updated. */updated_at: string;- /** Map of category ID to preference status. */+ /** Map of category ID to preference status (`OPTED_IN`, `OPTED_OUT` or `NO_PREFERENCE`). The reserved `$all` key covers every marketing message. */preferences: unknown;}@@ -59721,6 +59730,11 @@ export namespace Schemas {Postgres: 'Postgres',} as const;+ export interface PreferencesLink {+ /** Token-gated URL where the recipient can manage their preferences. */+ preferences_url: string;+ }+export interface PreviewInviteRequest {/*** Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.@@ -64860,6 +64874,16 @@ export namespace Schemas {run_id?: string | null;}+ export interface RemoveOptOutRequest {+ /**+ * The recipient identifier to opt back in (e.g. email address).+ * @maxLength 512+ */+ identifier: string;+ /** Optional message category key. If omitted, the recipient is opted back in to all marketing messages. */+ category_key?: string;+ }+export interface ReorderTilesRequest {/*** Array of tile IDs in the desired display order (top to bottom, left to right).@@ -76267,6 +76291,11 @@ export namespace Schemas {achievements_opt_out: boolean;}+ export interface WebhookUrl {+ /** URL to register in Customer.io so it posts subscription changes to PostHog. */+ url: string;+ }+export interface WeeklyDigestResponse {/** Unique visitors. */visitors: NumericMetric;diff --git a/services/mcp/src/generated/messaging/api.ts b/services/mcp/src/generated/messaging/api.tsindex b6612af0f2cd..9c985c754dcf 100644--- a/services/mcp/src/generated/messaging/api.ts+++ b/services/mcp/src/generated/messaging/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 2 enabled ops+ * PostHog API - MCP 3 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -67,3 +67,30 @@ export const MessagingPreferencesOptOutsRetrieveQueryParams = /* @__PURE__ */ zopage: zod.number().optional(),page_size: zod.number().optional(),})++/**+ * Opt a recipient back in to a specific category, or to all marketing messages.+ * @summary Remove a recipient from the opt-out list+ */+export const MessagingPreferencesRemoveOptOutCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const messagingPreferencesRemoveOptOutCreateBodyIdentifierMax = 512++export const MessagingPreferencesRemoveOptOutCreateBody = /* @__PURE__ */ zod.object({+ identifier: zod+ .string()+ .max(messagingPreferencesRemoveOptOutCreateBodyIdentifierMax)+ .describe('The recipient identifier to opt back in (e.g. email address).'),+ category_key: zod+ .string()+ .optional()+ .describe(+ 'Optional message category key. If omitted, the recipient is opted back in to all marketing messages.'+ ),+})diff --git a/services/mcp/src/tools/generated/messaging.ts b/services/mcp/src/tools/generated/messaging.tsindex 00ecbd63311f..18187db02d2d 100644--- a/services/mcp/src/tools/generated/messaging.ts+++ b/services/mcp/src/tools/generated/messaging.ts@@ -5,6 +5,7 @@ import type { Schemas } from '@/api/generated'import {MessagingPreferencesBulkAddOptOutsCreateBody,MessagingPreferencesOptOutsRetrieveQueryParams,+ MessagingPreferencesRemoveOptOutCreateBody,} from '@/generated/messaging/api'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -51,7 +52,31 @@ const optOutsList = (): ToolBase<typeof OptOutsListSchema, Schemas.PaginatedOptO},})+const OptOutsRemoveSchema = MessagingPreferencesRemoveOptOutCreateBody++const optOutsRemove = (): ToolBase<typeof OptOutsRemoveSchema, Schemas.MessagePreferences> => ({+ name: 'opt-outs-remove',+ schema: OptOutsRemoveSchema,+ handler: async (context: Context, params: z.infer<typeof OptOutsRemoveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.identifier !== undefined) {+ body['identifier'] = params.identifier+ }+ if (params.category_key !== undefined) {+ body['category_key'] = params.category_key+ }+ const result = await context.api.request<Schemas.MessagePreferences>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_preferences/remove_opt_out/`,+ body,+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'opt-outs-add': optOutsAdd,'opt-outs-list': optOutsList,+ 'opt-outs-remove': optOutsRemove,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-remove.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-remove.jsonnew file mode 100644index 000000000000..ed35b6c38e09--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-remove.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "category_key": {+ "description": "Optional message category key. If omitted, the recipient is opted back in to all marketing messages.",+ "type": "string"+ },+ "identifier": {+ "description": "The recipient identifier to opt back in (e.g. email address).",+ "maxLength": 512,+ "type": "string"+ }+ },+ "required": ["identifier"],+ "type": "object"+}