Skip to content

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

feat(workflows): emit workflows engagement events from plugin-server (#60212)

Daniel Marchuk7692f0e4f5b9
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 59421a62c59a..403503feae31 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -129,6 +129,8 @@ export class CdpApi {
this.hogFunctionManager,
this.hogFlowManager,
services.hogFunctionMonitoringService,
+ services.capturedEventsService,
+ services.teamWorkflowsConfigService,
services.recipientsManager
)
this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index e606fd2f15d6..42172c22fad6 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -31,6 +31,7 @@ import { HogFunctionManagerService } from './services/managers/hog-function-mana
import { HogFunctionTemplateManagerService } from './services/managers/hog-function-template-manager.service'
import { 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 { EmailService } from './services/messaging/email.service'
import { RecipientPreferencesService } from './services/messaging/recipient-preferences.service'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
@@ -86,8 +87,10 @@ export interface CdpCoreServices {
hogFlowFunctionsService: HogFlowFunctionsService
recipientsManager: RecipientsManagerService
recipientPreferencesService: RecipientPreferencesService
+ teamWorkflowsConfigService: TeamWorkflowsConfigService
hogFlowExecutor: HogFlowExecutorService
hogFunctionMonitoringService: HogFunctionMonitoringService
+ capturedEventsService: CapturedEventsService
/** Per-invocation lifecycle row producer for the new runs/invocations UI + rerun path. */
hogInvocationResultsService: HogInvocationResultsService
/** Fans `CyclotronJobInvocationResult` batches across monitoring / warehouse / captured-events. */
@@ -376,6 +379,7 @@ export function createCdpCoreServices(
: null
const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const emailService = new EmailService(
{
sesAccessKeyId: config.SES_ACCESS_KEY_ID,
@@ -384,6 +388,7 @@ export function createCdpCoreServices(
sesEndpoint: config.SES_ENDPOINT,
},
deps.integrationManager,
+ teamWorkflowsConfigService,
config.ENCRYPTION_SALT_KEYS,
config.SITE_URL
)
@@ -451,8 +456,10 @@ export function createCdpCoreServices(
hogFlowFunctionsService,
recipientsManager,
recipientPreferencesService,
+ teamWorkflowsConfigService,
hogFlowExecutor,
hogFunctionMonitoringService,
+ capturedEventsService,
hogInvocationResultsService,
invocationResultsService,
nativeDestinationExecutorService,
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 24935ff1e5ca..5e3b913982e1 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -19,6 +19,7 @@ import { HogInputsService } from '../services/hog-inputs.service'
import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'
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 { EmailService } from '../services/messaging/email.service'
import { RecipientTokensService } from '../services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService, MonitoringOutput } from '../services/monitoring/hog-function-monitoring.service'
@@ -469,6 +470,7 @@ export function createHogTransformerService(
const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)
const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const emailService = new EmailService(
{
sesAccessKeyId: config.SES_ACCESS_KEY_ID,
@@ -477,6 +479,7 @@ export function createHogTransformerService(
sesEndpoint: config.SES_ENDPOINT,
},
deps.integrationManager,
+ teamWorkflowsConfigService,
config.ENCRYPTION_SALT_KEYS,
config.SITE_URL
)
diff --git a/nodejs/src/cdp/services/captured-events/captured-events.service.ts b/nodejs/src/cdp/services/captured-events/captured-events.service.ts
index 67c372f638d5..cba836fd3c06 100644
--- a/nodejs/src/cdp/services/captured-events/captured-events.service.ts
+++ b/nodejs/src/cdp/services/captured-events/captured-events.service.ts
@@ -38,6 +38,25 @@ export class CapturedEventsService {
capturedEventsPending.set(this.queuedEvents.length)
}
+ /**
+ * Resolve the team for a single event (to obtain the API token) and queue it.
+ * Used by code paths outside the invocation-result lifecycle, e.g. SES webhooks.
+ */
+ async queueEvent(event: { team_id: number } & Omit<InternalCaptureEvent, 'team_token'>): Promise<void> {
+ const team = await this.teamManager.getTeam(event.team_id)
+ if (!team) {
+ return
+ }
+ this.queuedEvents.push({
+ team_token: team.api_token,
+ event: event.event,
+ distinct_id: event.distinct_id,
+ timestamp: event.timestamp,
+ properties: event.properties,
+ })
+ capturedEventsPending.set(this.queuedEvents.length)
+ }
+
/**
* Extract `capturedPostHogEvents` from each result, resolve the team
* (to obtain the API token used by capture), and queue.
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 8aa7428a3782..ad90f4124fd5 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -8,6 +8,7 @@ import { logger } from '~/utils/logger'
import { HogExecutorService } from '../../../src/cdp/services/hog-executor.service'
import { 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 { RecipientTokensService } from '../../../src/cdp/services/messaging/recipient-tokens.service'
import { CyclotronJobInvocationHogFunction, HogFunctionType } from '../../../src/cdp/types'
@@ -60,6 +61,7 @@ describe('Hog Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
@@ -1938,6 +1940,7 @@ describe('Hog Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index 18e51a755f21..5199bf5b2edf 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -15,6 +15,7 @@ import { CyclotronJobInvocationHogFlow, DBHogFunctionTemplate } from '../../../t
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 { EmailService } from '../../messaging/email.service'
import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'
import { RecipientTokensService } from '../../messaging/recipient-tokens.service'
@@ -49,6 +50,7 @@ describe('HogFunctionHandler', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index a0eb0d65d959..ea852f62d8d5 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -20,6 +20,7 @@ import { EmailService } from '../messaging/email.service'
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 { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
import { HogFlowExecutorService, createHogFlowInvocation } from './hogflow-executor.service'
import { HogFlowFunctionsService } from './hogflow-functions.service'
@@ -69,6 +70,7 @@ describe('Hogflow Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
@@ -1877,6 +1879,7 @@ describe('Hogflow Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
),
@@ -2075,6 +2078,7 @@ describe('Hogflow Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
),
@@ -2109,6 +2113,7 @@ describe('Hogflow Executor', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
),
diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts
new file mode 100644
index 000000000000..d82102b0862e
--- /dev/null
+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts
@@ -0,0 +1,59 @@
+import { PostgresRouter, PostgresUse } from '../../../utils/db/postgres'
+import { LazyLoader } from '../../../utils/lazy-loader'
+
+export type TeamWorkflowsConfig = {
+ capture_workflows_engagement_events: boolean
+}
+
+const DEFAULT_CONFIG: TeamWorkflowsConfig = {
+ capture_workflows_engagement_events: false,
+}
+
+/**
+ * Reads `workflows_teamworkflowsconfig` rows. The Django side creates a row
+ * lazily via `get_or_create_team_extension`, so a missing row means the team
+ * has never opted in — return the default (engagement event capture off).
+ */
+export class TeamWorkflowsConfigService {
+ private lazyLoader: LazyLoader<TeamWorkflowsConfig>
+
+ constructor(private postgres: PostgresRouter) {
+ this.lazyLoader = new LazyLoader({
+ name: 'team_workflows_config',
+ refreshAgeMs: 2 * 60 * 1000,
+ refreshJitterMs: 30 * 1000,
+ loader: async (teamIds) => await this.fetchConfigs(teamIds),
+ })
+ }
+
+ public async get(teamId: number): Promise<TeamWorkflowsConfig> {
+ return (await this.lazyLoader.get(String(teamId))) ?? DEFAULT_CONFIG
+ }
+
+ public async shouldCaptureEngagementEvents(teamId: number): Promise<boolean> {
+ const config = await this.get(teamId)
+ return config.capture_workflows_engagement_events
+ }
+
+ private async fetchConfigs(teamIds: string[]): Promise<Record<string, TeamWorkflowsConfig>> {
+ const result = await this.postgres.query<{ team_id: number; capture_workflows_engagement_events: boolean }>(
+ PostgresUse.COMMON_READ,
+ `SELECT team_id, capture_workflows_engagement_events
+ FROM workflows_teamworkflowsconfig
+ WHERE team_id = ANY($1)`,
+ [teamIds.map(Number)],
+ 'fetch-team-workflows-configs'
+ )
+
+ const configs: Record<string, TeamWorkflowsConfig> = {}
+ for (const teamId of teamIds) {
+ configs[teamId] = DEFAULT_CONFIG
+ }
+ for (const row of result.rows) {
+ configs[String(row.team_id)] = {
+ capture_workflows_engagement_events: row.capture_workflows_engagement_events,
+ }
+ }
+ return configs
+ }
+}
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
index 8eab42b80ae1..fcbfcb9761d8 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
@@ -10,14 +10,23 @@ import { setupExpressApp } from '~/api/router'
import { insertHogFunction } from '~/cdp/_tests/fixtures'
import { CdpApi } from '~/cdp/cdp-api'
import { HogFunctionType } from '~/cdp/types'
+import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
import { KAFKA_APP_METRICS_2 } from '~/config/kafka-topics'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
+import { waitForExpect } from '~/tests/helpers/expectations'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { closeHub, createHub } from '~/utils/db/hub'
+import * as envUtils from '~/utils/env-utils'
import { Hub, Team } from '../../../types'
-import { PIXEL_GIF, addTrackingToEmail, decodeHtmlEntitiesInHref } from './email-tracking.service'
-import { generateEmailTrackingCode } from './helpers/tracking-code'
+import {
+ METRIC_NAME_TO_EVENT_NAME,
+ PIXEL_GIF,
+ addTrackingToEmail,
+ decodeHtmlEntitiesInHref,
+ resolveEmailEngagementDistinctId,
+} from './email-tracking.service'
+import { generateEmailTrackingCode, parseEmailTrackingCode } from './helpers/tracking-code'
describe('EmailTrackingService', () => {
let hub: Hub
@@ -29,6 +38,7 @@ describe('EmailTrackingService', () => {
team = await getFirstTeam(hub.postgres)
mockFetch.mockClear()
+ mockProducerObserver.resetKafkaProducer()
})
afterEach(async () => {
@@ -88,6 +98,34 @@ describe('EmailTrackingService', () => {
expect(out).toContain('href="java&#x73;cript:alert(1)"')
expect(out).not.toContain('target=')
})
+
+ const invocationWithDistinctId = {
+ functionId: 'fn-1',
+ id: 'inv-1',
+ teamId: 1,
+ state: { globals: { event: { distinct_id: 'leaky-id' } } },
+ } as any
+ const phIdOf = (html: string): string => html.match(/ph_id=([A-Za-z0-9._-]+)/)![1]
+
+ it('includes distinct_id in the public tracking URLs in dev/test', () => {
+ const out = addTrackingToEmail('<body><a href="https://example.com">x</a></body>', invocationWithDistinctId)
+ expect(parseEmailTrackingCode(phIdOf(out))?.distinctId).toBe('leaky-id')
+ })
+
+ it('omits distinct_id from the public tracking URLs in production (Referer-leak guard)', () => {
+ const devSpy = jest.spyOn(envUtils, 'isDevEnv').mockReturnValue(false)
+ const testSpy = jest.spyOn(envUtils, 'isTestEnv').mockReturnValue(false)
+ try {
+ const out = addTrackingToEmail(
+ '<body><a href="https://example.com">x</a></body>',
+ invocationWithDistinctId
+ )
+ expect(parseEmailTrackingCode(phIdOf(out))?.distinctId).toBeUndefined()
+ } finally {
+ devSpy.mockRestore()
+ testSpy.mockRestore()
+ }
+ })
})
describe('decodeHtmlEntitiesInHref', () => {
@@ -109,7 +147,6 @@ describe('EmailTrackingService', () => {
})
describe('api', () => {
- // NOTE: These tests are done via the CdpApi router so we can get full coverage of the code
let api: CdpApi
let app: express.Application
let hogFunction: HogFunctionType
@@ -132,11 +169,11 @@ describe('EmailTrackingService', () => {
server.close()
})
- // Metrics are tracked via SES webhooks, not the direct pixel/redirect handlers,
- // to avoid double counting. These tests verify the handlers still serve correct
- // responses without recording metrics.
+ // In production, opens/clicks come from SES webhooks. In dev/test (which jest runs as)
+ // there is no SES, so the pixel/redirect handlers themselves emit the metric — these
+ // tests run in test env and exercise that path.
describe('handleEmailTrackingRedirect', () => {
- it('should redirect to the target url without recording metrics', async () => {
+ it('should redirect to the target url and record an email_link_clicked metric', async () => {
const phId = generateEmailTrackingCode({
functionId: hogFunction.id,
id: invocationId,
@@ -146,8 +183,15 @@ describe('EmailTrackingService', () => {
expect(res.status).toBe(302)
expect(res.headers.location).toBe('https://example.com')
- const messages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
- expect(messages).toHaveLength(0)
+ await waitForExpect(() => {
+ const messages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ expect(messages).toHaveLength(1)
+ expect(messages[0].value).toMatchObject({
+ team_id: team.id,
+ metric_name: 'email_link_clicked',
+ metric_kind: 'email',
+ })
+ })
})
it('should return 404 if the target is not provided', async () => {
@@ -158,11 +202,14 @@ describe('EmailTrackingService', () => {
})
const res = await supertest(app).get(`/public/m/redirect?ph_id=${phId}`)
expect(res.status).toBe(404)
+
+ const messages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ expect(messages).toHaveLength(0)
})
})
describe('email tracking pixel', () => {
- it('should return a gif image without recording metrics', async () => {
+ it('should return a gif image and record an email_opened metric', async () => {
const phId = generateEmailTrackingCode({
functionId: hogFunction.id,
id: invocationId,
@@ -173,8 +220,15 @@ describe('EmailTrackingService', () => {
expect(res.headers['content-type']).toBe('image/gif')
expect(res.body).toEqual(PIXEL_GIF)
- const messages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
- expect(messages).toHaveLength(0)
+ await waitForExpect(() => {
+ const messages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ expect(messages).toHaveLength(1)
+ expect(messages[0].value).toMatchObject({
+ team_id: team.id,
+ metric_name: 'email_opened',
+ metric_kind: 'email',
+ })
+ })
})
it('should return a 200 even if the tracking code is invalid', async () => {
@@ -188,4 +242,52 @@ describe('EmailTrackingService', () => {
})
})
})
+
+ describe('resolveEmailEngagementDistinctId', () => {
+ const buildInvocation = (
+ globals: Partial<NonNullable<CyclotronJobInvocationHogFunction['state']['globals']>>
+ ): CyclotronJobInvocationHogFunction =>
+ ({
+ state: { globals: globals as any },
+ }) as CyclotronJobInvocationHogFunction
+
+ it.each([
+ {
+ name: 'uses event.distinct_id (native for event-triggered; backfilled by the worker for batch)',
+ globals: { event: { distinct_id: 'user-from-event' } },
+ expected: 'user-from-event',
+ },
+ {
+ // Empty event.distinct_id means no distinct_id resolved upstream; we must NOT derive
+ // one from globals.person — person.id is the uuid (phantom person) and person.distinct_id
+ // is the same source already folded into event.distinct_id.
+ name: 'ignores globals.person and returns undefined when event.distinct_id is empty',
+ globals: { event: { distinct_id: '' }, person: { id: 'person-uuid', distinct_id: 'person-distinct' } },
+ expected: undefined,
+ },
+ {
+ name: 'returns undefined when there is no event',
+ globals: {},
+ expected: undefined,
+ },
+ ])('$name', ({ globals, expected }) => {
+ expect(resolveEmailEngagementDistinctId(buildInvocation(globals as any))).toBe(expected)
+ })
+ })
+
+ describe('METRIC_NAME_TO_EVENT_NAME allowlist', () => {
+ it('maps every email metric we want to surface and excludes internal ones', () => {
+ // Adding entries here changes the set of events customers can build insights on top of —
+ // treat as a public-API change. Removing entries leaves customers with broken insights.
+ expect(METRIC_NAME_TO_EVENT_NAME).toEqual({
+ email_sent: '$workflows_email_sent',
+ email_failed: '$workflows_email_failed',
+ email_delivered: '$workflows_email_delivered',
+ email_opened: '$workflows_email_opened',
+ email_link_clicked: '$workflows_email_link_clicked',
+ email_bounced: '$workflows_email_bounced',
+ email_blocked: '$workflows_email_blocked',
+ })
+ })
+ })
})
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index b8b5b51ec651..ac0d8a328836 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -4,12 +4,15 @@ import express from 'ultimate-express'
import { ModifiedRequest } from '~/api/router'
import { CyclotronJobInvocationHogFunction, MinimalAppMetric } from '~/cdp/types'
import { defaultConfig } from '~/config/config'
+import { isDevEnv, isTestEnv } from '~/utils/env-utils'
import { parseJSON } from '~/utils/json-parse'
import { logger } from '../../../utils/logger'
+import { CapturedEventsService } from '../captured-events/captured-events.service'
import { HogFlowManagerService } from '../hogflows/hogflow-manager.service'
import { HogFunctionManagerService } from '../managers/hog-function-manager.service'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
+import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
import { HogFunctionMonitoringService } from '../monitoring/hog-function-monitoring.service'
import { SesWebhookHandler } from './helpers/ses'
import {
@@ -35,10 +38,40 @@ const emailTrackingErrorsCounter = new Counter({
labelNames: ['error_type', 'source'],
})
+// Allowlist of metrics that surface as PostHog events when engagement-event capture is enabled.
+// Metrics not in this map are deliberately ignored (no `$messaging_${metricName}` fallback) so a new
+// internal metric can't silently leak into customers' event streams.
+export const METRIC_NAME_TO_EVENT_NAME: Partial<Record<MinimalAppMetric['metric_name'], string>> = {
+ email_sent: '$workflows_email_sent',
+ email_failed: '$workflows_email_failed',
+ email_delivered: '$workflows_email_delivered',
+ email_opened: '$workflows_email_opened',
+ email_link_clicked: '$workflows_email_link_clicked',
+ email_bounced: '$workflows_email_bounced',
+ email_blocked: '$workflows_email_blocked',
+}
+
+/**
+ * Resolve the identifier to attribute engagement events to. `event.distinct_id` is the canonical
+ * source for both flows: event-triggered runs carry it from the trigger event, and batch/scheduled
+ * runs have it backfilled by the cyclotron worker from the person's resolved distinct_id (see the
+ * `getCyclotronPerson` backfill in cdp-cyclotron-worker-hogflow.consumer.ts). We deliberately do
+ * NOT derive it from `globals.person` — `person.id` is the person UUID, which was never ingested as
+ * a distinct_id and would mint a phantom person, and `person.distinct_id` is the same source already
+ * folded into `event.distinct_id` upstream. If there's no distinct_id we skip capture rather than
+ * emit an unattributable event.
+ */
+export const resolveEmailEngagementDistinctId = (
+ invocation: Pick<CyclotronJobInvocationHogFunction, 'state'>
+): string | undefined => {
+ return invocation.state?.globals?.event?.distinct_id || undefined
+}
+
export const generateTrackingRedirectUrl = (
invocation: Pick<CyclotronJobInvocationHogFunction, 'functionId' | 'id' | 'teamId'> & {
parentRunId?: string | null
state?: { actionId?: string }
+ distinctId?: string
},
targetUrl: string,
isTest = false
@@ -69,7 +102,13 @@ export const addTrackingToEmail = (
invocation: CyclotronJobInvocationHogFunction,
isTest = false
): string => {
- const trackingUrl = generateEmailTrackingPixelUrl(invocation, isTest)
+ // Only carry distinct_id in the in-email pixel/redirect URLs in dev/test, where those handlers
+ // record metrics. In production they don't (SES webhooks own open/click attribution via the
+ // signed header), so embedding distinct_id in the public `ph_id` would be unused — and worse,
+ // a tracked-link click could leak the recipient identifier to the destination via the Referer.
+ const distinctId = isDevEnv() || isTestEnv() ? resolveEmailEngagementDistinctId(invocation) : undefined
+ const trackingInvocation = { ...invocation, distinctId }
+ const trackingUrl = generateEmailTrackingPixelUrl(trackingInvocation, isTest)
html = html.replace(LINK_REGEX, (m, d, s, u) => {
const href = decodeHtmlEntitiesInHref(d || s || u || '')
@@ -78,7 +117,7 @@ export const addTrackingToEmail = (
if (/^\s*javascript:/i.test(href)) {
return m
}
- const tracked = generateTrackingRedirectUrl(invocation, href, isTest)
+ const tracked = generateTrackingRedirectUrl(trackingInvocation, href, isTest)
// replace just the href in the original tag to preserve other attributes
return m.replace(/\bhref\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s]+)/i, `href="${tracked}"`)
@@ -96,6 +135,8 @@ export class EmailTrackingService {
private hogFunctionManager: HogFunctionManagerService,
private hogFlowManager: HogFlowManagerService,
private hogFunctionMonitoringService: HogFunctionMonitoringService,
+ private capturedEventsService: CapturedEventsService,
+ private teamWorkflowsConfigService: TeamWorkflowsConfigService,
private recipientsManager: RecipientsManagerService
) {
this.sesWebhookHandler = new SesWebhookHandler()
@@ -106,15 +147,21 @@ export class EmailTrackingService {
invocationId,
actionId,
parentRunId,
+ distinctId,
metricName,
source,
+ properties,
+ timestamp,
}: {
functionId?: string
invocationId?: string
actionId?: string
parentRunId?: string
+ distinctId?: string
metricName: MinimalAppMetric['metric_name']
source: 'direct' | 'ses'
+ properties?: Record<string, unknown>
+ timestamp?: string
}): Promise<void> {
if (!functionId || !invocationId) {
logger.error('[EmailTrackingService] trackMetric: Invalid custom ID', {
@@ -159,6 +206,22 @@ export class EmailTrackingService {
hogFlow ? 'hog_flow' : 'hog_function'
)
+ const eventName = METRIC_NAME_TO_EVENT_NAME[metricName]
+ if (eventName && distinctId && (await this.teamWorkflowsConfigService.shouldCaptureEngagementEvents(teamId))) {
+ await this.capturedEventsService.queueEvent({
+ team_id: teamId,
+ event: eventName,
+ distinct_id: distinctId,
+ timestamp,
+ properties: {
+ $workflow_id: appSourceId,
+ $workflow_action_id: actionId,
+ ...properties,
+ },
+ })
+ await this.capturedEventsService.flush()
+ }
+
await this.hogFunctionMonitoringService.flush()
trackingEventsCounter.inc({ event_type: metricName, source })
@@ -187,8 +250,11 @@ export class EmailTrackingService {
invocationId: metric.invocationId,
actionId: metric.actionId,
parentRunId: metric.parentRunId,
+ distinctId: metric.distinctId,
metricName: metric.metricName,
source: 'ses',
+ properties: metric.properties,
+ timestamp: metric.timestamp,
})
}
@@ -237,6 +303,7 @@ export class EmailTrackingService {
invocationId?: string
actionId?: string
parentRunId?: string
+ distinctId?: string
} {
// Support both combined ph_id format and legacy separate params
if (query.ph_id) {
@@ -249,6 +316,7 @@ export class EmailTrackingService {
invocationId: parsed?.invocationId,
actionId: parsed?.actionId,
parentRunId: parsed?.parentRunId,
+ distinctId: parsed?.distinctId,
}
}
return {
@@ -258,16 +326,22 @@ export class EmailTrackingService {
}
// NOTE: this is somewhat naieve. We should expand with UA checking for things like apple's tracking prevention etc.
- // Metrics are not recorded here because SES webhooks already track opens.
- // Recording here would double-count. The pixel is still served so email
- // clients that load it get a valid response.
- public handleEmailTrackingPixel(_req: ModifiedRequest, res: express.Response): void {
+ // In production, opens are tracked via SES webhooks — recording here would double-count.
+ // In dev/test (where maildev replaces SES and no webhooks come back), we fire the
+ // engagement event from the pixel handler so local testing produces real events.
+ public handleEmailTrackingPixel(req: ModifiedRequest, res: express.Response): void {
res.status(200).set('Content-Type', 'image/gif').send(PIXEL_GIF)
+
+ if (isDevEnv() || isTestEnv()) {
+ const params = this.parseTrackingParams(req.query as Record<string, any>)
+ void this.trackMetric({ ...params, metricName: 'email_opened', source: 'direct' }).catch((error) => {
+ logger.error('[EmailTrackingService] handleEmailTrackingPixel: trackMetric failed', { error })
+ })
+ }
}
- // Metrics are not recorded here because SES webhooks already track clicks.
- // Recording here would double-count. The redirect still works so users
- // reach their destination.
+ // Same rationale as handleEmailTrackingPixel: skip in production (SES webhooks own
+ // click tracking), but emit in dev/test where maildev never produces webhooks.
public handleEmailTrackingRedirect(req: ModifiedRequest, res: express.Response): void {
const { target } = req.query
@@ -277,5 +351,12 @@ export class EmailTrackingService {
}
res.redirect(target as string)
+
+ if (isDevEnv() || isTestEnv()) {
+ const params = this.parseTrackingParams(req.query as Record<string, any>)
+ void this.trackMetric({ ...params, metricName: 'email_link_clicked', source: 'direct' }).catch((error) => {
+ logger.error('[EmailTrackingService] handleEmailTrackingRedirect: trackMetric failed', { error })
+ })
+ }
}
}
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index a27d39737434..ecf82b0ed985 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -10,6 +10,7 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { closeHub, createHub } from '~/utils/db/hub'
import { Hub, Team } from '../../../types'
+import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'
import { MailDevAPI } from './helpers/maildev'
@@ -89,6 +90,7 @@ describe('EmailService', () => {
sesEndpoint: hub.SES_ENDPOINT,
},
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
@@ -102,6 +104,7 @@ describe('EmailService', () => {
const serviceWithoutSES = new EmailService(
{ sesAccessKeyId: '', sesSecretAccessKey: '', sesRegion: '', sesEndpoint: '' },
hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
hub.SITE_URL
)
@@ -363,7 +366,7 @@ describe('EmailService', () => {
to: [{ address: '[email protected]', name: 'Test User' }],
})
})
- it('should include tracking code in the email', async () => {
+ it('should include tracking code in the email with distinct_id', async () => {
invocation.queueParameters = createEmailParams({
html: '<body>Hi! <a href="https://example.com">Click me</a></body>',
})
@@ -423,7 +426,8 @@ describe('EmailService', () => {
expect(result.error).toBeUndefined()
expect(sendEmailSpy).toHaveBeenCalledTimes(1)
const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }
- // The SES tag carries the short unsigned code (no dot); the signed code rides in the header.
+ // The SES tag carries the short unsigned code (no dot); the signed code (with distinct_id)
+ // rides in the header.
expect(sentCommand.input).toMatchObject({
ConfigurationSetName: 'posthog-messaging',
Content: {
@@ -614,6 +618,9 @@ describe('EmailService', () => {
})
it('attaches the X-PostHog-Tracking-Code header carrying the full signed code', async () => {
+ // The header is the authoritative tracking-code carrier (the EmailTag is the
+ // bounded backwards-compat fallback). It rides on every outbound message,
+ // regardless of transactional vs. marketing category.
sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
invocation.hogFunction.metadata = { message_category_type: 'transactional' }
const result = await service.executeSendEmail(invocation)
@@ -623,7 +630,10 @@ describe('EmailService', () => {
(h: { Name: string }) => h.Name === 'X-PostHog-Tracking-Code'
)
expect(trackingHeader).toBeDefined()
- // The SES tag carries a different (shorter, unsigned) code so it stays under the 256-char cap.
+ expect(typeof trackingHeader.Value).toBe('string')
+ expect(trackingHeader.Value.length).toBeGreaterThan(0)
+ // The SES EmailTag carries a *different* (shorter, unsigned) code so it stays under the
+ // 256-char tag-value limit even when distinct_id is long.
expect(sentCommand.input.EmailTags[0].Value).not.toEqual(trackingHeader.Value)
})
@@ -632,5 +642,49 @@ describe('EmailService', () => {
const result = await service.executeSendEmail(invocation)
expect(result.error).toMatchInlineSnapshot(`"Failed to send email via SES: No messageId returned from SES"`)
})
+
+ it('should capture a $workflows_email_sent PostHog event on success', async () => {
+ // Engagement capture is team-opt-in; enable it for this team so the captured event is emitted.
+ jest.spyOn((service as any).teamWorkflowsConfigService, 'shouldCaptureEngagementEvents').mockResolvedValue(
+ true
+ )
+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
+ const result = await service.executeSendEmail(invocation)
+ expect(result.error).toBeUndefined()
+ expect(result.capturedPostHogEvents).toHaveLength(1)
+ expect(result.capturedPostHogEvents[0]).toMatchObject({
+ team_id: team.id,
+ distinct_id: 'distinct_id',
+ event: '$workflows_email_sent',
+ properties: {
+ $workflow_id: invocation.functionId,
+ $workflow_action_id: invocation.state.actionId,
+ $email_to: '[email protected]',
+ $email_subject: 'Test Subject',
+ },
+ })
+ })
+
+ it('does not capture a PostHog event when engagement capture is disabled for the team', async () => {
+ // Default config has capture_workflows_engagement_events=false, so even on success no event is queued.
+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
+ const result = await service.executeSendEmail(invocation)
+ expect(result.error).toBeUndefined()
+ expect(result.capturedPostHogEvents).toHaveLength(0)
+ })
+
+ it('should capture a $workflows_email_failed PostHog event on failure', async () => {
+ jest.spyOn((service as any).teamWorkflowsConfigService, 'shouldCaptureEngagementEvents').mockResolvedValue(
+ true
+ )
+ sendEmailSpy.mockRejectedValue(new Error('SES error'))
+ const result = await service.executeSendEmail(invocation)
+ expect(result.error).toBeDefined()
+ expect(result.capturedPostHogEvents).toHaveLength(1)
+ expect(result.capturedPostHogEvents[0]).toMatchObject({
+ event: '$workflows_email_failed',
+ distinct_id: 'distinct_id',
+ })
+ })
})
})
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 5bcfee0f6fe1..4a89d5a032d3 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -10,7 +10,8 @@ import { CyclotronInvocationQueueParametersEmailType } from '~/schema/cyclotron'
import { IntegrationManagerService } from '../managers/integration-manager.service'
import { RecipientManagerRecipient } from '../managers/recipients-manager.service'
-import { addTrackingToEmail } from './email-tracking.service'
+import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
+import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'
import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'
import { maybeAddPreheaderToEmail } from './helpers/preheader'
import {
@@ -108,6 +109,7 @@ export class EmailService {
constructor(
private sesConfig: EmailServiceConfig,
private integrationManager: IntegrationManagerService,
+ private teamWorkflowsConfigService: TeamWorkflowsConfigService,
encryptionSaltKeys: string,
siteUrl: string
) {
@@ -216,6 +218,26 @@ export class EmailService {
})
}
+ const distinctId = resolveEmailEngagementDistinctId(invocation)
+ if (
+ distinctId &&
+ !isTest &&
+ (await this.teamWorkflowsConfigService.shouldCaptureEngagementEvents(invocation.teamId))
+ ) {
+ result.capturedPostHogEvents.push({
+ team_id: invocation.teamId,
+ timestamp: new Date().toISOString(),
+ distinct_id: distinctId,
+ event: success ? '$workflows_email_sent' : '$workflows_email_failed',
+ properties: {
+ $workflow_id: invocation.functionId,
+ $workflow_action_id: invocation.state.actionId,
+ $email_to: params.to.email,
+ $email_subject: params.subject,
+ },
+ })
+ }
+
return result
}
@@ -275,10 +297,11 @@ export class EmailService {
if (!this.sesV2Client) {
throw new Error('SES is not configured - set SES_REGION and AWS credentials')
}
- const trackingCode = generateEmailTrackingCode(result.invocation, isTest)
- // Short carrier (unsigned) for the SES EmailTag — guaranteed under the 256-char tag-value
- // limit. Legacy backwards-compat carrier only; the full signed code (with isTest) rides in
- // the header below, which the webhook reads first.
+ const distinctId = resolveEmailEngagementDistinctId(result.invocation)
+ // Full signed code (with distinct_id + isTest) rides in the header; the short unsigned
+ // carrier (no distinct_id/isTest) goes in the SES EmailTag, guaranteed under the 256-char
+ // tag-value limit. The webhook reads the header first and only falls back to the tag.
+ const trackingCode = generateEmailTrackingCode({ ...result.invocation, distinctId }, isTest)
const shortTrackingCode = generateShortEmailTrackingCode(result.invocation)
const htmlBody = params.html
@@ -321,9 +344,9 @@ export class EmailService {
}
// Authoritative tracking-code carrier: a custom MIME header. Header values aren't
- // 256-char-bounded the way SES tag values are, so they fit the signed code. The
- // configuration set's event destination needs `IncludeOriginalHeaders: true` for the
- // webhook to surface this header.
+ // 256-char-bounded the way SES tag values are, so they safely carry the signed code
+ // (with distinct_id). The configuration set's event destination needs
+ // `IncludeOriginalHeaders: true` for the webhook to surface this header.
const trackingHeader: MessageHeader = { Name: TRACKING_CODE_HEADER_NAME, Value: trackingCode }
const isTransactionalEmail = result.invocation.hogFunction?.metadata?.message_category_type === 'transactional'
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index 910293171f58..de4ba8020b58 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -10,13 +10,15 @@ describe('SesWebhookHandler', () => {
handler = new SesWebhookHandler()
})
- // Mirrors what the sender writes: the custom header carries the full signed code (the
- // authoritative source), the SES tag carries the short unsigned code as a fallback.
+ // Mirrors what the sender writes: the custom header carries the full signed code (including
+ // distinct_id, the authoritative source), the SES tag carries the short unsigned code
+ // (no distinct_id) as a fallback. The parser prefers the header.
const baseInvocation = {
functionId: 'abc123',
id: 'inv456',
teamId: 1,
state: { actionId: 'act789' },
+ distinctId: 'user-123',
} as const
const baseMail = {
@@ -50,12 +52,32 @@ describe('SesWebhookHandler', () => {
functionId: 'abc123',
invocationId: 'inv456',
actionId: 'act789',
+ distinctId: 'user-123',
metricName: 'email_opened',
+ properties: { $email_to: '[email protected]' },
+ timestamp: '2025-10-03T12:01:00Z',
},
])
})
- it('parses a raw Click event', async () => {
+ it('includes $email_subject from the SES commonHeaders', async () => {
+ const mailWithSubject = { ...baseMail, commonHeaders: { subject: 'Welcome aboard' } }
+ const body = [
+ {
+ eventType: 'Open',
+ mail: mailWithSubject,
+ open: { ipAddress: '1.2.3.4', userAgent: 'UA', timestamp: '2025-10-03T12:01:00Z' },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.status).toBe(200)
+ expect(result.metrics?.[0].properties).toMatchObject({
+ $email_to: '[email protected]',
+ $email_subject: 'Welcome aboard',
+ })
+ })
+
+ it('parses a raw Click event with link URL', async () => {
const body = [
{
eventType: 'Click',
@@ -71,6 +93,72 @@ describe('SesWebhookHandler', () => {
const result = await handler.handleWebhook({ body, headers: {} })
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_link_clicked')
+ expect(result.metrics?.[0].distinctId).toBe('user-123')
+ expect(result.metrics?.[0].properties).toEqual({
+ $email_to: '[email protected]',
+ $link_url: 'https://example.com',
+ })
+ expect(result.metrics?.[0].timestamp).toBe('2025-10-03T12:02:00Z')
+ })
+
+ it('parses tracking code from header only when SES tag is absent', async () => {
+ // Simulates a future state where the EmailTag backwards-compat carrier has been removed.
+ const headerOnlyMail = {
+ ...baseMail,
+ tags: undefined,
+ }
+ const body = [
+ {
+ eventType: 'Open',
+ mail: headerOnlyMail,
+ open: { ipAddress: '1.2.3.4', userAgent: 'UA', timestamp: '2025-10-03T12:01:00Z' },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.status).toBe(200)
+ expect(result.metrics?.[0].functionId).toBe('abc123')
+ expect(result.metrics?.[0].invocationId).toBe('inv456')
+ expect(result.metrics?.[0].distinctId).toBe('user-123')
+ })
+
+ it('falls back to SES tag when the custom header is absent (in-flight backwards compat)', async () => {
+ // Simulates a webhook for a message sent before the header carrier was rolled out,
+ // or arriving from an environment where IncludeOriginalHeaders is not yet enabled
+ // on the SES configuration set. The tag still carries the (pre-distinct_id) shape.
+ const tagOnlyMail = {
+ ...baseMail,
+ headers: undefined,
+ }
+ const body = [
+ {
+ eventType: 'Open',
+ mail: tagOnlyMail,
+ open: { ipAddress: '1.2.3.4', userAgent: 'UA', timestamp: '2025-10-03T12:01:00Z' },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.status).toBe(200)
+ expect(result.metrics?.[0].functionId).toBe('abc123')
+ expect(result.metrics?.[0].invocationId).toBe('inv456')
+ // distinct_id is omitted because the short tag carrier doesn't include it.
+ expect(result.metrics?.[0].distinctId).toBeUndefined()
+ })
+
+ it('prefers the custom header over the SES tag when both are present', async () => {
+ // Header carries the canonical (full) code; tag carries the short code as a fallback.
+ // The parser must read from the header so distinct_id is recovered.
+ const result = await handler.handleWebhook({
+ body: [
+ {
+ eventType: 'Open',
+ mail: baseMail,
+ open: { ipAddress: '1.2.3.4', userAgent: 'UA', timestamp: '2025-10-03T12:01:00Z' },
+ },
+ ],
+ headers: {},
+ })
+ expect(result.status).toBe(200)
+ expect(result.metrics?.[0].distinctId).toBe('user-123')
})
it('skips Send events (email_sent is recorded synchronously, not from webhooks)', async () => {
@@ -171,7 +259,10 @@ describe('SesWebhookHandler', () => {
functionId: 'abc123',
invocationId: 'inv456',
actionId: 'act789',
+ distinctId: 'user-123',
metricName: 'email_delivered',
+ properties: { $email_to: '[email protected]' },
+ timestamp: '2025-10-03T12:03:00Z',
},
])
})
@@ -194,6 +285,7 @@ describe('SesWebhookHandler', () => {
const result = await handler.handleWebhook({ body, headers: {} })
expect(result.status).toBe(200)
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]'] }])
})
@@ -215,6 +307,7 @@ describe('SesWebhookHandler', () => {
const result = await handler.handleWebhook({ body, headers: {} })
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_bounced')
+ expect(result.metrics?.[0].distinctId).toBe('user-123')
expect(result.optOutRecipients).toEqual([])
})
@@ -257,9 +350,10 @@ describe('SesWebhookHandler', () => {
const result = await handler.handleWebhook({ body, headers: {} })
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_blocked')
+ expect(result.metrics?.[0].distinctId).toBe('user-123')
})
- it('returns 200 and no metrics if tracking code is missing', async () => {
+ it('returns 200 and no metrics if tracking code is missing from both carriers', async () => {
const body = [
{
eventType: 'Open',
@@ -345,7 +439,9 @@ describe('SesWebhookHandler', () => {
const mailWithParentRun = {
...baseMail,
headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(batchInvocation) }],
- tags: { ph_id: [generateShortEmailTrackingCode(batchInvocation)] },
+ tags: {
+ ph_id: [generateShortEmailTrackingCode(batchInvocation)],
+ },
}
const body = [
{
@@ -363,6 +459,8 @@ describe('SesWebhookHandler', () => {
actionId: 'email-action',
parentRunId: 'batch-run-id',
metricName: 'email_opened',
+ properties: { $email_to: '[email protected]' },
+ timestamp: '2025-10-03T12:01:00Z',
},
])
})
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 1d8ae6d8b652..043a587e925d 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -40,6 +40,7 @@ const SesMailSchema = z.object({
destination: z.array(z.string()),
headersTruncated: z.boolean().optional(),
headers: z.array(z.object({ name: z.string(), value: z.string() })).optional(),
+ commonHeaders: z.object({ subject: z.string().optional() }).passthrough().optional(),
tags: z.record(z.string(), z.array(z.string())).optional(), // your message tags: { user_id: ["u_123"] }
})
@@ -314,7 +315,10 @@ export class SesWebhookHandler {
invocationId?: string
actionId?: string
parentRunId?: string
+ distinctId?: string
metricName: MinimalAppMetric['metric_name']
+ properties?: Record<string, any>
+ timestamp?: string
}[]
optOutRecipients?: {
teamId?: string
@@ -372,7 +376,10 @@ export class SesWebhookHandler {
invocationId?: string
actionId?: string
parentRunId?: string
+ distinctId?: string
metricName: MinimalAppMetric['metric_name']
+ properties?: Record<string, any>
+ timestamp?: string
}[] = []
const optOutRecipients: {
teamId?: string
@@ -381,9 +388,9 @@ export class SesWebhookHandler {
for (const rec of records) {
logger.info('[SesWebhookHandler] processing record', { rec })
- // Prefer the custom MIME header (carries the signed code, unbounded). Fall back to the
- // SES EmailTag for messages sent before the header carrier was added, or where the
- // configuration set hasn't enabled `IncludeOriginalHeaders`.
+ // Prefer the custom MIME header (carries the full signed code including distinct_id,
+ // unbounded). Fall back to the SES EmailTag for messages sent before the header carrier
+ // was added, or where the configuration set hasn't enabled `IncludeOriginalHeaders`.
const headerValue = rec.mail.headers?.find(
(h) => h.name.toLowerCase() === TRACKING_CODE_HEADER_NAME.toLowerCase()
)?.value
@@ -392,7 +399,7 @@ export class SesWebhookHandler {
if (parsedCode) {
trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })
}
- const { functionId, invocationId, teamId, actionId, parentRunId, isTest } = parsedCode || {}
+ const { functionId, invocationId, teamId, actionId, parentRunId, distinctId, isTest } = parsedCode || {}
if (!functionId && !invocationId) {
logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })
@@ -404,7 +411,39 @@ export class SesWebhookHandler {
// their delivery/open/click metrics — otherwise a draft/never-enabled workflow shows
// email activity in its Metrics tab. Bounce-driven opt-outs below still apply.
if (metricName && !isTest) {
- metrics.push({ functionId, invocationId, actionId, parentRunId, metricName })
+ const properties: Record<string, any> = {
+ $email_to: rec.mail.destination?.[0],
+ $email_subject: rec.mail.commonHeaders?.subject,
+ }
+
+ // Each SES event detail carries its own timestamp (open.timestamp, click.timestamp, etc.)
+ // — prefer those over the webhook receipt time so the event reflects when the action
+ // actually happened, not when AWS got around to delivering the notification.
+ let timestamp: string | undefined
+ if ('open' in rec && rec.open) {
+ timestamp = rec.open.timestamp
+ } else if ('click' in rec && rec.click) {
+ timestamp = rec.click.timestamp
+ properties.$link_url = rec.click.link
+ } else if ('delivery' in rec && rec.delivery) {
+ timestamp = rec.delivery.timestamp
+ } else if ('bounce' in rec && rec.bounce) {
+ timestamp = rec.bounce.timestamp
+ } else if ('complaint' in rec && rec.complaint) {
+ timestamp = rec.complaint.timestamp
+ }
+ timestamp = timestamp ?? rec.mail.timestamp
+
+ metrics.push({
+ functionId,
+ invocationId,
+ actionId,
+ parentRunId,
+ distinctId,
+ metricName,
+ properties,
+ timestamp,
+ })
}
// Opt out recipients on permanent bounces
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
index c6dd97eb8c1d..765244d487d8 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
@@ -2,8 +2,8 @@ import { defaultConfig } from '~/config/config'
import { generateEmailTrackingCode, generateShortEmailTrackingCode, parseEmailTrackingCode } from './tracking-code'
-// Hand-encode a raw payload the same way generateEmailTrackingCode does, so we can test
-// pre-fix legacy shapes (4-segment) without pulling in the generator.
+// Hand-encode a raw payload the same way the generators do, so we can test pre-fix legacy
+// (unsigned) shapes without pulling in the generator.
const encodeRaw = (payload: string): string =>
Buffer.from(payload, 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
@@ -11,13 +11,15 @@ describe('email tracking code', () => {
describe('parseEmailTrackingCode', () => {
it.each([
{
- name: 'roundtrips all invocation fields including parentRunId',
+ // Generated codes are signed in the test env (ENCRYPTION_SALT_KEYS is set).
+ name: 'roundtrips all invocation fields including distinctId (signed)',
encoded: generateEmailTrackingCode({
functionId: 'fn-1',
id: 'inv-2',
teamId: 3,
parentRunId: 'batch-4',
state: { actionId: 'act-5' },
+ distinctId: '[email protected]',
}),
expected: {
functionId: 'fn-1',
@@ -26,6 +28,7 @@ describe('email tracking code', () => {
actionId: 'act-5',
parentRunId: 'batch-4',
isTest: false,
+ distinctId: '[email protected]',
format: 'signed',
},
},
@@ -38,6 +41,7 @@ describe('email tracking code', () => {
teamId: 3,
parentRunId: 'batch-4',
state: { actionId: 'act-5' },
+ distinctId: '[email protected]',
},
true
),
@@ -48,6 +52,7 @@ describe('email tracking code', () => {
actionId: 'act-5',
parentRunId: 'batch-4',
isTest: true,
+ distinctId: '[email protected]',
format: 'signed',
},
},
@@ -62,11 +67,31 @@ describe('email tracking code', () => {
actionId: undefined,
parentRunId: undefined,
isTest: true,
+ distinctId: undefined,
format: 'signed',
},
},
{
- name: 'omits parentRunId when not supplied',
+ name: 'roundtrips with UUID distinctId (signed)',
+ encoded: generateEmailTrackingCode({
+ functionId: 'abc-123',
+ id: 'xyz-456',
+ teamId: 7,
+ distinctId: '550e8400-e29b-41d4-a716-446655440000',
+ }),
+ expected: {
+ functionId: 'abc-123',
+ invocationId: 'xyz-456',
+ teamId: '7',
+ actionId: undefined,
+ parentRunId: undefined,
+ isTest: false,
+ distinctId: '550e8400-e29b-41d4-a716-446655440000',
+ format: 'signed',
+ },
+ },
+ {
+ name: 'omits parentRunId and distinctId when not supplied (signed)',
encoded: generateEmailTrackingCode({
functionId: 'fn-1',
id: 'inv-2',
@@ -80,9 +105,32 @@ describe('email tracking code', () => {
actionId: 'act-5',
parentRunId: undefined,
isTest: false,
+ distinctId: undefined,
format: 'signed',
},
},
+ {
+ // The short code (SES tag carrier) is never signed and omits distinctId/isTest.
+ name: 'parses the unsigned short code used for the SES tag',
+ encoded: generateShortEmailTrackingCode({
+ functionId: 'fn-1',
+ id: 'inv-2',
+ teamId: 3,
+ parentRunId: 'batch-4',
+ state: { actionId: 'act-5' },
+ distinctId: '[email protected]',
+ }),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: 'batch-4',
+ isTest: false,
+ distinctId: undefined,
+ format: 'unsigned',
+ },
+ },
{
// Webhooks for emails already in flight when the fix deploys must still parse.
name: 'parses legacy 4-segment unsigned codes emitted before parentRunId existed',
@@ -94,11 +142,12 @@ describe('email tracking code', () => {
actionId: 'act-5',
parentRunId: undefined,
isTest: false,
+ distinctId: undefined,
format: 'unsigned',
},
},
{
- name: 'parses legacy 5-segment unsigned codes emitted before signing existed',
+ name: 'parses legacy 5-segment unsigned codes emitted before isTest/distinctId existed',
encoded: encodeRaw('fn-1:inv-2:3:act-5:batch-4'),
expected: {
functionId: 'fn-1',
@@ -107,6 +156,38 @@ describe('email tracking code', () => {
actionId: 'act-5',
parentRunId: 'batch-4',
isTest: false,
+ distinctId: undefined,
+ format: 'unsigned',
+ },
+ },
+ {
+ // Deployed master codes carry isTest at position 6 and no distinctId — must keep parsing.
+ name: 'parses legacy 6-segment codes with isTest at position 6 and no distinctId',
+ encoded: encodeRaw('fn-1:inv-2:3:act-5:batch-4:1'),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: 'batch-4',
+ isTest: true,
+ distinctId: undefined,
+ format: 'unsigned',
+ },
+ },
+ {
+ // Security: a forged UNSIGNED code carrying a distinct_id must NOT be trusted —
+ // distinct_id is only honored from signed codes, so this one parses with no distinctId.
+ name: 'ignores distinct_id on an unsigned (forged) code',
+ encoded: encodeRaw('fn-1:inv-2:3:act-5:batch-4::attacker-distinct-id'),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: 'batch-4',
+ isTest: false,
+ distinctId: undefined,
format: 'unsigned',
},
},
@@ -136,7 +217,7 @@ describe('email tracking code', () => {
const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
const sig = code.split('.')[1]
// Mint a different payload but reuse the original signature.
- const tampered = `${encodeRaw('attacker:invX:1::')}.${sig}`
+ const tampered = `${encodeRaw('attacker:invX:1:::')}.${sig}`
expect(parseEmailTrackingCode(tampered)).toBeNull()
})
@@ -176,7 +257,7 @@ describe('email tracking code', () => {
const original = defaultConfig.ENCRYPTION_SALT_KEYS
defaultConfig.ENCRYPTION_SALT_KEYS = 'old-key-aaaaaaaaaaaaaaaaaaaaaaaa'
const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
- // Rotation: new key first, old key kept for verification grace period.
+ // Rotation: new key first, old key kept for the verification grace period.
defaultConfig.ENCRYPTION_SALT_KEYS = 'new-key-bbbbbbbbbbbbbbbbbbbbbbbb,old-key-aaaaaaaaaaaaaaaaaaaaaaaa'
try {
expect(parseEmailTrackingCode(code)?.format).toBe('signed')
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
index 4d9a9be653c9..0ae423179fc9 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
@@ -65,6 +65,7 @@ function verifySignature(payload: string, signature: string): boolean {
type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functionId' | 'id' | 'teamId'> & {
parentRunId?: string | null
state?: { actionId?: string }
+ distinctId?: string
}
export type TrackingCodeFormat = 'signed' | 'unsigned'
@@ -78,6 +79,7 @@ export const parseEmailTrackingCode = (
actionId?: string
parentRunId?: string
isTest: boolean
+ distinctId?: string
format: TrackingCodeFormat
} | null => {
if (!encodedTrackingCode) {
@@ -100,7 +102,8 @@ export const parseEmailTrackingCode = (
try {
const decoded = fromBase64UrlSafe(payloadB64)
- const [functionId, invocationId, teamId, actionId, parentRunId, isTest] = decoded.split(':')
+ // distinctId is the trailing segment and may itself contain colons, so rejoin everything past it.
+ const [functionId, invocationId, teamId, actionId, parentRunId, isTest, ...distinctIdParts] = decoded.split(':')
if (!functionId || !invocationId) {
return null
}
@@ -111,6 +114,11 @@ export const parseEmailTrackingCode = (
actionId: actionId || undefined,
parentRunId: parentRunId || undefined,
isTest: isTest === '1',
+ // Only trust distinct_id from a signed code — the HMAC is its integrity guarantee. The
+ // legitimate unsigned tag never carries a distinct_id, so an unsigned code with one is
+ // forged; honoring it would let a crafted ph_id inject engagement events for any team.
+ distinctId:
+ format === 'signed' && distinctIdParts.length > 0 ? distinctIdParts.join(':') || undefined : undefined,
format,
}
} catch {
@@ -124,10 +132,12 @@ export const parseEmailTrackingCode = (
export const generateEmailTrackingCode = (invocation: TrackingInvocation, isTest = false): string => {
const actionId = invocation.state?.actionId ?? ''
const parentRunId = invocation.parentRunId ?? ''
- // isTest marks sends from the editor's "Run test" so the SES webhook can skip recording
- // their metrics — keeping test traffic out of the production Metrics tab.
+ const distinctId = invocation.distinctId ?? ''
+ // isTest marks sends from the editor's "Run test" so the SES webhook can skip recording their
+ // metrics — keeping test traffic out of the production Metrics tab. distinctId is appended last
+ // because it may contain colons; it attributes engagement events.
const payload = toBase64UrlSafe(
- `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}:${isTest ? '1' : ''}`
+ `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}:${isTest ? '1' : ''}:${distinctId}`
)
const keys = getSigningKeys()
if (keys.length === 0) {
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index a8b0bb1febc8..a3f24e78ae8f 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -197,6 +197,7 @@ export class TemplateTester {
sesEndpoint: config.SES_ENDPOINT,
},
undefined as any,
+ undefined as any,
config.ENCRYPTION_SALT_KEYS,
config.SITE_URL
)