: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(workflows): suppress repeatedly-bouncing email addresses (#71038)
Meikel Ratz6b1a875925f8
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 247f20b2a723..34060dcaf2c6 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -536,6 +536,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analyticsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows+ WORKFLOWS_SUPPRESSION_LIST: 'workflows-suppression-list', // owner: #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features} as constexport type FeatureFlagLookupKey = keyof typeof FEATURE_FLAGSdiff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 5116168945bb..1c3a453f96c5 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -164,7 +164,8 @@ export class CdpApi {services.capturedEventsService,services.teamWorkflowsConfigService,services.recipientsManager,- new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),+ services.emailSuppressionService)this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.batchExportHogFunctionService = new BatchExportHogFunctionService(diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex ac6ce5ccf843..31ad270d75ba 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -31,6 +31,7 @@ import { HogFunctionTemplateManagerService } from './services/managers/hog-functimport { IntegrationManagerService } from './services/managers/integration-manager.service'import { RecipientsManagerService } from './services/managers/recipients-manager.service'import { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'+import { EmailSuppressionService } from './services/messaging/email-suppression.service'import { EmailValidationService } from './services/messaging/email-validation.service'import { EmailService } from './services/messaging/email.service'import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'@@ -89,6 +90,7 @@ export interface CdpCoreServices {hogFlowFunctionsService: HogFlowFunctionsServicerecipientsManager: RecipientsManagerServicerecipientPreferencesService: RecipientPreferencesService+ emailSuppressionService: EmailSuppressionServiceteamWorkflowsConfigService: TeamWorkflowsConfigServicehogFlowExecutor: HogFlowExecutorServicehogFunctionMonitoringService: HogFunctionMonitoringService@@ -144,6 +146,9 @@ export type CdpCoreServicesConfig = Pick<| 'SES_SECRET_ACCESS_KEY'| 'SES_REGION'| 'SES_ENDPOINT'+ | 'EMAIL_SUPPRESSION_WRITE_ENABLED'+ | 'EMAIL_SUPPRESSION_ENFORCE_ENABLED'+ | 'EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD'| 'CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN'| 'CDP_FETCH_RETRIES'| 'CDP_FETCH_BACKOFF_BASE_MS'@@ -392,6 +397,14 @@ export function createCdpCoreServices(const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)const messageAssetsService = new MessageAssetsService(outputs)+ // Constructed here (rather than below with the other messaging services) so it can be threaded+ // into EmailService — the pre-send suppression check lives there so every send path shares one+ // choke point regardless of whether the invocation came from a workflow action or a hog function.+ const emailSuppressionService = new EmailSuppressionService(deps.postgres, {+ writeEnabled: config.EMAIL_SUPPRESSION_WRITE_ENABLED,+ enforceEnabled: config.EMAIL_SUPPRESSION_ENFORCE_ENABLED,+ transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,+ })const emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,@@ -404,6 +417,7 @@ export function createCdpCoreServices(config.ENCRYPTION_SALT_KEYS,config.SITE_URL,trackingCodeSigner,+ emailSuppressionService,messageAssetsService)const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)@@ -444,7 +458,7 @@ export function createCdpCoreServices()const recipientsManager = new RecipientsManagerService(deps.postgres)- const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)+ const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)// MX verdicts live on the dedicated SES Valkey (same instance as the SES rate// limiter, separate pool). The pool is created by the server only on pods// whose capabilities execute email actions; everywhere else this is null@@ -487,6 +501,7 @@ export function createCdpCoreServices(hogFlowFunctionsService,recipientsManager,recipientPreferencesService,+ emailSuppressionService,teamWorkflowsConfigService,hogFlowExecutor,hogFunctionMonitoringService,diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 27e7a0996091..e92f51dbd4e5 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -131,6 +131,18 @@ export type CdpConfig = ClickhouseConfig & {SES_ACCESS_KEY_ID: stringSES_SECRET_ACCESS_KEY: stringSES_REGION: string+ // Comma-separated allowlist of SNS Topic ARNs the SES webhook accepts events from. Empty string+ // means no restriction (dev/test); production should set this to the workflow SES topic ARN(s).+ SES_ALLOWED_SNS_TOPIC_ARNS: string++ // Two independent kill switches for the email suppression list, both OFF by default so the+ // feature ships dark. WRITE controls whether the SES webhook populates the list; ENFORCE+ // controls whether the pre-send check actually skips suppressed recipients. Separating them+ // lets us turn on writing first and observe what would be suppressed before enforcing.+ EMAIL_SUPPRESSION_WRITE_ENABLED: boolean+ EMAIL_SUPPRESSION_ENFORCE_ENABLED: boolean+ // Consecutive soft bounces before an address is auto-suppressed. Tunable without a deploy.+ EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD: number// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: boolean@@ -281,6 +293,10 @@ export function getDefaultCdpConfig(): CdpConfig {SES_ACCESS_KEY_ID: isTestEnv() || isDevEnv() ? 'test' : '',SES_SECRET_ACCESS_KEY: isTestEnv() || isDevEnv() ? 'test' : '',SES_REGION: isTestEnv() || isDevEnv() ? 'us-east-1' : '',+ SES_ALLOWED_SNS_TOPIC_ARNS: '',+ EMAIL_SUPPRESSION_WRITE_ENABLED: false,+ EMAIL_SUPPRESSION_ENFORCE_ENABLED: false,+ EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD: 5,// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: false,diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex e9064cf8616d..842253625e7c 100644--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts@@ -21,6 +21,7 @@ import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'import { IntegrationManagerService } from '../services/managers/integration-manager.service'import { TeamWorkflowsConfigService } from '../services/managers/team-workflows-config.service'+import { EmailSuppressionService } from '../services/messaging/email-suppression.service'import { EmailService } from '../services/messaging/email.service'import { EmailTrackingCodeSigner } from '../services/messaging/helpers/tracking-code'import { PushNotificationService } from '../services/messaging/push-notification.service'@@ -509,6 +510,11 @@ export function createHogTransformerService(const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)+ const emailSuppressionService = new EmailSuppressionService(deps.postgres, {+ writeEnabled: config.EMAIL_SUPPRESSION_WRITE_ENABLED,+ enforceEnabled: config.EMAIL_SUPPRESSION_ENFORCE_ENABLED,+ transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,+ })const emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,@@ -520,7 +526,8 @@ export function createHogTransformerService(teamWorkflowsConfigService,config.ENCRYPTION_SALT_KEYS,config.SITE_URL,- trackingCodeSigner+ trackingCodeSigner,+ emailSuppressionService)const pushNotificationService = new PushNotificationService(deps.integrationManager,diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex f5e424fa79a0..ed1259f186d3 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -10,6 +10,10 @@ import { HogExecutorService } from '../../../src/cdp/services/hog-executor.serviimport { HogInputsService } from '../../../src/cdp/services/hog-inputs.service'import { TeamWorkflowsConfigService } from '../../../src/cdp/services/managers/team-workflows-config.service'import { EmailService } from '../../../src/cdp/services/messaging/email.service'+import {+ EmailSuppressionService,+ emailSuppressionConfigFromEnv,+} from '../../../src/cdp/services/messaging/email-suppression.service'import { EmailTrackingCodeSigner } from '../../../src/cdp/services/messaging/helpers/tracking-code'import { RecipientTokensService } from '../../../src/cdp/services/messaging/recipient-tokens.service'import { CyclotronJobInvocationHogFunction, HogFunctionType } from '../../../src/cdp/types'@@ -69,7 +73,8 @@ describe('Hog Executor', () => {new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,- new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()))const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)executor = new HogExecutorService(diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 5015f0ab7bc2..cd74a25e7a18 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -16,6 +16,7 @@ import { HogExecutorService } from '../../hog-executor.service'import { HogInputsService } from '../../hog-inputs.service'import { HogFunctionTemplateManagerService } from '../../managers/hog-function-template-manager.service'import { TeamWorkflowsConfigService } from '../../managers/team-workflows-config.service'+import { EmailSuppressionService, emailSuppressionConfigFromEnv } from '../../messaging/email-suppression.service'import { EmailValidationService } from '../../messaging/email-validation.service'import { EmailService } from '../../messaging/email.service'import { EmailTrackingCodeSigner } from '../../messaging/helpers/tracking-code'@@ -61,7 +62,8 @@ describe('HogFunctionHandler', () => {new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,- new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()))mockHogFunctionExecutor = new HogExecutorService({diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex f11a964474fb..4715b758d925 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -22,6 +22,7 @@ import { RecipientTokensService } from '../messaging/recipient-tokens.service'import { HogFunctionTemplateManagerService } from '../managers/hog-function-template-manager.service'import { RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'+import { EmailSuppressionService, emailSuppressionConfigFromEnv } from '../messaging/email-suppression.service'import { EmailValidationService } from '../messaging/email-validation.service'import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'import { HogFlowExecutorService, createHogFlowInvocation } from './hogflow-executor.service'@@ -68,6 +69,7 @@ describe('Hogflow Executor', () => {new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),hub.encryptedFields)+ const emailSuppressionService = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())const emailService = new EmailService({sesAccessKeyId: hub.SES_ACCESS_KEY_ID,@@ -79,7 +81,8 @@ describe('Hogflow Executor', () => {new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,- new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ emailSuppressionService)const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)const hogExecutor = new HogExecutorService(@@ -103,7 +106,7 @@ describe('Hogflow Executor', () => {hogExecutor)const recipientsManager = new RecipientsManagerService(hub.postgres)- const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)+ const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)// Stubbed to always allow: this suite covers executor routing and flow control,// not MX validation (email-validation.service.test.ts does), and the real// service would fire live DNS lookups for the fixture recipients here.diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.test.tsnew file mode 100644index 000000000000..d6287673e454--- /dev/null+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts@@ -0,0 +1,316 @@+import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'+import { Hub, Team } from '~/types'++import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'++interface SuppressionRow {+ identifier: string+ source: string+ suppressed: boolean+ transient_bounce_count: number+ deleted: boolean+}++describe('EmailSuppressionService', () => {+ let hub: Hub+ let team: Team+ let originalWriteEnv: string | undefined+ let originalEnforceEnv: string | undefined+ let originalThresholdEnv: string | undefined++ beforeEach(async () => {+ await resetTestDatabase()+ hub = await createHub()+ team = await getFirstTeam(hub.postgres)+ originalWriteEnv = process.env.EMAIL_SUPPRESSION_WRITE_ENABLED+ originalEnforceEnv = process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED+ originalThresholdEnv = process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD+ })++ afterEach(async () => {+ if (originalWriteEnv === undefined) {+ delete process.env.EMAIL_SUPPRESSION_WRITE_ENABLED+ } else {+ process.env.EMAIL_SUPPRESSION_WRITE_ENABLED = originalWriteEnv+ }+ if (originalEnforceEnv === undefined) {+ delete process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED+ } else {+ process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED = originalEnforceEnv+ }+ if (originalThresholdEnv === undefined) {+ delete process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD+ } else {+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = originalThresholdEnv+ }+ await closeHub(hub)+ })++ const readRow = async (email: string): Promise<SuppressionRow | undefined> => {+ const res = await hub.postgres.query<SuppressionRow>(+ PostgresUse.COMMON_READ,+ `SELECT identifier, source, suppressed, transient_bounce_count, deleted+ FROM posthog_messagesuppression+ WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-suppression'+ )+ return res.rows[0]+ }++ describe('recordTransientBounces (write flag on, threshold=3)', () => {+ beforeEach(() => {+ process.env.EMAIL_SUPPRESSION_WRITE_ENABLED = 'true'+ // Threshold=3 gives a clean boundary: 2 bounces must not flip, 3 must.+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '3'+ })++ it.each([+ ['below threshold — 2 consecutive bounces stay unsuppressed', 2, false],+ ['at threshold — the 3rd consecutive bounce flips suppressed', 3, true],+ ] as const)('%s', async (_label, bounces, expectedSuppressed) => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ for (let i = 0; i < bounces; i++) {+ await svc.recordTransientBounces(team.id, [email], 'temp')+ }+ expect(await readRow(email)).toMatchObject({+ identifier: email,+ source: 'BOUNCE',+ transient_bounce_count: bounces,+ suppressed: expectedSuppressed,+ deleted: false,+ })+ })+ })++ describe('recordDeliveries (write flag on)', () => {+ beforeEach(() => {+ process.env.EMAIL_SUPPRESSION_WRITE_ENABLED = 'true'+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '5'+ })++ it('resets the counter after a successful delivery so a transient outage does not accumulate', async () => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'++ await svc.recordTransientBounces(team.id, [email], 'temp')+ await svc.recordTransientBounces(team.id, [email], 'temp')+ expect((await readRow(email))?.transient_bounce_count).toBe(2)++ // Newer delivery timestamp than the just-recorded bounces.+ const newerTimestamp = new Date(Date.now() + 60 * 1000).toISOString()+ await svc.recordDeliveries(team.id, [email], newerTimestamp)+ expect(await readRow(email)).toMatchObject({+ transient_bounce_count: 0,+ suppressed: false,+ })+ })++ it('does not reset the counter when the delivery is missing a timestamp (fail closed)', async () => {+ // Guards against a caller that forgets to pass the delivery timestamp — without one we+ // can't prove the delivery is newer than the last bounce, so we leave the counter alone.+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'++ await svc.recordTransientBounces(team.id, [email], 'temp')+ expect((await readRow(email))?.transient_bounce_count).toBe(1)++ await svc.recordDeliveries(team.id, [email])+ expect((await readRow(email))?.transient_bounce_count).toBe(1)+ })++ it('ignores a delivery older than the last bounce (out-of-order events)', async () => {+ // Guards against SES delivery + bounce notifications for different sends arriving in any+ // order — a late delivery for an older send must not erase a fresh bounce.+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'++ await svc.recordTransientBounces(team.id, [email], 'temp')+ const rowAfterBounce = await readRow(email)+ expect(rowAfterBounce?.transient_bounce_count).toBe(1)++ // Delivery timestamp is 1 hour before the bounce we just recorded.+ const olderTimestamp = new Date(Date.now() - 60 * 60 * 1000).toISOString()+ await svc.recordDeliveries(team.id, [email], olderTimestamp)++ expect((await readRow(email))?.transient_bounce_count).toBe(1)+ })++ it('resets the counter when the delivery is newer than the last bounce', async () => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'++ await svc.recordTransientBounces(team.id, [email], 'temp')+ expect((await readRow(email))?.transient_bounce_count).toBe(1)++ const futureTimestamp = new Date(Date.now() + 60 * 60 * 1000).toISOString()+ await svc.recordDeliveries(team.id, [email], futureTimestamp)++ expect((await readRow(email))?.transient_bounce_count).toBe(0)+ })+ })++ describe('recordHardBounces (write flag on)', () => {+ beforeEach(() => {+ process.env.EMAIL_SUPPRESSION_WRITE_ENABLED = 'true'+ // Threshold irrelevant — hard bounces suppress on the first hit.+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '5'+ })++ it('suppresses immediately with source=BOUNCE and the diagnostic captured', async () => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ await svc.recordHardBounces(team.id, [email], 'smtp; 550 5.1.1 user unknown')++ expect(await readRow(email)).toMatchObject({+ identifier: email,+ source: 'BOUNCE',+ suppressed: true,+ transient_bounce_count: 0,+ deleted: false,+ })+ })++ it('escalates an unsuppressed BOUNCE counter to suppressed when a hard bounce lands', async () => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ // Two soft bounces — below threshold, still unsuppressed.+ await svc.recordTransientBounces(team.id, [email], 'temp')+ await svc.recordTransientBounces(team.id, [email], 'temp')+ expect(await readRow(email)).toMatchObject({ suppressed: false, transient_bounce_count: 2 })++ await svc.recordHardBounces(team.id, [email], 'smtp; 550 5.1.1 user unknown')+ expect(await readRow(email)).toMatchObject({+ suppressed: true,+ // Counter is history; we keep it. Hard bounce is now the operative reason.+ transient_bounce_count: 2,+ })+ })++ it('does not override a MANUAL entry (user-managed rows are authoritative)', async () => {+ const email = '[email protected]'+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'MANUAL', 'Manually added', 0,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-manual'+ )++ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ await svc.recordHardBounces(team.id, [email], 'smtp; 550 5.1.1 user unknown')++ expect(await readRow(email)).toMatchObject({+ source: 'MANUAL',+ suppressed: true,+ })+ // The reason must not be overwritten to the auto-suppressed one.+ const detail = await hub.postgres.query<{ reason: string }>(+ PostgresUse.COMMON_READ,+ `SELECT reason FROM posthog_messagesuppression WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-reason'+ )+ expect(detail.rows[0].reason).toBe('Manually added')+ })+ })++ describe('cache invalidation', () => {+ beforeEach(() => {+ process.env.EMAIL_SUPPRESSION_WRITE_ENABLED = 'true'+ process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED = 'true'+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '5'+ })++ it("a write for one team does not evict another team's cached entries", async () => {+ // Guards against a regression from markForRefresh(touchedKeys) back to clear() — clear()+ // would drop every team's cache on any write, causing a thundering-herd read against+ // Postgres in busy multi-tenant pods.+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const otherTeamId = team.id + 100000+ const otherEmail = '[email protected]'+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'BOUNCE', 'test row', 5,+ true, NOW(), false, NOW(), NOW())`,+ [otherTeamId, otherEmail],+ 'test-insert-other-team'+ )++ // Warm both teams' caches.+ expect(await svc.isSuppressed(otherTeamId, otherEmail)).toBe(true)++ // Simulate a state change we should NOT observe via cache (would only be visible via a+ // full cache clear + refetch): delete the row directly.+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `DELETE FROM posthog_messagesuppression WHERE team_id = $1 AND identifier = $2`,+ [otherTeamId, otherEmail],+ 'test-delete-other-team'+ )++ // Trigger a write to `team.id` — must not invalidate other-team entries.+ await svc.recordTransientBounces(team.id, ['[email protected]'], 'temp')++ // Other team's entry is still served from cache (would be `false` if clear() ran).+ expect(await svc.isSuppressed(otherTeamId, otherEmail)).toBe(true)+ })+ })++ describe('isSuppressed', () => {+ it('returns false when enforcement is disabled, even if a suppressed row exists (dark-launch gate)', async () => {+ // enforce env deliberately left unset — the gate must short-circuit before hitting the DB.+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'BOUNCE', 'test row', 5,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-suppression'+ )++ expect(await svc.isSuppressed(team.id, email)).toBe(false)+ })++ describe('with enforcement enabled', () => {+ beforeEach(() => {+ process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED = 'true'+ })++ it.each([+ ['returns true for a suppressed row', true],+ ['returns false for an identifier that is not on the list', false],+ ])('%s', async (_label, expected) => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = expected ? '[email protected]' : '[email protected]'+ if (expected) {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'BOUNCE', 'test row', 5,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-suppression'+ )+ }++ expect(await svc.isSuppressed(team.id, email)).toBe(expected)+ })+ })+ })+})diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.tsnew file mode 100644index 000000000000..02b8da165f35--- /dev/null+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.ts@@ -0,0 +1,330 @@+import { Counter } from 'prom-client'++import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { LazyLoader } from '~/common/utils/lazy-loader'+import { logger } from '~/common/utils/logger'++const cdpEmailSuppressionTotal = new Counter({+ name: 'cdp_email_suppression_total',+ help: 'Email suppression-list outcomes. `suppressed_hit` = a send skipped because the recipient is on the list; `transient_bounce` = a soft-bounce counter increment; `hard_bounce` = an address suppressed immediately after a permanent bounce.',+ labelNames: ['result'],+})++const DIAGNOSTIC_MAX_LENGTH = 1000++const normalizeIdentifier = (email: string): string => email.trim().toLowerCase()++const toKey = (teamId: number, identifier: string): string => `${teamId}:${identifier}`++export type EmailSuppressionConfig = {+ // Populate the list on soft bounces / hard bounces / deliveries.+ writeEnabled: boolean+ // Skip sends to suppressed recipients (pre-send hook).+ enforceEnabled: boolean+ // Consecutive soft bounces before auto-suppression.+ transientBounceThreshold: number+}++// Test helper — production paths take config from `CdpConfig`; tests that still mutate process.env+// can call this to construct the same shape without duplicating the parse logic.+export function emailSuppressionConfigFromEnv(): EmailSuppressionConfig {+ const flagOn = (value: string | undefined): boolean => value === '1' || value?.toLowerCase() === 'true'+ const rawThreshold = process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD+ const parsedThreshold = rawThreshold ? parseInt(rawThreshold, 10) : NaN+ return {+ writeEnabled: flagOn(process.env.EMAIL_SUPPRESSION_WRITE_ENABLED),+ enforceEnabled: flagOn(process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED),+ transientBounceThreshold: Number.isFinite(parsedThreshold) && parsedThreshold > 0 ? parsedThreshold : 5,+ }+}++/**+ * Per-team email suppression list, backed by `posthog_messagesuppression`.+ *+ * Read path (pre-send): `isSuppressed` is consulted before every email send so we skip+ * addresses that can't (or shouldn't) receive mail. Cached via LazyLoader so a big batch to the+ * same recipients doesn't hammer Postgres.+ *+ * Write path (SES webhook): `recordTransientBounces` counts consecutive soft bounces per address+ * and flips it to suppressed once the count crosses the threshold; `recordDeliveries` resets the+ * count on any successful delivery so a one-off outage never accumulates into a suppression.+ * Manual entries (added via the API/UI) are never touched by the bounce/delivery bookkeeping.+ *+ * Cache invalidation window (v1):+ * The LazyLoader cache is per-process. `clear()` only fires on the Node process that performed+ * the write, so manual add/remove via the Django API (which never touches Node) and bounce writes+ * handled by a different worker won't invalidate other workers' caches immediately. Effect:+ * suppression state can be stale for up to LazyLoader's refresh window (~5 minutes) on other pods.+ * The pre-send check may allow a send to a just-suppressed address, or block a send to a+ * just-removed one, for that window. Acceptable for v1 given the low rate of state changes; a+ * follow-up should propagate invalidations via pubsub (see `IntegrationManagerService` for the+ * pattern) if the staleness becomes a support issue.+ */+export class EmailSuppressionService {+ private readonly threshold: number+ private readonly writeEnabled: boolean+ private readonly enforceEnabled: boolean+ private readonly lazyLoader: LazyLoader<boolean>++ constructor(+ private postgres: PostgresRouter,+ config: EmailSuppressionConfig+ ) {+ this.writeEnabled = config.writeEnabled+ this.enforceEnabled = config.enforceEnabled+ this.threshold = config.transientBounceThreshold+ this.lazyLoader = new LazyLoader({+ name: 'email_suppression',+ loader: async (keys) => await this.loadSuppressed(keys),+ })+ }++ public clear(): void {+ this.lazyLoader.clear()+ }++ /** Pre-send check: is this recipient currently on the team's suppression list? */+ public async isSuppressed(teamId: number, email: string): Promise<boolean> {+ // Enforcement is gated: when off, the list never blocks a send (writes may still populate it).+ if (!this.enforceEnabled) {+ return false+ }+ const identifier = normalizeIdentifier(email)+ if (!identifier) {+ return false+ }+ try {+ const suppressed = (await this.lazyLoader.get(toKey(teamId, identifier))) ?? false+ if (suppressed) {+ cdpEmailSuppressionTotal.inc({ result: 'suppressed_hit' })+ }+ return suppressed+ } catch (error) {+ // Fail open: a lookup error must never block a legitimate send.+ logger.error('[EmailSuppression] Failed to check suppression', { teamId, error })+ return false+ }+ }++ /**+ * Record one or more soft (Transient) bounces. Increments each address's consecutive-bounce+ * counter and auto-suppresses it in the same statement once it reaches the threshold. Manual+ * entries keep their suppressed state untouched.+ */+ public async recordTransientBounces(teamId: number, emails: string[], diagnostic?: string): Promise<void> {+ if (!this.writeEnabled) {+ return+ }+ const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))+ if (identifiers.length === 0) {+ return+ }++ const diag = diagnostic ? diagnostic.slice(0, DIAGNOSTIC_MAX_LENGTH) : null+ const reason = `Auto-suppressed after ${this.threshold} consecutive soft bounces`++ // Build a single multi-row upsert. Params: teamId, reason, threshold, diag, then one+ // identifier per row.+ const valueClauses: string[] = []+ const params: (number | string | null)[] = [teamId, reason, this.threshold, diag]+ identifiers.forEach((identifier, i) => {+ const p = params.length + 1 + i+ // gen_random_uuid() for the id, mirroring RecipientsManagerService.optOut. First bounce+ // starts the count at 1 and only suppresses immediately if the threshold is 1.+ valueClauses.push(+ `(gen_random_uuid(), $1, $${p}, 'BOUNCE', NULL, 1, NOW(), $4, (1 >= $3), CASE WHEN 1 >= $3 THEN NOW() ELSE NULL END, false, NOW(), NOW())`+ )+ })+ params.push(...identifiers)++ const query = `+ INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count, last_bounce_at,+ last_bounce_diagnostic, suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES ${valueClauses.join(', ')}+ ON CONFLICT (team_id, identifier) DO UPDATE SET+ transient_bounce_count = posthog_messagesuppression.transient_bounce_count + 1,+ last_bounce_at = NOW(),+ last_bounce_diagnostic = EXCLUDED.last_bounce_diagnostic,+ -- Never downgrade or re-key a manual entry; only auto (BOUNCE) rows can cross the threshold.+ suppressed = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed+ WHEN posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN true+ ELSE posthog_messagesuppression.suppressed END,+ suppressed_at = CASE+ WHEN posthog_messagesuppression.source <> 'MANUAL'+ AND posthog_messagesuppression.suppressed = false+ AND posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN NOW()+ ELSE posthog_messagesuppression.suppressed_at END,+ reason = CASE+ WHEN posthog_messagesuppression.source <> 'MANUAL'+ AND posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN $2+ ELSE posthog_messagesuppression.reason END,+ -- A provably-undeliverable address coming back over threshold un-deletes itself.+ deleted = CASE+ WHEN posthog_messagesuppression.source <> 'MANUAL'+ AND posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN false+ ELSE posthog_messagesuppression.deleted END,+ updated_at = NOW()+ `++ try {+ await this.postgres.query(PostgresUse.COMMON_WRITE, query, params, 'recordTransientBounces')+ cdpEmailSuppressionTotal.inc({ result: 'transient_bounce' }, identifiers.length)+ // Only invalidate the keys we touched — cross-team entries stay warm.+ this.lazyLoader.markForRefresh(identifiers.map((identifier) => toKey(teamId, identifier)))+ } catch (error) {+ logger.error('[EmailSuppression] Failed to record transient bounces', { teamId, error })+ }+ }++ /**+ * Record one or more hard (Permanent) bounces. Suppresses each address immediately — no+ * threshold, no counter — because a permanent bounce is definitive. Manual entries are never+ * touched. If a row already exists as an unsuppressed BOUNCE counter, this escalates it.+ */+ public async recordHardBounces(teamId: number, emails: string[], diagnostic?: string): Promise<void> {+ if (!this.writeEnabled) {+ return+ }+ const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))+ if (identifiers.length === 0) {+ return+ }++ const diag = diagnostic ? diagnostic.slice(0, DIAGNOSTIC_MAX_LENGTH) : null+ const reason = 'Auto-suppressed after a hard bounce'++ // Params: teamId, reason, diag, then one identifier per row.+ const valueClauses: string[] = []+ const params: (number | string | null)[] = [teamId, reason, diag]+ identifiers.forEach((identifier, i) => {+ const p = params.length + 1 + i+ valueClauses.push(+ `(gen_random_uuid(), $1, $${p}, 'BOUNCE', $2, 0, NOW(), $3, true, NOW(), false, NOW(), NOW())`+ )+ })+ params.push(...identifiers)++ const query = `+ INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count, last_bounce_at,+ last_bounce_diagnostic, suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES ${valueClauses.join(', ')}+ ON CONFLICT (team_id, identifier) DO UPDATE SET+ last_bounce_at = NOW(),+ last_bounce_diagnostic = EXCLUDED.last_bounce_diagnostic,+ -- Manual entries are authoritative; never override them.+ suppressed = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed+ ELSE true END,+ suppressed_at = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed_at+ WHEN posthog_messagesuppression.suppressed = false THEN NOW()+ ELSE posthog_messagesuppression.suppressed_at END,+ reason = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.reason+ ELSE EXCLUDED.reason END,+ -- A provably-undeliverable address coming back un-deletes itself.+ deleted = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.deleted+ ELSE false END,+ updated_at = NOW()+ `++ try {+ await this.postgres.query(PostgresUse.COMMON_WRITE, query, params, 'recordHardBounces')+ cdpEmailSuppressionTotal.inc({ result: 'hard_bounce' }, identifiers.length)+ // Only invalidate the keys we touched — cross-team entries stay warm.+ this.lazyLoader.markForRefresh(identifiers.map((identifier) => toKey(teamId, identifier)))+ } catch (error) {+ logger.error('[EmailSuppression] Failed to record hard bounces', { teamId, error })+ }+ }++ /**+ * Record successful deliveries. Resets the consecutive-bounce counter for auto (non-manual)+ * entries that haven't yet been suppressed, so a transient outage never accumulates.+ *+ * `deliveryTimestamp` guards against out-of-order events: SES delivery and bounce notifications+ * for different sends can arrive in any order, and a late delivery for an older send must not+ * erase a fresh bounce for a newer send. Reset only when the delivery is newer than the last+ * recorded bounce.+ */+ public async recordDeliveries(teamId: number, emails: string[], deliveryTimestamp?: string): Promise<void> {+ if (!this.writeEnabled) {+ return+ }+ const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))+ if (identifiers.length === 0) {+ return+ }++ // Fail closed on a missing delivery timestamp: without one we can't prove the delivery is+ // newer than the last bounce, so leave the counter alone rather than risk erasing a fresh+ // bounce. In practice the SES Delivery schema requires a timestamp, so this branch only+ // guards against a caller that forgets to pass it.+ const query = `+ UPDATE posthog_messagesuppression+ SET transient_bounce_count = 0, updated_at = NOW()+ WHERE team_id = $1+ AND identifier = ANY($2)+ AND source <> 'MANUAL'+ AND suppressed = false+ AND transient_bounce_count > 0+ AND (last_bounce_at IS NULL OR ($3::timestamptz IS NOT NULL AND last_bounce_at < $3::timestamptz))+ `+ try {+ await this.postgres.query(+ PostgresUse.COMMON_WRITE,+ query,+ [teamId, identifiers, deliveryTimestamp ?? null],+ 'resetBounceCounts'+ )+ } catch (error) {+ logger.error('[EmailSuppression] Failed to reset bounce counts on delivery', { teamId, error })+ }+ }++ private async loadSuppressed(keys: string[]): Promise<Record<string, boolean>> {+ // keys are `${teamId}:${identifier}`. Identifiers may contain ':' only in exotic cases; the+ // stored identifier is an email so split on the first ':' only.+ const parsed = keys.map((key) => {+ const idx = key.indexOf(':')+ return { key, teamId: parseInt(key.slice(0, idx), 10), identifier: key.slice(idx + 1) }+ })++ // Group by team_id so we run one indexed `identifier = ANY(...)` scan per team instead of an+ // OR-chain of paired lookups. Same UNIQUE (team_id, identifier) index, cheaper plan and+ // prepared-statement reuse — matters when the LazyLoader coalesces many keys in a batch.+ // In practice most batches are single-team (one workflow, one team), so this is almost+ // always a single query regardless of batch size.+ const byTeam = new Map<number, string[]>()+ for (const p of parsed) {+ const list = byTeam.get(p.teamId) ?? []+ list.push(p.identifier)+ byTeam.set(p.teamId, list)+ }++ const suppressedKeys = new Set<string>()+ for (const [teamId, identifiers] of byTeam) {+ const result = await this.postgres.query<{ identifier: string }>(+ PostgresUse.COMMON_READ,+ `SELECT identifier+ FROM posthog_messagesuppression+ WHERE team_id = $1+ AND identifier = ANY($2)+ AND suppressed = true+ AND deleted = false`,+ [teamId, identifiers],+ 'loadSuppressed'+ )+ for (const row of result.rows) {+ suppressedKeys.add(toKey(teamId, row.identifier))+ }+ }++ // Default every requested key to false so the LazyLoader caches negatives too.+ return Object.fromEntries(parsed.map((p) => [p.key, suppressedKeys.has(p.key)]))+ }+}diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 279347c5ffb1..c6f65cece14a 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -15,6 +15,7 @@ import { setupExpressApp } from '~/common/api/router'import { defaultConfig } from '~/common/config/config'import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'import * as envUtils from '~/common/utils/env-utils'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { waitForExpect } from '~/tests/helpers/expectations'@@ -397,6 +398,176 @@ describe('EmailTrackingService', () => {})})+ describe('SES webhook writes to the suppression list', () => {+ // EmailSuppressionService reads its flags from `hub.EMAIL_SUPPRESSION_*` (via CdpConfig),+ // not directly from process.env. The outer beforeEach recreates `hub` per test, so overriding+ // here doesn't leak across tests — no restore in afterEach needed. Threshold=1 keeps the test+ // to a single POST — the counter arithmetic is not what this test is guarding, the write-path+ // wiring is.+ let api: CdpApi+ let app: express.Application+ let server: Server+ let verifySignatureSpy: jest.SpyInstance++ beforeEach(() => {+ hub.EMAIL_SUPPRESSION_WRITE_ENABLED = true+ hub.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = 1++ api = new CdpApi(hub, createCdpConsumerDeps(hub), {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })+ app = setupExpressApp()+ app.use('/', api.router())+ server = app.listen(0, () => {})++ verifySignatureSpy = jest+ .spyOn(SesWebhookHandler.prototype as any, 'verifySnsSignature')+ .mockResolvedValue(true)+ })++ afterEach(() => {+ server.close()+ verifySignatureSpy.mockRestore()+ })++ const postTransientBounce = async (functionId: string, emailAddress: string): Promise<supertest.Response> => {+ const trackingCode = signer.generate({ functionId, id: 'invocation-id', teamId: team.id })+ const sesRecord = {+ eventType: 'Bounce',+ mail: {+ timestamp: '2024-01-01T00:00:00.000Z',+ source: '[email protected]',+ messageId: 'ses-message-id',+ destination: [emailAddress],+ headers: [{ name: TRACKING_CODE_HEADER_NAME, value: trackingCode }],+ },+ bounce: {+ bounceType: 'Transient',+ bouncedRecipients: [+ { emailAddress, diagnosticCode: 'smtp; 421 4.2.1 mailbox temporarily unavailable' },+ ],+ timestamp: '2024-01-01T00:00:00.000Z',+ },+ }+ const envelope = {+ Type: 'Notification',+ MessageId: 'sns-message-id',+ TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-events',+ Message: JSON.stringify(sesRecord),+ Timestamp: '2024-01-01T00:00:00.000Z',+ SignatureVersion: '1',+ Signature: 'stubbed',+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ }+ return await supertest(app)+ .post('/public/m/ses_webhook')+ .set('Content-Type', 'text/plain')+ .send(JSON.stringify(envelope))+ }++ const postPermanentBounce = async (functionId: string, emailAddress: string): Promise<supertest.Response> => {+ const trackingCode = signer.generate({ functionId, id: 'invocation-id', teamId: team.id })+ const sesRecord = {+ eventType: 'Bounce',+ mail: {+ timestamp: '2024-01-01T00:00:00.000Z',+ source: '[email protected]',+ messageId: 'ses-message-id',+ destination: [emailAddress],+ headers: [{ name: TRACKING_CODE_HEADER_NAME, value: trackingCode }],+ },+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [{ emailAddress, diagnosticCode: 'smtp; 550 5.1.1 user unknown' }],+ timestamp: '2024-01-01T00:00:00.000Z',+ },+ }+ const envelope = {+ Type: 'Notification',+ MessageId: 'sns-message-id',+ TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-events',+ Message: JSON.stringify(sesRecord),+ Timestamp: '2024-01-01T00:00:00.000Z',+ SignatureVersion: '1',+ Signature: 'stubbed',+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ }+ return await supertest(app)+ .post('/public/m/ses_webhook')+ .set('Content-Type', 'text/plain')+ .send(JSON.stringify(envelope))+ }++ it('inserts a suppression row and marks it suppressed after a Transient bounce webhook', async () => {+ const hogFlow = await insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())+ const email = '[email protected]'++ const res = await postTransientBounce(hogFlow.id, email)+ expect(res.status).toBe(200)++ // handleSesWebhook awaits the suppression write inline, so the row is present+ // as soon as the 200 returns — no waitForExpect needed.+ const result = await hub.postgres.query<{+ identifier: string+ source: string+ suppressed: boolean+ transient_bounce_count: number+ deleted: boolean+ }>(+ PostgresUse.COMMON_READ,+ `SELECT identifier, source, suppressed, transient_bounce_count, deleted+ FROM posthog_messagesuppression+ WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-suppression'+ )+ expect(result.rows).toEqual([+ {+ identifier: email,+ source: 'BOUNCE',+ suppressed: true,+ transient_bounce_count: 1,+ deleted: false,+ },+ ])+ })++ it('inserts a suppressed row for a Permanent bounce webhook (dual-write with the opt-out path)', async () => {+ const hogFlow = await insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())+ const email = '[email protected]'++ const res = await postPermanentBounce(hogFlow.id, email)+ expect(res.status).toBe(200)++ const result = await hub.postgres.query<{+ identifier: string+ source: string+ suppressed: boolean+ transient_bounce_count: number+ last_bounce_diagnostic: string | null+ deleted: boolean+ }>(+ PostgresUse.COMMON_READ,+ `SELECT identifier, source, suppressed, transient_bounce_count, last_bounce_diagnostic, deleted+ FROM posthog_messagesuppression+ WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-hard-bounce-suppression'+ )+ expect(result.rows).toEqual([+ {+ identifier: email,+ source: 'BOUNCE',+ suppressed: true,+ transient_bounce_count: 0,+ last_bounce_diagnostic: 'smtp; 550 5.1.1 user unknown',+ deleted: false,+ },+ ])+ })+ })+describe('resolveEmailEngagementDistinctId', () => {const buildInvocation = (globals: Partial<NonNullable<CyclotronJobInvocationHogFunction['state']['globals']>>diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 74fb6f950c42..8923d85b7bdd 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -15,6 +15,7 @@ import { HogFunctionManagerService } from '../managers/hog-function-manager.servimport { RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { HogFunctionMonitoringService } from '../monitoring/hog-function-monitoring.service'+import { EmailSuppressionService } from './email-suppression.service'import { SesWebhookHandler } from './helpers/ses'import { EmailTrackingCodeSigner, trackingCodeFormatCounter } from './helpers/tracking-code'@@ -143,9 +144,11 @@ export class EmailTrackingService {private capturedEventsService: CapturedEventsService,private teamWorkflowsConfigService: TeamWorkflowsConfigService,private recipientsManager: RecipientsManagerService,- private trackingCodeSigner: EmailTrackingCodeSigner+ private trackingCodeSigner: EmailTrackingCodeSigner,+ private emailSuppressionService: EmailSuppressionService) {- this.sesWebhookHandler = new SesWebhookHandler(this.trackingCodeSigner)+ const allowedTopicArns = (process.env.SES_ALLOWED_SNS_TOPIC_ARNS ?? '').split(',')+ this.sesWebhookHandler = new SesWebhookHandler(this.trackingCodeSigner, allowedTopicArns)}public async trackMetric({@@ -308,7 +311,16 @@ export class EmailTrackingService {}try {- const { status, body, metrics, logEntries, optOutRecipients } = await this.sesWebhookHandler.handleWebhook({+ const {+ status,+ body,+ metrics,+ logEntries,+ optOutRecipients,+ transientBounceRecipients,+ hardBounceRecipients,+ deliveredRecipients,+ } = await this.sesWebhookHandler.handleWebhook({body: parseJSON(req.body),headers: req.headers,verifySignature: true,@@ -376,6 +388,41 @@ export class EmailTrackingService {}}+ // Feed soft bounces and successful deliveries into the suppression list. Wrapped so a+ // failure here never affects the webhook's 200 response to SNS. Deliveries are processed+ // first so a delivery + bounce in the same batch nets out conservatively (count resets,+ // then the fresh bounce re-counts from a clean slate).+ try {+ for (const { teamId, emailAddresses, timestamp } of deliveredRecipients || []) {+ const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN+ if (parsedTeamId && !isNaN(parsedTeamId)) {+ await this.emailSuppressionService.recordDeliveries(parsedTeamId, emailAddresses, timestamp)+ }+ }+ for (const { teamId, emailAddresses, diagnostic } of transientBounceRecipients || []) {+ const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN+ if (parsedTeamId && !isNaN(parsedTeamId)) {+ await this.emailSuppressionService.recordTransientBounces(+ parsedTeamId,+ emailAddresses,+ diagnostic+ )+ }+ }+ // Dual-write: hard bounces still go through the opt-out path above; here we also+ // mirror them into the suppression list so the unified deliverability view+ // includes them ahead of phase 2 (retiring the opt-out write).+ for (const { teamId, emailAddresses, diagnostic } of hardBounceRecipients || []) {+ const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN+ if (parsedTeamId && !isNaN(parsedTeamId)) {+ await this.emailSuppressionService.recordHardBounces(parsedTeamId, emailAddresses, diagnostic)+ }+ }+ } catch (error) {+ logger.error('[EmailTrackingService] Failed to update suppression list', { error })+ emailTrackingErrorsCounter.inc({ error_type: 'suppression_update_failed', source: 'ses' })+ }+return { status, message: body as string }} catch (error) {emailTrackingErrorsCounter.inc({ error_type: error.name || 'unknown' })diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex cb9177fdd8b0..d6c93349be15 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -11,6 +11,7 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, Team } from '../../../types'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'+import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'import { MailDevAPI } from './helpers/maildev'import { EmailTrackingCodeSigner } from './helpers/tracking-code'@@ -94,7 +95,8 @@ describe('EmailService', () => {new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,- new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()))mockFetch.mockClear()})@@ -109,7 +111,8 @@ describe('EmailService', () => {new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,- new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()))expect(serviceWithoutSES.sesV2Client).toBeNull()@@ -459,6 +462,36 @@ describe('EmailService', () => {expect(testSend.metrics).toEqual([])})+ describe('suppression enforcement at send time', () => {+ // Guards the "email hog function destination bypasses shouldSkipAction, so suppression+ // isn't enforced on that path" gap. executeSendEmail is the single choke point every+ // outbound send goes through — the suppression check has to live here so it can't be+ // skipped just by choosing a different upstream code path.+ it('does not call SES when the recipient is on the suppression list', async () => {+ const isSuppressedSpy = jest+ .spyOn(service['emailSuppressionService'], 'isSuppressed')+ .mockResolvedValue(true)+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(isSuppressedSpy).toHaveBeenCalled()+ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.metrics.map((m) => m.metric_name)).toContain('email_suppressed')+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('email_sent')+ })++ it('calls SES when the recipient is not suppressed', async () => {+ jest.spyOn(service['emailSuppressionService'], 'isSuppressed').mockResolvedValue(false)+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).toHaveBeenCalledTimes(1)+ expect(result.metrics.map((m) => m.metric_name)).toContain('email_sent')+ })+ })+it('should include cc addresses in SES destination', async () => {sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })invocation.queueParameters = createEmailParams({diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 7bf0937571d3..dc3fcfb513bd 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -16,6 +16,7 @@ import { createInvocationResult } from '~/cdp/utils/invocation-utils'import { IntegrationManagerService } from '../managers/integration-manager.service'import { RecipientManagerRecipient } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'+import { EmailSuppressionService } from './email-suppression.service'import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'import { maybeAddPreheaderToEmail } from './helpers/preheader'@@ -92,6 +93,23 @@ export function sanitizeEmailSubject(subject: string): string {.trim()}+// Splits a comma-separated address list and extracts the bare email from any RFC-822+// `"Name" <email@x>` entries. Used by the pre-send suppression check to normalize cc/bcc entries+// before matching against the suppression list (which stores bare, lower-cased addresses).+export function extractEmailsFromAddressList(value: string | undefined): string[] {+ if (typeof value !== 'string' || value.trim().length === 0) {+ return []+ }+ return value+ .split(',')+ .map((raw) => {+ const trimmed = raw.trim()+ const bracketed = trimmed.match(/<([^>]+)>/)+ return (bracketed ? bracketed[1] : trimmed).trim()+ })+ .filter((addr) => addr.length > 0)+}+export function parseAddressList(value?: string): string[] | undefined {if (!value || !value.trim()) {return undefined@@ -115,6 +133,7 @@ export class EmailService {encryptionSaltKeys: string,siteUrl: string,private trackingCodeSigner: EmailTrackingCodeSigner,+ private emailSuppressionService: EmailSuppressionService,private messageAssetsService?: MessageAssetsService) {this.sesV2Client = this.sesConfig.sesRegion@@ -167,6 +186,27 @@ export class EmailService {const from = this.resolveFromSender(integration)+ // Single choke point for the suppression check — every send path lands here regardless+ // of whether the invocation came from a workflow action or an email destination hog+ // function. Checking here means callers can't bypass it by taking a different upstream+ // route. Covers `to`, `cc`, and `bcc`; a suppressed address anywhere blocks the send.+ const skipReason = await this.buildSuppressionSkipReason(invocation.teamId, params)+ if (skipReason) {+ addLog('info', skipReason)+ if (!isTest) {+ result.metrics.push({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? invocation.functionId,+ instance_id: invocation.state.actionId || invocation.id,+ metric_kind: 'email',+ metric_name: 'email_suppressed',+ count: 1,+ })+ }+ result.invocation.state.vmState?.stack.push({ success: false })+ return result+ }+switch (integration.config.provider ?? 'ses') {case 'maildev':await this.sendEmailWithMaildev(result, params, from, isTest)@@ -258,6 +298,38 @@ export class EmailService {return result}+ // Returns a human-readable log string when any destination address is suppressed for the team,+ // or null when the send should proceed. Scans to + cc + bcc — SES delivers to every list, so a+ // suppressed address anywhere blocks the whole send. `cc` and `bcc` can be comma-separated+ // lists with RFC-822 `"Name" <email>` entries; we strip the angle-bracketed address before+ // matching against the normalized suppression identifier.+ private async buildSuppressionSkipReason(+ teamId: number,+ params: CyclotronInvocationQueueParametersEmailType+ ): Promise<string | null> {+ const recipients: string[] = []+ if (params.to?.email && params.to.email.trim()) {+ recipients.push(params.to.email.trim())+ }+ recipients.push(...extractEmailsFromAddressList(params.cc))+ recipients.push(...extractEmailsFromAddressList(params.bcc))+ if (recipients.length === 0) {+ return null+ }++ const results = await Promise.all(+ recipients.map(async (email) => ({+ email,+ suppressed: await this.emailSuppressionService.isSuppressed(teamId, email),+ }))+ )+ const suppressed = results.filter((r) => r.suppressed).map((r) => r.email)+ if (suppressed.length === 0) {+ return null+ }+ return `Skipping send: recipient(s) on the suppression list — ${suppressed.join(', ')}`+ }+private resolveFromSender(integration: IntegrationType): { email: string; name: string } {if (!integration.config.verified) {throw new Error('The selected email integration domain is not verified')diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex 2c0c2ad7b5c6..4497a09fb416 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -243,10 +243,48 @@ describe('SesWebhookHandler', () => {},]const result = await handler.handleWebhook({ body, headers: {} })- // No metric or log entry recorded for the test send, but the hard bounce still triggers an opt-out.+ // No metric or log entry recorded for the test send, but the hard bounce still triggers an opt-out+ // (pre-existing behavior, kept unchanged for backward compat).expect(result.metrics).toEqual([])expect(result.logEntries).toEqual([])expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])+ // Suppression writes are NOT populated for test sends — editor "Run test" traffic shouldn't be+ // able to suppress a production address just by targeting a bad recipient.+ expect(result.hardBounceRecipients).toEqual([])+ })++ it.each([+ [+ 'Transient bounce',+ {+ eventType: 'Bounce',+ bounce: {+ bounceType: 'Transient',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'temp' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ },+ 'transientBounceRecipients' as const,+ ],+ [+ 'Delivery',+ {+ eventType: 'Delivery',+ delivery: { timestamp: '2025-10-03T12:04:00Z', recipients: ['[email protected]'] },+ },+ 'deliveredRecipients' as const,+ ],+ ])('does not populate %s suppression writes for test sends', async (_label, eventFields, arrayKey) => {+ // Same guarantee as the permanent-bounce test above but for the counter-driving events:+ // a "Run test" from the editor must not push into the suppression counter (transient) or+ // reset it (delivery), which could otherwise perturb production suppression state.+ const testMail = {+ ...baseMail,+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation, true) }],+ tags: { ph_id: [signer.generateShort(baseInvocation)] },+ }+ const result = await handler.handleWebhook({ body: [{ mail: testMail, ...eventFields }], headers: {} })+ expect(result[arrayKey]).toEqual([])})it('parses a raw Delivery event', async () => {@@ -292,6 +330,10 @@ describe('SesWebhookHandler', () => {expect(result.metrics?.[0].metricName).toBe('email_bounced')expect(result.metrics?.[0].distinctId).toBe('user-123')expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])+ // Dual-write: permanent bounces also surface for the suppression list with the diagnostic.+ expect(result.hardBounceRecipients).toEqual([+ { teamId: '1', emailAddresses: ['[email protected]'], diagnostic: 'bad' },+ ])})it('does not return opt-out recipients for transient bounces', async () => {@@ -314,6 +356,29 @@ describe('SesWebhookHandler', () => {expect(result.metrics?.[0].metricName).toBe('email_bounced')expect(result.metrics?.[0].distinctId).toBe('user-123')expect(result.optOutRecipients).toEqual([])+ // Soft bounces are surfaced separately so the suppression list can count them.+ expect(result.transientBounceRecipients).toEqual([+ { teamId: '1', emailAddresses: ['[email protected]'], diagnostic: 'temp' },+ ])+ })++ it('surfaces delivered recipients so the suppression counter can reset', async () => {+ const body = [+ {+ eventType: 'Delivery',+ mail: baseMail,+ delivery: {+ timestamp: '2025-10-03T12:04:00Z',+ recipients: ['[email protected]'],+ },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ expect(result.status).toBe(200)+ expect(result.deliveredRecipients).toEqual([+ { teamId: '1', emailAddresses: ['[email protected]'], timestamp: '2025-10-03T12:04:00Z' },+ ])+ expect(result.transientBounceRecipients).toEqual([])})it('rejects raw (non-SNS) deliveries when signature verification is required', async () => {@@ -672,4 +737,126 @@ describe('SesWebhookHandler', () => {expect(result.logEntries).toEqual([])})})++ describe('security: TopicArn allowlist + signed-code gate', () => {+ // Two-layer hardening: the TopicArn allowlist restricts which SNS topics we accept events from,+ // and state-changing writes require a signed tracking code (unsigned carriers only contribute+ // to engagement metrics/log entries).+ const buildEnvelope = (+ topicArn: string,+ innerRecord: object,+ envelopeType: 'Notification' | 'SubscriptionConfirmation' = 'Notification'+ ): Record<string, any> => ({+ Type: envelopeType,+ MessageId: 'sns-msg-1',+ TopicArn: topicArn,+ Message: envelopeType === 'Notification' ? JSON.stringify(innerRecord) : JSON.stringify({}),+ Timestamp: '2025-10-03T12:10:00Z',+ SignatureVersion: '1',+ Signature: 'stubbed',+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ })++ it('rejects a Notification whose TopicArn is not on the allowlist', async () => {+ const restricted = new SesWebhookHandler(signer, ['arn:aws:sns:us-east-1:123456789012:allowed-topic'])+ const envelope = buildEnvelope('arn:aws:sns:us-east-1:999999999999:other-topic', {+ eventType: 'Bounce',+ mail: baseMail,+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'bad' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ })+ const result = await restricted.handleWebhook({ body: envelope, headers: {}, verifySignature: false })+ expect(result.status).toBe(403)+ expect(result.optOutRecipients).toBeUndefined()+ expect(result.hardBounceRecipients).toBeUndefined()+ })++ it('accepts a Notification whose TopicArn matches the allowlist', async () => {+ const restricted = new SesWebhookHandler(signer, ['arn:aws:sns:us-east-1:123456789012:allowed-topic'])+ const envelope = buildEnvelope('arn:aws:sns:us-east-1:123456789012:allowed-topic', {+ eventType: 'Bounce',+ mail: baseMail,+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'bad' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ })+ const result = await restricted.handleWebhook({ body: envelope, headers: {}, verifySignature: false })+ expect(result.status).toBe(200)+ expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])+ })++ it('empty allowlist means no restriction (dev/test backward compat)', async () => {+ // The default `handler` in the outer beforeEach was constructed without an allowlist.+ const envelope = buildEnvelope('arn:aws:sns:us-east-1:999999999999:some-topic', {+ eventType: 'Bounce',+ mail: baseMail,+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'bad' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ })+ const result = await handler.handleWebhook({ body: envelope, headers: {}, verifySignature: false })+ expect(result.status).toBe(200)+ })++ it('rejects a SubscriptionConfirmation from a disallowed topic', async () => {+ const restricted = new SesWebhookHandler(signer, ['arn:aws:sns:us-east-1:123456789012:allowed-topic'])+ const envelope = buildEnvelope(+ 'arn:aws:sns:us-east-1:999999999999:other-topic',+ {},+ 'SubscriptionConfirmation'+ )+ const result = await restricted.handleWebhook({ body: envelope, headers: {}, verifySignature: false })+ expect(result.status).toBe(403)+ })++ it('does not populate suppression writes for an unsigned tracking code', async () => {+ // Only signed tracking codes drive state changes. Unsigned codes still contribute to+ // metrics/log entries (engagement signal) but not to suppression / opt-out / delivery resets.+ const unsignedMail = {+ ...baseMail,+ headers: undefined,+ tags: { ph_id: [signer.generateShort(baseInvocation)] },+ }+ const body = [+ {+ eventType: 'Bounce',+ mail: unsignedMail,+ bounce: {+ bounceType: 'Transient',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'temp' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ },+ {+ eventType: 'Bounce',+ mail: unsignedMail,+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'bad' }],+ timestamp: '2025-10-03T12:04:00Z',+ },+ },+ {+ eventType: 'Delivery',+ mail: unsignedMail,+ delivery: { timestamp: '2025-10-03T12:05:00Z', recipients: ['[email protected]'] },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ expect(result.status).toBe(200)+ expect(result.transientBounceRecipients).toEqual([])+ expect(result.hardBounceRecipients).toEqual([])+ expect(result.deliveredRecipients).toEqual([])+ expect(result.optOutRecipients).toEqual([])+ // Metrics are unaffected — engagement signal is still emitted for the parsed events.+ expect(result.metrics?.length).toBeGreaterThan(0)+ })+ })})diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 7822f2f9d1aa..fc54a2328ee2 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts@@ -234,8 +234,23 @@ export const formatSesEventLogs = (rec: SesEventRecord): SesEventLogLine[] => {export class SesWebhookHandler {certCache: Record<string, Promise<string> | undefined> = {}+ private allowedTopicArns: Set<string>++ constructor(+ private trackingCodeSigner: EmailTrackingCodeSigner,+ // Empty set means no restriction (dev/test); prod is expected to configure the workflow SES+ // topic ARN.+ allowedTopicArns: string[] = []+ ) {+ this.allowedTopicArns = new Set(allowedTopicArns.map((arn) => arn.trim()).filter(Boolean))+ }- constructor(private trackingCodeSigner: EmailTrackingCodeSigner) {}+ private isTopicAllowed(topicArn: string | undefined): boolean {+ if (this.allowedTopicArns.size === 0) {+ return true+ }+ return typeof topicArn === 'string' && this.allowedTopicArns.has(topicArn)+ }private async fetchText(url: string): Promise<string> {const response = await fetch(url)@@ -411,6 +426,27 @@ export class SesWebhookHandler {teamId?: stringemailAddresses: string[]}[]+ // Soft (Transient) bounces — fed into the suppression list's consecutive-bounce counter.+ transientBounceRecipients?: {+ teamId?: string+ emailAddresses: string[]+ diagnostic?: string+ }[]+ // Hard (Permanent) bounces — mirrored into the suppression list alongside the existing+ // opt-out write, during the dual-write window before the opt-out path is retired.+ hardBounceRecipients?: {+ teamId?: string+ emailAddresses: string[]+ diagnostic?: string+ }[]+ // Successful deliveries — reset the suppression counter so transient outages don't accumulate.+ // Timestamp is threaded through so the reset ignores an out-of-order delivery from an older send+ // arriving after a newer bounce.+ deliveredRecipients?: {+ teamId?: string+ emailAddresses: string[]+ timestamp?: string+ }[]}> {logger.info('[SesWebhookHandler] handleWebhook', { body: opts.body, headers: opts.headers })const parsed = this.parseIncomingBody(opts.body)@@ -431,6 +467,16 @@ export class SesWebhookHandler {}}+ // Restrict accepted SNS envelopes (Notification, SubscriptionConfirmation, UnsubscribeConfirmation)+ // to the configured TopicArn allowlist. SNS signature verification proves the message came from+ // AWS, but not from a specific topic — this narrows accepted sources to the workflow SES topic.+ if ('envelope' in parsed && !this.isTopicAllowed(parsed.envelope.TopicArn)) {+ logger.warn('[SesWebhookHandler] Rejecting event from disallowed TopicArn', {+ topicArn: parsed.envelope.TopicArn,+ })+ return { status: 403, body: { error: 'SNS TopicArn not allowed' } }+ }+// Handle confirmation flowif (parsed.mode === 'sns' && 'envelope' in parsed && parsed.envelope?.Type === 'SubscriptionConfirmation') {logger.info('[SesWebhookHandler] confirming subscription', { envelope: parsed.envelope })@@ -481,6 +527,21 @@ export class SesWebhookHandler {teamId?: stringemailAddresses: string[]}[] = []+ const transientBounceRecipients: {+ teamId?: string+ emailAddresses: string[]+ diagnostic?: string+ }[] = []+ const hardBounceRecipients: {+ teamId?: string+ emailAddresses: string[]+ diagnostic?: string+ }[] = []+ const deliveredRecipients: {+ teamId?: string+ emailAddresses: string[]+ timestamp?: string+ }[] = []for (const rec of records) {logger.info('[SesWebhookHandler] processing record', { rec })@@ -560,13 +621,57 @@ export class SesWebhookHandler {})}- // Opt out recipients on permanent bounces- if (teamId && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Permanent') {+ // State-changing writes (opt-out, suppression, delivery counter reset) require a signed+ // tracking code. The signed header carries the HMAC we mint on send; the unsigned SES-tag+ // carrier is only used for engagement metrics/log entries above.+ const codeIsTrusted = parsedCode?.format === 'signed'++ // Suppression writes (below) skip test sends — editor "Run test" traffic must not be+ // able to perturb production suppression state by targeting a bad recipient. The+ // pre-existing opt-out push stays ungated for backward compat.+ const suppressionAllowed = teamId && codeIsTrusted && !isTest++ // Opt out recipients on permanent bounces. Dual-write: also mirror into the suppression+ // list with the SMTP diagnostic so a unified deliverability view exists before the+ // opt-out path is retired (see phase 2 of the suppression rollout).+ if (teamId && codeIsTrusted && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Permanent') {const emails = rec.bounce.bouncedRecipients.map((r) => r.emailAddress)+ const diagnostic = rec.bounce.bouncedRecipients.find((r) => r.diagnosticCode)?.diagnosticCodeoptOutRecipients.push({ teamId, emailAddresses: emails })+ if (!isTest) {+ hardBounceRecipients.push({ teamId, emailAddresses: emails, diagnostic })+ }+ }++ // Count soft (Transient) bounces toward suppression. These are recipient-side failures+ // (server unreachable, mailbox full, greylisting); one is harmless but a persistent run+ // of them means the address can't receive mail.+ if (suppressionAllowed && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Transient') {+ const emails = rec.bounce.bouncedRecipients.map((r) => r.emailAddress)+ const diagnostic = rec.bounce.bouncedRecipients.find((r) => r.diagnosticCode)?.diagnosticCode+ transientBounceRecipients.push({ teamId, emailAddresses: emails, diagnostic })+ }++ // Successful delivery resets an address's soft-bounce counter — but only if newer than the+ // last-recorded bounce (checked at the SQL layer), so an out-of-order delivery from an+ // older send can't erase a fresh bounce.+ if (suppressionAllowed && rec.eventType === 'Delivery') {+ const emails = rec.delivery.recipients ?? rec.mail.destination ?? []+ if (emails.length > 0) {+ deliveredRecipients.push({ teamId, emailAddresses: emails, timestamp: rec.delivery.timestamp })+ }}}- return { status: 200, body: { ok: true }, metrics, logEntries, optOutRecipients }+ return {+ status: 200,+ body: { ok: true },+ metrics,+ logEntries,+ optOutRecipients,+ transientBounceRecipients,+ hardBounceRecipients,+ deliveredRecipients,+ }}}diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.tsindex e9b61c00938f..753f80b9e38f 100644--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts@@ -3,12 +3,14 @@ import { createExampleInvocation } from '~/cdp/_tests/fixtures'import { HogFlowAction } from '~/cdp/schema/hogflow'import { CyclotronJobInvocationHogFunction } from '~/cdp/types'import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'import { logger } from '~/common/utils/logger'import { UUIDT } from '~/common/utils/utils'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, Team } from '~/types'import { RecipientsManagerService } from '../managers/recipients-manager.service'+import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'import { RecipientPreferencesService } from './recipient-preferences.service'import { RecipientTokensService } from './recipient-tokens.service'@@ -19,6 +21,7 @@ describe('RecipientPreferencesService', () => {let team: Teamlet service: RecipientPreferencesServicelet mockRecipientsManager: RecipientsManagerService+ let mockEmailSuppressionService: EmailSuppressionServicelet mockRecipientsManagerGet: jest.SpyInstancelet mockRecipientsManagerGetPreference: jest.SpyInstancelet mockRecipientsManagerGetAllMarketingMessagingPreference: jest.SpyInstance@@ -35,7 +38,8 @@ describe('RecipientPreferencesService', () => {'getAllMarketingMessagingPreference')- service = new RecipientPreferencesService(mockRecipientsManager)+ mockEmailSuppressionService = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ service = new RecipientPreferencesService(mockRecipientsManager, mockEmailSuppressionService)})afterEach(async () => {@@ -341,6 +345,126 @@ describe('RecipientPreferencesService', () => {expect(result).toBe(false)expect(mockRecipientsManagerGetAllMarketingMessagingPreference).toHaveBeenCalledWith(recipient)})++ describe('when the recipient is on the suppression list (enforce enabled)', () => {+ // EmailSuppressionService reads EMAIL_SUPPRESSION_ENFORCE_ENABLED once in its+ // constructor, so we flip the env then rebuild both services so the fresh instance+ // reads it. Suppression is a deliverability signal that must apply even to+ // transactional messages — the parameterized case guards that ordering.+ let originalEnforceEnv: string | undefined++ beforeEach(() => {+ originalEnforceEnv = process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED+ process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED = 'true'+ mockEmailSuppressionService = new EmailSuppressionService(+ hub.postgres,+ emailSuppressionConfigFromEnv()+ )+ service = new RecipientPreferencesService(mockRecipientsManager, mockEmailSuppressionService)+ })++ afterEach(() => {+ if (originalEnforceEnv === undefined) {+ delete process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED+ } else {+ process.env.EMAIL_SUPPRESSION_ENFORCE_ENABLED = originalEnforceEnv+ }+ })++ const insertSuppressionRow = async (email: string): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'BOUNCE', 'test row', 5,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-suppression'+ )+ }++ it.each([+ ['marketing', 'marketing' as const],+ ['transactional', 'transactional' as const],+ ])('skips a %s email to a suppressed recipient', async (_label, categoryType) => {+ const email = `suppressed-${categoryType}@example.com`+ await insertSuppressionRow(email)+ const action = createEmailAction(email, '123e4567-e89b-12d3-a456-426614174000', categoryType)+ const invocation = createFunctionStepInvocation(action)++ const result = await service.shouldSkipAction(invocation, action)++ expect(result).toBe(true)+ })++ // A suppressed address placed in cc or bcc must still block the send, because SES+ // delivers to every recipient list, not just `to`.+ it.each([+ ['cc', '[email protected]', '[email protected]'],+ ['bcc', '[email protected]', '[email protected]'],+ [+ 'cc RFC-822 bracketed',+ '[email protected]',+ '"Blocked User" <[email protected]>',+ ],+ [+ 'bcc mixed comma-separated list',+ '[email protected]',+ ],+ ] as const)(+ 'skips when a suppressed address appears in %s',+ async (field, suppressedEmail, headerValue) => {+ await insertSuppressionRow(suppressedEmail)+ const action = createEmailAction(+ '[email protected]',+ '123e4567-e89b-12d3-a456-426614174000',+ 'marketing'+ )+ const invocation = createFunctionStepInvocation(action)+ // Inject the cc/bcc into the resolved invocation inputs (this is what the+ // executor sees at send time after template resolution).+ const emailInputs = invocation.state.globals!.inputs!.email as {+ to: { email: string }+ cc?: string+ bcc?: string+ }+ if (field.startsWith('cc')) {+ emailInputs.cc = headerValue+ } else {+ emailInputs.bcc = headerValue+ }++ const result = await service.shouldSkipAction(invocation, action)++ expect(result).toBe(true)+ }+ )++ it('does not skip when cc/bcc contain only non-suppressed addresses', async () => {+ // Sanity check: the CC/BCC scan must not over-suppress. `to` is not suppressed+ // and cc/bcc contain unrelated addresses → fall through to the opt-out path.+ const action = createEmailAction(+ '[email protected]',+ '123e4567-e89b-12d3-a456-426614174000',+ 'marketing'+ )+ const invocation = createFunctionStepInvocation(action)+ const emailInputs = invocation.state.globals!.inputs!.email as {+ to: { email: string }+ cc?: string+ bcc?: string+ }+ emailInputs.cc = '[email protected], [email protected]'+ emailInputs.bcc = '[email protected]'+ mockRecipientsManagerGet.mockResolvedValue(null)++ const result = await service.shouldSkipAction(invocation, action)++ expect(result).toBe(false)+ })+ })})describe('for SMS actions', () => {diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.tsindex a0f07090d305..080a4ae84d36 100644--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts@@ -3,13 +3,33 @@ import { logger } from '~/common/utils/logger'import { CyclotronJobInvocationHogFunction } from '../../types'import { RecipientsManagerService } from '../managers/recipients-manager.service'+import { EmailSuppressionService } from './email-suppression.service'type MessageFunctionActionType = 'function_email' | 'function_sms' | 'function_push'type MessageAction = Extract<HogFlowAction, { type: MessageFunctionActionType }>+// Split a comma-separated address list and, for each entry, extract the bare email from an RFC-822+// `"Name" <email@x>` form so it can be matched against normalized suppression identifiers.+const extractEmailsFromAddressList = (value: unknown): string[] => {+ if (typeof value !== 'string' || value.trim().length === 0) {+ return []+ }+ return value+ .split(',')+ .map((raw) => {+ const trimmed = raw.trim()+ const bracketed = trimmed.match(/<([^>]+)>/)+ return (bracketed ? bracketed[1] : trimmed).trim()+ })+ .filter((addr) => addr.length > 0)+}+export class RecipientPreferencesService {- constructor(private recipientsManager: RecipientsManagerService) {}+ constructor(+ private recipientsManager: RecipientsManagerService,+ private emailSuppressionService: EmailSuppressionService+ ) {}public async shouldSkipAction(invocation: CyclotronJobInvocationHogFunction,@@ -19,6 +39,13 @@ export class RecipientPreferencesService {return false}+ // Suppression is a deliverability signal, not a messaging preference: an address that can't+ // receive mail can't receive it regardless of category. So we check it even for+ // transactional messages, and before the transactional opt-out bypass below.+ if (await this.isRecipientSuppressed(invocation, action)) {+ return true+ }+// Transactional messages are not eligible for opt-outs, so they send regardless of// whether the recipient has opted out of this category or of all marketing messaging.if (action.config.message_category_type === 'transactional') {@@ -28,6 +55,41 @@ export class RecipientPreferencesService {return await this.isRecipientOptedOutOfAction(invocation, action)}+ private async isRecipientSuppressed(+ invocation: CyclotronJobInvocationHogFunction,+ action: MessageAction+ ): Promise<boolean> {+ // Suppression is driven by email bounces, so it only applies to email sends.+ if (action.type !== 'function_email') {+ return false+ }++ // Check every destination address SES will see — `to`, `cc`, and `bcc`. A suppressed+ // address in any of the three blocks the send, not just when it appears in `to`.+ const emailInputs = invocation.state.globals.inputs?.email+ const to = emailInputs?.to?.email+ const recipients = [+ ...(typeof to === 'string' && to.trim() ? [to.trim()] : []),+ ...extractEmailsFromAddressList(emailInputs?.cc),+ ...extractEmailsFromAddressList(emailInputs?.bcc),+ ]++ if (recipients.length === 0) {+ return false+ }++ try {+ const results = await Promise.all(+ recipients.map((email) => this.emailSuppressionService.isSuppressed(invocation.teamId, email))+ )+ return results.some(Boolean)+ } catch (error) {+ // Fail open — never block a send on a suppression-lookup error.+ logger.error(`Failed to check suppression list for recipients ${recipients.join(', ')}:`, error)+ return false+ }+ }+private isSubjectToRecipientPreferences(action: HogFlowAction): action is MessageAction {return ['function_email', 'function_sms', 'function_push'].includes(action.type)}diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex 8b6e12ed4235..bdfabeb674eb 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -207,7 +207,8 @@ export class TemplateTester {undefined as any,config.ENCRYPTION_SALT_KEYS,config.SITE_URL,- new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)+ new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),+ undefined as any)return new HogExecutorService({diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 81d9e1c332f7..4d546dbb452e 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -237,6 +237,7 @@ export type MinimalAppMetric = {| 'email_link_clicked'| 'email_bounced'| 'email_bounce_prevented'+ | 'email_suppressed'| 'email_blocked'| 'email_spam'| 'email_unsubscribed'diff --git a/products/messaging/backend/api/message_suppression.py b/products/messaging/backend/api/message_suppression.pynew file mode 100644index 000000000000..18a6648e899d--- /dev/null+++ b/products/messaging/backend/api/message_suppression.py@@ -0,0 +1,223 @@+from typing import Any++from django.db.models import F+from django.db.models.functions import Coalesce, Now+from django.utils import timezone++from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import PermissionDenied+from rest_framework.pagination import PageNumberPagination+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.documentation import _FallbackSerializer+from posthog.api.routing import TeamAndOrgViewSetMixin++from products.messaging.backend.models.message_suppression import MessageSuppression, SuppressionSource+++class SuppressionPagination(PageNumberPagination):+ page_size = 20+ page_size_query_param = "page_size"+ max_page_size = 100+++class MessageSuppressionSerializer(serializers.ModelSerializer):+ class Meta:+ model = MessageSuppression+ fields = [+ "id",+ "identifier",+ "source",+ "reason",+ "transient_bounce_count",+ "last_bounce_at",+ "last_bounce_diagnostic",+ "suppressed",+ "suppressed_at",+ "created_at",+ "updated_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "Server-assigned UUID for this suppression entry."},+ "identifier": {+ "help_text": "Normalized recipient email address. Suppression is keyed on this value, per team."+ },+ "source": {+ "help_text": "How the entry landed on the list: `BOUNCE` for automatic (bounce-driven), `MANUAL` for user-added via the UI/API."+ },+ "reason": {+ "help_text": "Human-readable reason for the suppression (e.g. 'Auto-suppressed after 5 consecutive soft bounces')."+ },+ "transient_bounce_count": {+ "help_text": "Rolling count of consecutive soft bounces with no successful delivery in between. Reset to 0 on any successful delivery. Ignored for MANUAL entries."+ },+ "last_bounce_at": {"help_text": "Timestamp of the most recent bounce, if any."},+ "last_bounce_diagnostic": {+ "help_text": "SMTP diagnostic string from the most recent bounce (e.g. '550 5.1.1 user unknown'), kept for visibility."+ },+ "suppressed": {+ "help_text": "Whether the address is actively suppressed. A BOUNCE row can exist while still only counting bounces (suppressed=false) before it crosses the threshold."+ },+ "suppressed_at": {"help_text": "Timestamp when the address was first suppressed."},+ "created_at": {"help_text": "When the row was first created (first bounce or manual add)."},+ "updated_at": {"help_text": "When the row was last touched by any write."},+ }+++class PaginatedMessageSuppressionSerializer(serializers.Serializer):+ """OpenAPI shape for the paginated suppressions response. Declared so drf-spectacular emits+ the {count, next, previous, results} envelope on the generated client, rather than a bare+ array — which the frontend actually receives at runtime."""++ count = serializers.IntegerField(help_text="Total number of suppressed recipients for the team.")+ next = serializers.URLField(allow_null=True, help_text="URL for the next page, or null on the last page.")+ previous = serializers.URLField(allow_null=True, help_text="URL for the previous page, or null on the first page.")+ results = MessageSuppressionSerializer(many=True)+++class AddSuppressionRequestSerializer(serializers.Serializer):+ identifier = serializers.CharField(+ max_length=512,+ help_text="The email address to suppress. Will not receive any messages until removed.",+ )+++class MessageSuppressionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """+ Per-team email suppression list. Addresses here are skipped before send.++ Entries are added automatically after an address repeatedly soft-bounces, or manually by a+ user. This viewset lets users see and edit the list for full visibility.+ """++ scope_object = "hog_flow"+ # Custom actions must declare their write status so TeamAndOrgViewSetMixin's AccessControlPermission+ # checks hog_flow:write on the mutating endpoints; the default 'suppressions' list stays a read.+ scope_object_write_actions = ["add_suppression", "remove_suppression"]+ serializer_class = _FallbackSerializer++ @extend_schema(+ parameters=[+ OpenApiParameter(name="page", type=int, location=OpenApiParameter.QUERY, required=False),+ OpenApiParameter(name="page_size", type=int, location=OpenApiParameter.QUERY, required=False),+ ],+ responses={200: PaginatedMessageSuppressionSerializer},+ summary="List suppressed email addresses for the team",+ )+ @action(detail=False, methods=["get"])+ def suppressions(self, request: Request, **kwargs: Any) -> Response:+ """List suppressed recipients for the team, most recently updated first."""+ # Resource-level check: `AccessControlPermission` only guarantees the caller has some+ # hog_flow object access. Since this endpoint returns team-wide data (every suppressed+ # recipient + their SMTP diagnostics) with no per-workflow object, require project-wide+ # hog_flow viewer access — otherwise a member granted access to a single workflow could+ # read the entire team's suppression list.+ if not self.user_access_control.check_access_level_for_resource("hog_flow", "viewer"):+ raise PermissionDenied("You need hog_flow viewer access to view the suppression list.")++ suppressions = (+ MessageSuppression.objects.for_team(self.team_id)+ .filter(suppressed=True, deleted=False)+ .order_by("-updated_at")+ )++ paginator = SuppressionPagination()+ page = paginator.paginate_queryset(suppressions, request)+ if page is not None:+ serializer = MessageSuppressionSerializer(page, many=True)+ return paginator.get_paginated_response(serializer.data)++ serializer = MessageSuppressionSerializer(suppressions, many=True)+ return Response(serializer.data)++ @extend_schema(+ request=AddSuppressionRequestSerializer,+ responses={201: MessageSuppressionSerializer},+ summary="Manually add an email address to the suppression list",+ )+ @action(detail=False, methods=["post"])+ def add_suppression(self, request: Request, **kwargs: Any) -> Response:+ """Manually suppress an email address so no workflow sends to it."""+ # Team-wide mutation with no per-workflow object — require project-wide hog_flow editor+ # access. Otherwise an editor grant on one workflow could add arbitrary addresses to the+ # team's suppression list, blocking unrelated (including transactional) delivery.+ if not self.user_access_control.check_access_level_for_resource("hog_flow", "editor"):+ raise PermissionDenied("You need hog_flow editor access to modify the suppression list.")++ serializer = AddSuppressionRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ identifier = serializer.validated_data["identifier"].strip().lower()++ suppression, created = MessageSuppression.objects.for_team(self.team_id).get_or_create(+ team_id=self.team_id,+ identifier=identifier,+ defaults={+ "created_by": request.user,+ "source": SuppressionSource.MANUAL,+ "suppressed": True,+ "suppressed_at": timezone.now(),+ "reason": "Manually added",+ },+ )++ if not created:+ # Re-suppress (and un-delete) an existing row, e.g. one that had only been counting+ # bounces or was previously removed. Coalesce lets Postgres preserve an existing+ # suppressed_at atomically, so two concurrent add_suppression calls can't both compute+ # their own now() and overwrite each other.+ MessageSuppression.objects.for_team(self.team_id).filter(pk=suppression.pk).update(+ suppressed=True,+ suppressed_at=Coalesce(F("suppressed_at"), Now()),+ source=SuppressionSource.MANUAL,+ reason="Manually added",+ deleted=False,+ updated_at=Now(),+ )+ suppression.refresh_from_db()++ response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK+ return Response(MessageSuppressionSerializer(suppression).data, status=response_status)++ @extend_schema(+ request=AddSuppressionRequestSerializer,+ responses={204: None},+ summary="Remove an email address from the suppression list",+ )+ @action(detail=False, methods=["post"])+ def remove_suppression(self, request: Request, **kwargs: Any) -> Response:+ """Remove an address from the suppression list so it can receive messages again."""+ # Same rationale as add_suppression — this is a team-wide mutation.+ if not self.user_access_control.check_access_level_for_resource("hog_flow", "editor"):+ raise PermissionDenied("You need hog_flow editor access to modify the suppression list.")++ serializer = AddSuppressionRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ identifier = serializer.validated_data["identifier"].strip().lower()++ # Soft-delete and un-suppress. Reset the bounce counter so a previously-dead address that+ # a user deliberately re-enables starts from a clean slate. `source` is reset to BOUNCE so+ # a future auto-suppression can re-suppress this row — the node upserts skip rows with+ # source='MANUAL' (to protect user-managed entries), so a removed MANUAL row would otherwise+ # be permanently invisible to the bounce-driven write path.+ updated = (+ MessageSuppression.objects.for_team(self.team_id)+ .filter(identifier=identifier)+ .update(+ suppressed=False,+ deleted=True,+ transient_bounce_count=0,+ source=SuppressionSource.BOUNCE,+ updated_at=timezone.now(),+ )+ )++ if not updated:+ return Response({"error": "Suppression not found"}, status=status.HTTP_404_NOT_FOUND)++ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/messaging/backend/api/test/test_message_suppression.py b/products/messaging/backend/api/test/test_message_suppression.pynew file mode 100644index 000000000000..dff6728e39b3--- /dev/null+++ b/products/messaging/backend/api/test/test_message_suppression.py@@ -0,0 +1,60 @@+from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase++from products.messaging.backend.api.message_suppression import MessageSuppressionViewSet+from products.messaging.backend.models.message_suppression import MessageSuppression, SuppressionSource+++class TestMessageSuppressionViewSetScope(SimpleTestCase):+ """+ Guards against the viewset silently reverting to scope_object='INTERNAL', which would bypass+ hog_flow RBAC and let any project member manage suppressions regardless of workflow permissions.+ """++ def test_scope_object_is_hog_flow(self) -> None:+ assert MessageSuppressionViewSet.scope_object == "hog_flow"++ def test_mutating_actions_are_declared_as_writes(self) -> None:+ # `add_suppression` and `remove_suppression` are custom @action endpoints; without being+ # listed here they'd default to a read scope and slip past hog_flow:write enforcement.+ assert set(MessageSuppressionViewSet.scope_object_write_actions) == {+ "add_suppression",+ "remove_suppression",+ }+++class TestRemoveSuppressionResetsSource(APIBaseTest):+ """+ Guards against a regression where remove_suppression keeps source='MANUAL' on the removed row.+ The node upserts preserve suppressed/deleted `WHEN source = 'MANUAL'`, so a manual entry that+ was removed via the API would never be auto-suppressed again — not even by a hard bounce —+ and would stay hidden from the UI (which filters deleted=false).+ """++ def _url(self, action: str) -> str:+ return f"/api/projects/{self.team.id}/messaging_suppressions/{action}/"++ def test_remove_resets_source_to_bounce_so_future_auto_suppression_can_run(self) -> None:+ # Manual add → row exists as MANUAL, suppressed.+ response = self.client.post(self._url("add_suppression"), {"identifier": "[email protected]"}, format="json")+ assert response.status_code in (200, 201)++ row = MessageSuppression.objects.for_team(self.team.id).get(identifier="[email protected]")+ assert row.source == SuppressionSource.MANUAL+ assert row.suppressed++ # Remove — the row should be un-suppressed AND its source reset so that the ON CONFLICT+ # branches in the node write path (which skip MANUAL rows) can re-suppress it later.+ response = self.client.post(self._url("remove_suppression"), {"identifier": "[email protected]"}, format="json")+ assert response.status_code == 204++ row.refresh_from_db()+ assert (row.suppressed, row.deleted, row.transient_bounce_count, row.source) == (+ False,+ True,+ 0,+ SuppressionSource.BOUNCE,+ ), (+ "remove_suppression must reset the row so the node write path can auto-suppress this address again if it later bounces"+ )diff --git a/products/messaging/backend/routes.py b/products/messaging/backend/routes.pyindex ab3be0ebbc64..770954d5b63c 100644--- a/products/messaging/backend/routes.py+++ b/products/messaging/backend/routes.py@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistryfrom products.messaging.backend.api.message_categories import MessageCategoryViewSetfrom products.messaging.backend.api.message_preferences import MessagePreferencesViewSet+from products.messaging.backend.api.message_suppression import MessageSuppressionViewSetfrom products.messaging.backend.api.message_templates import MessageTemplatesViewSet@@ -15,3 +16,7 @@ def register_routes(routers: RouterRegistry) -> None:routers.register_legacy_dual_route(r"messaging_preferences", MessagePreferencesViewSet, "project_messaging_preferences", ["team_id"])+ # New endpoint — register under /api/projects/ only, not the dual-route legacy shim.+ routers.projects.register(+ r"messaging_suppressions", MessageSuppressionViewSet, "project_messaging_suppressions", ["team_id"]+ )diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex f1eae1260af3..d43668e64d66 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -79,6 +79,87 @@ export interface MessagePreferencesApi {preferences: unknown}+export interface AddSuppressionRequestApi {+ /**+ * The email address to suppress. Will not receive any messages until removed.+ * @maxLength 512+ */+ identifier: string+}++/**+ * * `BOUNCE` - Bounce+ * * `MANUAL` - Manual+ */+export type MessageSuppressionSourceEnumApi =+ (typeof MessageSuppressionSourceEnumApi)[keyof typeof MessageSuppressionSourceEnumApi]++export const MessageSuppressionSourceEnumApi = {+ Bounce: 'BOUNCE',+ Manual: 'MANUAL',+} as const++export interface MessageSuppressionApi {+ /** Server-assigned UUID for this suppression entry. */+ readonly id: string+ /** Normalized recipient email address. Suppression is keyed on this value, per team. */+ readonly identifier: string+ /** How the entry landed on the list: `BOUNCE` for automatic (bounce-driven), `MANUAL` for user-added via the UI/API.+ *+ * * `BOUNCE` - Bounce+ * * `MANUAL` - Manual */+ readonly source: MessageSuppressionSourceEnumApi+ /**+ * Human-readable reason for the suppression (e.g. 'Auto-suppressed after 5 consecutive soft bounces').+ * @nullable+ */+ readonly reason: string | null+ /** Rolling count of consecutive soft bounces with no successful delivery in between. Reset to 0 on any successful delivery. Ignored for MANUAL entries. */+ readonly transient_bounce_count: number+ /**+ * Timestamp of the most recent bounce, if any.+ * @nullable+ */+ readonly last_bounce_at: string | null+ /**+ * SMTP diagnostic string from the most recent bounce (e.g. '550 5.1.1 user unknown'), kept for visibility.+ * @nullable+ */+ readonly last_bounce_diagnostic: string | null+ /** Whether the address is actively suppressed. A BOUNCE row can exist while still only counting bounces (suppressed=false) before it crosses the threshold. */+ readonly suppressed: boolean+ /**+ * Timestamp when the address was first suppressed.+ * @nullable+ */+ readonly suppressed_at: string | null+ /** When the row was first created (first bounce or manual add). */+ readonly created_at: string+ /** When the row was last touched by any write. */+ readonly updated_at: string+}++/**+ * OpenAPI shape for the paginated suppressions response. Declared so drf-spectacular emits+ * the {count, next, previous, results} envelope on the generated client, rather than a bare+ * array — which the frontend actually receives at runtime.+ */+export interface PaginatedMessageSuppressionApi {+ /** Total number of suppressed recipients for the team. */+ count: number+ /**+ * URL for the next page, or null on the last page.+ * @nullable+ */+ next: string | null+ /**+ * URL for the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null+ results: MessageSuppressionApi[]+}+/*** * `liquid` - liquid*/@@ -336,6 +417,11 @@ export type MessagingCategoriesListParams = {offset?: number}+export type MessagingSuppressionsSuppressionsRetrieveParams = {+ page?: number+ page_size?: number+}+export type MessagingTemplatesListParams = {/*** Number of results to return per page.diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.tsindex cc919a6cbb2f..57e527549352 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -10,12 +10,16 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {AddOptOutRequestApi,+ AddSuppressionRequestApi,MessageCategoryApi,MessagePreferencesApi,+ MessageSuppressionApi,MessageTemplateApi,MessagingCategoriesListParams,+ MessagingSuppressionsSuppressionsRetrieveParams,MessagingTemplatesListParams,PaginatedMessageCategoryListApi,+ PaginatedMessageSuppressionApi,PaginatedMessageTemplateListApi,PatchedDesignPatchApi,PatchedMessageCategoryApi,@@ -398,6 +402,85 @@ export const messagingPreferencesWebhookUrlRetrieve = async (})}+export const getMessagingSuppressionsAddSuppressionCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/messaging_suppressions/add_suppression/`+}++/**+ * Manually suppress an email address so no workflow sends to it.+ * @summary Manually add an email address to the suppression list+ */+export const messagingSuppressionsAddSuppressionCreate = async (+ projectId: string,+ addSuppressionRequestApi: AddSuppressionRequestApi,+ options?: RequestInit+): Promise<MessageSuppressionApi> => {+ return apiMutator<MessageSuppressionApi>(getMessagingSuppressionsAddSuppressionCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(addSuppressionRequestApi),+ })+}++export const getMessagingSuppressionsRemoveSuppressionCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/messaging_suppressions/remove_suppression/`+}++/**+ * Remove an address from the suppression list so it can receive messages again.+ * @summary Remove an email address from the suppression list+ */+export const messagingSuppressionsRemoveSuppressionCreate = async (+ projectId: string,+ addSuppressionRequestApi: AddSuppressionRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getMessagingSuppressionsRemoveSuppressionCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(addSuppressionRequestApi),+ })+}++export const getMessagingSuppressionsSuppressionsRetrieveUrl = (+ projectId: string,+ params?: MessagingSuppressionsSuppressionsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/messaging_suppressions/suppressions/?${stringifiedParams}`+ : `/api/projects/${projectId}/messaging_suppressions/suppressions/`+}++/**+ * List suppressed recipients for the team, most recently updated first.+ * @summary List suppressed email addresses for the team+ */+export const messagingSuppressionsSuppressionsRetrieve = async (+ projectId: string,+ params?: MessagingSuppressionsSuppressionsRetrieveParams,+ options?: RequestInit+): Promise<PaginatedMessageSuppressionApi> => {+ return apiMutator<PaginatedMessageSuppressionApi>(+ getMessagingSuppressionsSuppressionsRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getMessagingTemplatesListUrl = (projectId: string, params?: MessagingTemplatesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex bb6d1355d384..c95172d2b53e 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -163,6 +163,32 @@ export const MessagingPreferencesAddOptOutCreateBody = /* @__PURE__ */ zod.objec.describe('Optional message category key. If omitted, the recipient is opted out of all marketing messages.'),})+/**+ * Manually suppress an email address so no workflow sends to it.+ * @summary Manually add an email address to the suppression list+ */+export const messagingSuppressionsAddSuppressionCreateBodyIdentifierMax = 512++export const MessagingSuppressionsAddSuppressionCreateBody = /* @__PURE__ */ zod.object({+ identifier: zod+ .string()+ .max(messagingSuppressionsAddSuppressionCreateBodyIdentifierMax)+ .describe('The email address to suppress. Will not receive any messages until removed.'),+})++/**+ * Remove an address from the suppression list so it can receive messages again.+ * @summary Remove an email address from the suppression list+ */+export const messagingSuppressionsRemoveSuppressionCreateBodyIdentifierMax = 512++export const MessagingSuppressionsRemoveSuppressionCreateBody = /* @__PURE__ */ zod.object({+ identifier: zod+ .string()+ .max(messagingSuppressionsRemoveSuppressionCreateBodyIdentifierMax)+ .describe('The email address to suppress. Will not receive any messages until removed.'),+})+export const messagingTemplatesCreateBodyNameMax = 400export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`diff --git a/products/workflows/backend/api/test/test_message_suppression_access_control.py b/products/workflows/backend/api/test/test_message_suppression_access_control.pynew file mode 100644index 000000000000..a4b7b82c888a--- /dev/null+++ b/products/workflows/backend/api/test/test_message_suppression_access_control.py@@ -0,0 +1,109 @@+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 TestMessageSuppressionAccessControl(APIBaseTest):+ """+ Guards the resource-level RBAC gate on `/api/projects/:id/messaging_suppressions/`.++ The endpoints act on team-wide data (every suppressed recipient, their SMTP diagnostics,+ 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 mutate the entire team's list.+ `check_access_level_for_resource` closes that gap by requiring project-wide hog_flow access.++ 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_viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ 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 for the regression users.+ # A locked-down project is the scenario the reviewer flagged: object grants are the only+ # access the user has.+ AccessControl.objects.create(+ team=self.team,+ resource="hog_flow",+ resource_id=None,+ access_level="none",+ organization_member=None,+ role=None,+ )++ # Object-level grants use 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.+ single_workflow_id = str(uuid.uuid4())+ self._grant(self.object_viewer, access_level="viewer", resource_id=single_workflow_id)+ self._grant(self.object_editor, access_level="editor", resource_id=single_workflow_id)+ 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_suppressions/{action}/"++ @parameterized.expand(+ [+ # (grant_type, list_status, add_status, remove_status)+ # Regression cases: object-level grant on one workflow must not unlock team-wide endpoints.+ ("object_viewer", status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),+ ("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_204_NO_CONTENT),+ ]+ )+ 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("suppressions")).status_code == list_status+ assert (+ self.client.post(+ self._url("add_suppression"), {"identifier": f"{grant_type}@example.com"}, format="json"+ ).status_code+ == add_status+ )+ assert (+ self.client.post(+ self._url("remove_suppression"), {"identifier": f"{grant_type}@example.com"}, format="json"+ ).status_code+ == remove_status+ )diff --git a/products/workflows/frontend/Suppression/SuppressionList.tsx b/products/workflows/frontend/Suppression/SuppressionList.tsxnew file mode 100644index 000000000000..58310bf0101e--- /dev/null+++ b/products/workflows/frontend/Suppression/SuppressionList.tsx@@ -0,0 +1,193 @@+import { useActions, useValues } from 'kea'++import { IconChevronLeft, IconChevronRight, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'+import { LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { More } from 'lib/lemon-ui/LemonButton/More'++import type { MessageSuppressionApi } from 'products/messaging/frontend/generated/api.schemas'++import { suppressionListLogic } from './suppressionListLogic'++const PAGE_SIZE = 20++export function SuppressionList(): JSX.Element {+ const {+ loadNextPage,+ loadPreviousPage,+ loadSuppressions,+ setShowAddModal,+ setNewIdentifier,+ addSuppression,+ removeSuppression,+ } = useActions(suppressionListLogic)+ const {+ suppressions,+ suppressionsLoading,+ currentPage,+ showAddModal,+ addSuppressionLoading,+ removeSuppressionLoading,+ newIdentifier,+ } = useValues(suppressionListLogic)++ const columns: LemonTableColumns<MessageSuppressionApi> = [+ {+ title: 'Recipient',+ dataIndex: 'identifier',+ key: 'identifier',+ },+ {+ title: 'Added by',+ dataIndex: 'source',+ key: 'source',+ render: (source) => (+ <LemonTag type={source === 'MANUAL' ? 'completion' : 'warning'}>+ {source === 'MANUAL' ? 'Manual' : 'Bounces'}+ </LemonTag>+ ),+ },+ {+ title: 'Reason',+ key: 'reason',+ render: function Render(_, entry: MessageSuppressionApi): JSX.Element {+ return (+ <span className="text-muted text-xs">{entry.reason || (entry.last_bounce_diagnostic ?? '—')}</span>+ )+ },+ },+ {+ title: 'Suppressed',+ dataIndex: 'suppressed_at',+ key: 'suppressed_at',+ render: (suppressed_at) => (suppressed_at ? <TZLabel time={suppressed_at as string} /> : <span>—</span>),+ },+ {+ width: 0,+ render: function Render(_, entry: MessageSuppressionApi): JSX.Element {+ return (+ <More+ overlay={+ <LemonButton+ status="danger"+ icon={<IconTrash />}+ onClick={() => removeSuppression(entry.identifier)}+ loading={removeSuppressionLoading}+ disabledReason={removeSuppressionLoading ? 'Removing…' : undefined}+ fullWidth+ >+ Remove+ </LemonButton>+ }+ />+ )+ },+ },+ ]++ const totalPages = suppressions.count ? Math.ceil(suppressions.count / PAGE_SIZE) : 0+ const showingStart = (currentPage - 1) * PAGE_SIZE + 1+ const showingEnd = Math.min(currentPage * PAGE_SIZE, suppressions.count)++ return (+ <>+ <div className="flex justify-end gap-2 mb-2">+ <LemonButton icon={<IconPlus />} size="small" type="secondary" onClick={() => setShowAddModal(true)}>+ Add address+ </LemonButton>+ <LemonButton+ icon={<IconRefresh />}+ size="small"+ type="secondary"+ onClick={loadSuppressions}+ loading={suppressionsLoading}+ >+ Reload+ </LemonButton>+ </div>+ <LemonTable+ columns={columns}+ dataSource={suppressions.results || []}+ loading={suppressionsLoading}+ loadingSkeletonRows={3}+ rowKey="identifier"+ emptyState="No suppressed addresses. Addresses land here automatically after repeated soft bounces, or when you add them manually."+ size="small"+ />+ {suppressions.count > PAGE_SIZE && (+ <div className="flex items-center justify-between mt-4 px-2">+ <div className="text-sm text-muted">+ <span>+ Showing {showingStart} - {showingEnd} of {suppressions.count.toLocaleString()} addresses+ </span>+ </div>+ <div className="flex items-center gap-2">+ <LemonButton+ icon={<IconChevronLeft />}+ size="small"+ disabled={currentPage === 1 || suppressionsLoading}+ onClick={loadPreviousPage}+ />+ <span className="text-sm">+ Page {currentPage} of {totalPages}+ </span>+ <LemonButton+ icon={<IconChevronRight />}+ size="small"+ disabled={!suppressions.next || suppressionsLoading}+ onClick={loadNextPage}+ />+ </div>+ </div>+ )}++ <LemonModal+ isOpen={showAddModal}+ onClose={() => setShowAddModal(false)}+ title="Add address to suppression list"+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setShowAddModal(false)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={addSuppressionLoading}+ disabledReason={+ addSuppressionLoading+ ? 'Adding…'+ : !newIdentifier.trim()+ ? 'Enter an email address'+ : undefined+ }+ onClick={() => addSuppression(newIdentifier.trim())}+ >+ Add address+ </LemonButton>+ </>+ }+ >+ <div className="space-y-2">+ <label htmlFor="suppression-identifier" className="text-sm font-medium">+ Email address+ </label>+ <LemonInput+ id="suppression-identifier"+ placeholder="[email protected]"+ value={newIdentifier}+ onChange={setNewIdentifier}+ autoFocus+ onPressEnter={() => {+ // Guard against a second Enter mid-flight firing a duplicate POST — the+ // footer button already disables while loading; mirror that here.+ if (newIdentifier.trim() && !addSuppressionLoading) {+ addSuppression(newIdentifier.trim())+ }+ }}+ />+ </div>+ </LemonModal>+ </>+ )+}diff --git a/products/workflows/frontend/Suppression/SuppressionScene.tsx b/products/workflows/frontend/Suppression/SuppressionScene.tsxnew file mode 100644index 000000000000..150f34e22331--- /dev/null+++ b/products/workflows/frontend/Suppression/SuppressionScene.tsx@@ -0,0 +1,17 @@+import { SuppressionList } from './SuppressionList'++export function SuppressionScene(): JSX.Element {+ return (+ <div className="space-y-4" data-attr="suppression-scene">+ <div>+ <h2 className="text-xl font-semibold">Suppression list</h2>+ <p className="mt-2">+ Email addresses that workflows will never send to. Addresses are added automatically after they+ repeatedly soft-bounce (their mail server keeps rejecting or timing out), or you can add them+ manually. Remove an address to start sending to it again.+ </p>+ </div>+ <SuppressionList />+ </div>+ )+}diff --git a/products/workflows/frontend/Suppression/suppressionListLogic.test.ts b/products/workflows/frontend/Suppression/suppressionListLogic.test.tsnew file mode 100644index 000000000000..ff5e7fb3b2f9--- /dev/null+++ b/products/workflows/frontend/Suppression/suppressionListLogic.test.ts@@ -0,0 +1,44 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import * as messagingApi from 'products/messaging/frontend/generated/api'++import { suppressionListLogic } from './suppressionListLogic'++describe('suppressionListLogic', () => {+ beforeEach(() => {+ initKeaTests()+ })++ describe('page-state failure isolation', () => {+ // Guards against the "silent-swallow catch returns previous rows -> kea-loaders treats it as+ // success -> currentPage still increments" bug. On a failed loadNextPage the counter must+ // stay put; otherwise the UI shows the wrong page number over old data, then permanently+ // skips the page it thought it advanced to.+ it('does not advance currentPage when loadNextPage fails', async () => {+ jest.spyOn(messagingApi, 'messagingSuppressionsSuppressionsRetrieve').mockRejectedValue(new Error('boom'))+ const logic = suppressionListLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.loadNextPage()+ }).toDispatchActions(['loadNextPageFailure'])++ expect(logic.values.currentPage).toBe(1)+ })++ it('does not roll back currentPage when loadPreviousPage fails', async () => {+ jest.spyOn(messagingApi, 'messagingSuppressionsSuppressionsRetrieve').mockRejectedValue(new Error('boom'))+ const logic = suppressionListLogic()+ logic.mount()+ logic.actions.setCurrentPage(3)++ await expectLogic(logic, () => {+ logic.actions.loadPreviousPage()+ }).toDispatchActions(['loadPreviousPageFailure'])++ expect(logic.values.currentPage).toBe(3)+ })+ })+})diff --git a/products/workflows/frontend/Suppression/suppressionListLogic.ts b/products/workflows/frontend/Suppression/suppressionListLogic.tsnew file mode 100644index 000000000000..19f616b899d4--- /dev/null+++ b/products/workflows/frontend/Suppression/suppressionListLogic.ts@@ -0,0 +1,252 @@+import { MakeLogicType, actions, afterMount, connect, kea, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { projectLogic } from 'scenes/projectLogic'++import {+ messagingSuppressionsAddSuppressionCreate,+ messagingSuppressionsRemoveSuppressionCreate,+ messagingSuppressionsSuppressionsRetrieve,+} from 'products/messaging/frontend/generated/api'+import type {+ MessageSuppressionApi,+ PaginatedMessageSuppressionApi,+} from 'products/messaging/frontend/generated/api.schemas'++const EMPTY_SUPPRESSIONS: PaginatedMessageSuppressionApi = { count: 0, next: null, previous: null, results: [] }++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface suppressionListLogicValues {+ currentProjectId: number | null // projectLogic+ addSuppression: MessageSuppressionApi | null+ addSuppressionLoading: boolean+ currentPage: number+ newIdentifier: string+ removeSuppression: string | null+ removeSuppressionLoading: boolean+ showAddModal: boolean+ suppressions: PaginatedMessageSuppressionApi+ suppressionsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface suppressionListLogicActions {+ addSuppression: (identifier: string) => string+ addSuppressionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ addSuppressionSuccess: (+ addSuppression: MessageSuppressionApi,+ payload?: string+ ) => {+ addSuppression: MessageSuppressionApi+ payload?: string+ }+ loadNextPage: () => {+ value: true+ }+ loadNextPageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNextPageSuccess: (+ suppressions: PaginatedMessageSuppressionApi,+ payload?: {+ value: true+ }+ ) => {+ suppressions: PaginatedMessageSuppressionApi+ payload?: {+ value: true+ }+ }+ loadPreviousPage: () => {+ value: true+ }+ loadPreviousPageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPreviousPageSuccess: (+ suppressions: PaginatedMessageSuppressionApi,+ payload?: {+ value: true+ }+ ) => {+ suppressions: PaginatedMessageSuppressionApi+ payload?: {+ value: true+ }+ }+ loadSuppressions: () => any+ loadSuppressionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSuppressionsSuccess: (+ suppressions: PaginatedMessageSuppressionApi,+ payload?: any+ ) => {+ suppressions: PaginatedMessageSuppressionApi+ payload?: any+ }+ removeSuppression: (identifier: string) => string+ removeSuppressionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ removeSuppressionSuccess: (+ removeSuppression: string,+ payload?: string+ ) => {+ removeSuppression: string+ payload?: string+ }+ setCurrentPage: (page: number) => {+ page: number+ }+ setNewIdentifier: (identifier: string) => {+ identifier: string+ }+ setShowAddModal: (show: boolean) => {+ show: boolean+ }+}++export type suppressionListLogicType = MakeLogicType<suppressionListLogicValues, suppressionListLogicActions>++const fetchPage = async (projectId: number | null, page: number): Promise<PaginatedMessageSuppressionApi> => {+ if (projectId === null) {+ return EMPTY_SUPPRESSIONS+ }+ return await messagingSuppressionsSuppressionsRetrieve(String(projectId), { page })+}++export const suppressionListLogic = kea<suppressionListLogicType>([+ path(['products', 'workflows', 'frontend', 'Suppression', 'suppressionListLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ setCurrentPage: (page: number) => ({ page }),+ loadNextPage: true,+ loadPreviousPage: true,+ setShowAddModal: (show: boolean) => ({ show }),+ setNewIdentifier: (identifier: string) => ({ identifier }),+ }),+ reducers({+ currentPage: [+ 1,+ {+ setCurrentPage: (_, { page }) => page,+ loadSuppressionsSuccess: () => 1,+ loadNextPageSuccess: (state) => state + 1,+ loadPreviousPageSuccess: (state) => Math.max(1, state - 1),+ },+ ],+ showAddModal: [+ false,+ {+ setShowAddModal: (_, { show }) => show,+ addSuppressionSuccess: () => false,+ },+ ],+ newIdentifier: [+ '',+ {+ setNewIdentifier: (_, { identifier }) => identifier,+ addSuppressionSuccess: () => '',+ setShowAddModal: (state, { show }) => (show ? state : ''),+ },+ ],+ }),+ loaders(({ values, actions }) => ({+ suppressions: {+ __default: EMPTY_SUPPRESSIONS,+ loadSuppressions: async (): Promise<PaginatedMessageSuppressionApi> => {+ try {+ return await fetchPage(values.currentProjectId, 1)+ } catch (e) {+ lemonToast.error('Failed to load suppression list')+ // Rethrow so kea-loaders emits loadSuppressionsFailure and the currentPage reducer+ // (which only advances on *Success) stays put — otherwise a failed page fetch would+ // still tick currentPage and skip pages permanently.+ throw e+ }+ },+ loadNextPage: async (): Promise<PaginatedMessageSuppressionApi> => {+ try {+ return await fetchPage(values.currentProjectId, values.currentPage + 1)+ } catch (e) {+ lemonToast.error('Failed to load next page')+ throw e+ }+ },+ loadPreviousPage: async (): Promise<PaginatedMessageSuppressionApi> => {+ try {+ return await fetchPage(values.currentProjectId, Math.max(1, values.currentPage - 1))+ } catch (e) {+ lemonToast.error('Failed to load previous page')+ throw e+ }+ },+ },+ addSuppression: {+ __default: null as MessageSuppressionApi | null,+ addSuppression: async (identifier: string): Promise<MessageSuppressionApi> => {+ if (values.currentProjectId === null) {+ throw new Error('No current project')+ }+ try {+ const result = await messagingSuppressionsAddSuppressionCreate(String(values.currentProjectId), {+ identifier,+ })+ lemonToast.success(`${identifier} added to suppression list`)+ actions.loadSuppressions()+ return result+ } catch (e) {+ lemonToast.error('Failed to add to suppression list')+ throw e+ }+ },+ },+ removeSuppression: {+ __default: null as string | null,+ removeSuppression: async (identifier: string): Promise<string> => {+ if (values.currentProjectId === null) {+ throw new Error('No current project')+ }+ try {+ await messagingSuppressionsRemoveSuppressionCreate(String(values.currentProjectId), { identifier })+ lemonToast.success(`${identifier} removed from suppression list`)+ actions.loadSuppressions()+ return identifier+ } catch (e) {+ lemonToast.error('Failed to remove from suppression list')+ throw e+ }+ },+ },+ })),+ afterMount(({ actions }) => {+ actions.loadSuppressions()+ }),+])diff --git a/products/workflows/frontend/WorkflowsScene.test.ts b/products/workflows/frontend/WorkflowsScene.test.tsnew file mode 100644index 000000000000..17a438bb9005--- /dev/null+++ b/products/workflows/frontend/WorkflowsScene.test.ts@@ -0,0 +1,47 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { workflowsSceneLogic } from './WorkflowsScene'++describe('workflowsSceneLogic', () => {+ beforeEach(() => {+ initKeaTests()+ featureFlagLogic.mount()+ })++ describe('deep-link to /workflows/suppression', () => {+ // Guards the "flag-off user hits the suppression URL, activeKey stays 'suppression', but+ // the tab isn't in the tabs list" edge case — LemonTabs would render with no matching tab+ // and an empty content area. The logic should fall back to 'workflows' when the flag is off.+ it('falls back to workflows when WORKFLOWS_SUPPRESSION_LIST flag is off', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})+ const logic = workflowsSceneLogic()+ logic.mount()++ await expectLogic(logic, () => {+ router.actions.push('/workflows/suppression')+ }).toMatchValues({+ currentTab: 'workflows',+ })+ })++ it('honors the suppression tab when the flag is on', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WORKFLOWS_SUPPRESSION_LIST], {+ [FEATURE_FLAGS.WORKFLOWS_SUPPRESSION_LIST]: true,+ })+ const logic = workflowsSceneLogic()+ logic.mount()++ await expectLogic(logic, () => {+ router.actions.push('/workflows/suppression')+ }).toMatchValues({+ currentTab: 'suppression',+ })+ })+ })+})diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex 719b307313ff..5e46623eed8c 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, path, props, reducers, selectors, useActions, useValues } from 'kea'+import { MakeLogicType, actions, connect, kea, path, props, reducers, selectors, useActions, useValues } from 'kea'import { urlToAction } from 'kea-router'import { IconApple, IconAndroid, IconLetter, IconPlusSmall } from '@posthog/icons'@@ -24,15 +24,17 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'+import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'import { MessageChannels } from './Channels/MessageChannels'import { optOutCategoriesLogic } from './OptOuts/optOutCategoriesLogic'import { OptOutScene } from './OptOuts/OptOutScene'+import { SuppressionScene } from './Suppression/SuppressionScene'import { MessageTemplatesTable } from './TemplateLibrary/MessageTemplatesTable'import { newWorkflowLogic } from './Workflows/newWorkflowLogic'import { NewWorkflowModal } from './Workflows/NewWorkflowModal'import { WorkflowsTable } from './Workflows/WorkflowsTable'-const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs'] as const+const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs', 'suppression'] as constexport type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]export type WorkflowsSceneProps = {@@ -41,6 +43,7 @@ export type WorkflowsSceneProps = {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsSceneLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicbreadcrumbs: Breadcrumb[]currentTab: WorkflowsSceneTablogicProps: any@@ -49,7 +52,7 @@ export interface workflowsSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsSceneLogicActions {setCurrentTab: (tab: WorkflowsSceneTab) => {- tab: 'channels' | 'library' | 'opt-outs' | 'workflows'+ tab: 'channels' | 'library' | 'opt-outs' | 'suppression' | 'workflows'}}@@ -57,7 +60,7 @@ export interface workflowsSceneLogicActions {export interface workflowsSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {logicProps: (arg: any) => any- breadcrumbs: (currentTab: 'channels' | 'library' | 'opt-outs' | 'workflows') => Breadcrumb[]+ breadcrumbs: (currentTab: 'channels' | 'library' | 'opt-outs' | 'suppression' | 'workflows') => Breadcrumb[]}}@@ -71,6 +74,9 @@ export type workflowsSceneLogicType = MakeLogicType<export const workflowsSceneLogic = kea<workflowsSceneLogicType>([props({} as WorkflowsSceneProps),path(() => ['scenes', 'workflows', 'workflowsSceneLogic']),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ })),actions({setCurrentTab: (tab: WorkflowsSceneTab) => ({ tab }),}),@@ -111,6 +117,14 @@ export const workflowsSceneLogic = kea<workflowsSceneLogicType>([let possibleTab: WorkflowsSceneTab = (tab as WorkflowsSceneTab) ?? 'workflows'possibleTab = WORKFLOW_SCENE_TABS.includes(possibleTab) ? possibleTab : 'workflows'+ // The suppression tab is only rendered when its feature flag is on. Without this+ // guard, a flag-off user deep-linking to /workflows/suppression would set currentTab+ // to a tab that isn't in the tabs list — LemonTabs would show no active tab and no+ // content. Fall back to 'workflows' so the scene stays usable.+ if (possibleTab === 'suppression' && !values.featureFlags[FEATURE_FLAGS.WORKFLOWS_SUPPRESSION_LIST]) {+ possibleTab = 'workflows'+ }+if (possibleTab !== values.currentTab) {actions.setCurrentTab(possibleTab)}@@ -189,6 +203,10 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {: []),]+ // Suppression list is hidden until enforcement rolls out — until then the tab would show+ // entries that don't yet block sends, which would be confusing.+ const suppressionListEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_SUPPRESSION_LIST]+const tabs: LemonTab<WorkflowsSceneTab>[] = [{label: 'Workflows',@@ -218,6 +236,16 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {content: <OptOutScene />,link: urls.workflows('opt-outs'),},+ ...(suppressionListEnabled+ ? [+ {+ label: 'Suppression list',+ key: 'suppression' as const,+ content: <SuppressionScene />,+ link: urls.workflows('suppression'),+ },+ ]+ : []),]return (diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b6c6999d9e82..2de38fe33db6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8037,6 +8037,14 @@ export namespace Schemas {uploads: UploadTarget[];}+ export interface AddSuppressionRequest {+ /**+ * The email address to suppress. Will not receive any messages until removed.+ * @maxLength 512+ */+ identifier: string;+ }+/*** Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.*/@@ -35625,6 +35633,58 @@ export namespace Schemas {preferences: unknown;}+ /**+ * * `BOUNCE` - Bounce+ * * `MANUAL` - Manual+ */+ export type MessageSuppressionSourceEnum = typeof MessageSuppressionSourceEnum[keyof typeof MessageSuppressionSourceEnum];+++ export const MessageSuppressionSourceEnum = {+ Bounce: 'BOUNCE',+ Manual: 'MANUAL',+ } as const;++ export interface MessageSuppression {+ /** Server-assigned UUID for this suppression entry. */+ readonly id: string;+ /** Normalized recipient email address. Suppression is keyed on this value, per team. */+ readonly identifier: string;+ /** How the entry landed on the list: `BOUNCE` for automatic (bounce-driven), `MANUAL` for user-added via the UI/API.+ *+ * * `BOUNCE` - Bounce+ * * `MANUAL` - Manual */+ readonly source: MessageSuppressionSourceEnum;+ /**+ * Human-readable reason for the suppression (e.g. 'Auto-suppressed after 5 consecutive soft bounces').+ * @nullable+ */+ readonly reason: string | null;+ /** Rolling count of consecutive soft bounces with no successful delivery in between. Reset to 0 on any successful delivery. Ignored for MANUAL entries. */+ readonly transient_bounce_count: number;+ /**+ * Timestamp of the most recent bounce, if any.+ * @nullable+ */+ readonly last_bounce_at: string | null;+ /**+ * SMTP diagnostic string from the most recent bounce (e.g. '550 5.1.1 user unknown'), kept for visibility.+ * @nullable+ */+ readonly last_bounce_diagnostic: string | null;+ /** Whether the address is actively suppressed. A BOUNCE row can exist while still only counting bounces (suppressed=false) before it crosses the threshold. */+ readonly suppressed: boolean;+ /**+ * Timestamp when the address was first suppressed.+ * @nullable+ */+ readonly suppressed_at: string | null;+ /** When the row was first created (first bounce or manual add). */+ readonly created_at: string;+ /** When the row was last touched by any write. */+ readonly updated_at: string;+ }+/*** * `liquid` - liquid*/@@ -38121,6 +38181,27 @@ export namespace Schemas {results: MessageCategory[];}+ /**+ * OpenAPI shape for the paginated suppressions response. Declared so drf-spectacular emits+ * the {count, next, previous, results} envelope on the generated client, rather than a bare+ * array — which the frontend actually receives at runtime.+ */+ export interface PaginatedMessageSuppression {+ /** Total number of suppressed recipients for the team. */+ count: number;+ /**+ * URL for the next page, or null on the last page.+ * @nullable+ */+ next: string | null;+ /**+ * URL for the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null;+ results: MessageSuppression[];+ }+export interface PaginatedMessageTemplateList {count: number;/** @nullable */@@ -77021,6 +77102,11 @@ export namespace Schemas {offset?: number;};+ export type MessagingSuppressionsSuppressionsRetrieveParams = {+ page?: number;+ page_size?: number;+ };+export type MessagingTemplatesListParams = {/*** Number of results to return per page.