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.

chore(cdp): extract EmailTrackingCodeSigner so signing keys are injected (#63586)

Daniel Marchukd331f69bd59c
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 403503feae31..b8788cb575dd 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -35,6 +35,7 @@ import { JobQueue } from './services/job-queue/job-queue.interface'
import { GroupsManagerService } from './services/managers/groups-manager.service'
import { HogFunctionManagerService } from './services/managers/hog-function-manager.service'
import { EmailTrackingService } from './services/messaging/email-tracking.service'
+import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
import { HogWatcherService, HogWatcherState } from './services/monitoring/hog-watcher.service'
import { NativeDestinationExecutorService } from './services/native-destination-executor.service'
@@ -131,7 +132,8 @@ export class CdpApi {
services.hogFunctionMonitoringService,
services.capturedEventsService,
services.teamWorkflowsConfigService,
- services.recipientsManager
+ services.recipientsManager,
+ new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
)
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.ts
index 42172c22fad6..337362d4db54 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -33,6 +33,7 @@ import { IntegrationManagerService } from './services/managers/integration-manag
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 { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { RecipientPreferencesService } from './services/messaging/recipient-preferences.service'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService } from './services/monitoring/hog-function-monitoring.service'
@@ -146,6 +147,7 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_FETCH_BACKOFF_MAX_MS'
| 'CDP_SELF_LOOP_GUARD_MODE'
| 'CDP_EMAIL_QUEUE_ROUTING'
+ | 'CDP_EMAIL_TRACKING_URL'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'
| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC'
@@ -379,6 +381,7 @@ export function createCdpCoreServices(
: null
const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const emailService = new EmailService(
{
@@ -390,7 +393,8 @@ export function createCdpCoreServices(
deps.integrationManager,
teamWorkflowsConfigService,
config.ENCRYPTION_SALT_KEYS,
- config.SITE_URL
+ config.SITE_URL,
+ trackingCodeSigner
)
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 5e3b913982e1..84cb6a633eed 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 { HogFunctionManagerService } from '../services/managers/hog-function-man
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 { EmailTrackingCodeSigner } from '../services/messaging/helpers/tracking-code'
import { RecipientTokensService } from '../services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService, MonitoringOutput } from '../services/monitoring/hog-function-monitoring.service'
import { HogWatcherService, HogWatcherState } from '../services/monitoring/hog-watcher.service'
@@ -470,6 +471,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 trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const emailService = new EmailService(
{
@@ -481,7 +483,8 @@ export function createHogTransformerService(
deps.integrationManager,
teamWorkflowsConfigService,
config.ENCRYPTION_SALT_KEYS,
- config.SITE_URL
+ config.SITE_URL,
+ trackingCodeSigner
)
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
const hogExecutor = new HogExecutorService(
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index ad90f4124fd5..2dedc2009074 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -10,6 +10,7 @@ import { HogExecutorService } from '../../../src/cdp/services/hog-executor.servi
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 { 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'
import { Hub } from '../../../src/types'
@@ -63,7 +64,8 @@ describe('Hog Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
executor = new HogExecutorService(
@@ -1942,7 +1944,8 @@ describe('Hog Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
return 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.ts
index 4722225d0c72..cf56367937fb 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -17,6 +17,7 @@ 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 { EmailTrackingCodeSigner } from '../../messaging/helpers/tracking-code'
import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'
import { RecipientTokensService } from '../../messaging/recipient-tokens.service'
import { HogFlowFunctionsService } from '../hogflow-functions.service'
@@ -52,7 +53,8 @@ describe('HogFunctionHandler', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
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.ts
index ea852f62d8d5..0df1e9a766b6 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -17,6 +17,7 @@ import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'
import { HogExecutorService } from '../hog-executor.service'
import { HogInputsService } from '../hog-inputs.service'
import { EmailService } from '../messaging/email.service'
+import { EmailTrackingCodeSigner } from '../messaging/helpers/tracking-code'
import { RecipientTokensService } from '../messaging/recipient-tokens.service'
import { HogFunctionTemplateManagerService } from '../managers/hog-function-template-manager.service'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
@@ -72,7 +73,8 @@ describe('Hogflow Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
const hogExecutor = new HogExecutorService(
@@ -1881,7 +1883,8 @@ describe('Hogflow Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
),
new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
)
@@ -2080,7 +2083,8 @@ describe('Hogflow Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
),
new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
)
@@ -2115,7 +2119,8 @@ describe('Hogflow Executor', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
),
new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
)
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 fcbfcb9761d8..19d2cb42de74 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
@@ -9,8 +9,8 @@ import express from 'ultimate-express'
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 { CyclotronJobInvocationHogFunction, HogFunctionType } from '~/cdp/types'
+import { defaultConfig } from '~/config/config'
import { KAFKA_APP_METRICS_2 } from '~/config/kafka-topics'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { waitForExpect } from '~/tests/helpers/expectations'
@@ -26,12 +26,14 @@ import {
decodeHtmlEntitiesInHref,
resolveEmailEngagementDistinctId,
} from './email-tracking.service'
-import { generateEmailTrackingCode, parseEmailTrackingCode } from './helpers/tracking-code'
+import { EmailTrackingCodeSigner } from './helpers/tracking-code'
describe('EmailTrackingService', () => {
let hub: Hub
let team: Team
+ const signer = new EmailTrackingCodeSigner(defaultConfig.ENCRYPTION_SALT_KEYS, defaultConfig.CDP_EMAIL_TRACKING_URL)
+
beforeEach(async () => {
await resetTestDatabase()
hub = await createHub({})
@@ -82,19 +84,19 @@ describe('EmailTrackingService', () => {
'https://example.com/path',
],
])('decodes %s in the redirect target', (_name, html, expected) => {
- expect(extractTarget(addTrackingToEmail(html, invocation))).toBe(expected)
+ expect(extractTarget(addTrackingToEmail(html, invocation, signer))).toBe(expected)
})
it('skips literal javascript: hrefs', () => {
const html = '<body><a href="javascript:alert(1)">x</a></body>'
- const out = addTrackingToEmail(html, invocation)
+ const out = addTrackingToEmail(html, invocation, signer)
expect(out).toContain('href="javascript:alert(1)"')
expect(out).not.toContain('target=')
})
it('skips entity-encoded javascript: hrefs after decoding', () => {
const html = '<body><a href="java&#x73;cript:alert(1)">x</a></body>'
- const out = addTrackingToEmail(html, invocation)
+ const out = addTrackingToEmail(html, invocation, signer)
expect(out).toContain('href="java&#x73;cript:alert(1)"')
expect(out).not.toContain('target=')
})
@@ -108,8 +110,12 @@ describe('EmailTrackingService', () => {
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')
+ const out = addTrackingToEmail(
+ '<body><a href="https://example.com">x</a></body>',
+ invocationWithDistinctId,
+ signer
+ )
+ expect(signer.parse(phIdOf(out))?.distinctId).toBe('leaky-id')
})
it('omits distinct_id from the public tracking URLs in production (Referer-leak guard)', () => {
@@ -118,9 +124,10 @@ describe('EmailTrackingService', () => {
try {
const out = addTrackingToEmail(
'<body><a href="https://example.com">x</a></body>',
- invocationWithDistinctId
+ invocationWithDistinctId,
+ signer
)
- expect(parseEmailTrackingCode(phIdOf(out))?.distinctId).toBeUndefined()
+ expect(signer.parse(phIdOf(out))?.distinctId).toBeUndefined()
} finally {
devSpy.mockRestore()
testSpy.mockRestore()
@@ -174,7 +181,7 @@ describe('EmailTrackingService', () => {
// tests run in test env and exercise that path.
describe('handleEmailTrackingRedirect', () => {
it('should redirect to the target url and record an email_link_clicked metric', async () => {
- const phId = generateEmailTrackingCode({
+ const phId = signer.generate({
functionId: hogFunction.id,
id: invocationId,
teamId: team.id,
@@ -195,7 +202,7 @@ describe('EmailTrackingService', () => {
})
it('should return 404 if the target is not provided', async () => {
- const phId = generateEmailTrackingCode({
+ const phId = signer.generate({
functionId: hogFunction.id,
id: invocationId,
teamId: team.id,
@@ -210,7 +217,7 @@ describe('EmailTrackingService', () => {
describe('email tracking pixel', () => {
it('should return a gif image and record an email_opened metric', async () => {
- const phId = generateEmailTrackingCode({
+ const phId = signer.generate({
functionId: hogFunction.id,
id: invocationId,
teamId: team.id,
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index ac0d8a328836..fe18d61f890c 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -3,7 +3,6 @@ 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'
@@ -15,12 +14,7 @@ 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 {
- generateEmailTrackingCode,
- generateEmailTrackingPixelUrl,
- parseEmailTrackingCode,
- trackingCodeFormatCounter,
-} from './helpers/tracking-code'
+import { EmailTrackingCodeSigner, trackingCodeFormatCounter } from './helpers/tracking-code'
export const PIXEL_GIF = Buffer.from('R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'base64')
const LINK_REGEX =
@@ -67,18 +61,6 @@ export const resolveEmailEngagementDistinctId = (
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
-): string => {
- return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/redirect?ph_id=${generateEmailTrackingCode(invocation, isTest)}&target=${encodeURIComponent(targetUrl)}`
-}
-
// HTML attribute values arrive entity-encoded (e.g. `&amp;`, `&#38;`). Decode before
// percent-encoding for the tracking redirect, otherwise `?a=1&amp;b=2` round-trips
// through `target=` as a literal `&amp;` and breaks the destination page's query string.
@@ -100,6 +82,7 @@ export const decodeHtmlEntitiesInHref = (value: string): string => {
export const addTrackingToEmail = (
html: string,
invocation: CyclotronJobInvocationHogFunction,
+ signer: EmailTrackingCodeSigner,
isTest = false
): string => {
// Only carry distinct_id in the in-email pixel/redirect URLs in dev/test, where those handlers
@@ -108,7 +91,7 @@ export const addTrackingToEmail = (
// 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)
+ const trackingUrl = signer.pixelUrl(trackingInvocation, isTest)
html = html.replace(LINK_REGEX, (m, d, s, u) => {
const href = decodeHtmlEntitiesInHref(d || s || u || '')
@@ -117,7 +100,7 @@ export const addTrackingToEmail = (
if (/^\s*javascript:/i.test(href)) {
return m
}
- const tracked = generateTrackingRedirectUrl(trackingInvocation, href, isTest)
+ const tracked = signer.redirectUrl(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}"`)
@@ -137,9 +120,10 @@ export class EmailTrackingService {
private hogFunctionMonitoringService: HogFunctionMonitoringService,
private capturedEventsService: CapturedEventsService,
private teamWorkflowsConfigService: TeamWorkflowsConfigService,
- private recipientsManager: RecipientsManagerService
+ private recipientsManager: RecipientsManagerService,
+ private trackingCodeSigner: EmailTrackingCodeSigner
) {
- this.sesWebhookHandler = new SesWebhookHandler()
+ this.sesWebhookHandler = new SesWebhookHandler(this.trackingCodeSigner)
}
public async trackMetric({
@@ -307,7 +291,7 @@ export class EmailTrackingService {
} {
// Support both combined ph_id format and legacy separate params
if (query.ph_id) {
- const parsed = parseEmailTrackingCode(query.ph_id as string)
+ const parsed = this.trackingCodeSigner.parse(query.ph_id as string)
if (parsed) {
trackingCodeFormatCounter.inc({ format: parsed.format, source: 'tracking' })
}
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index ecf82b0ed985..17f69377c11c 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -13,6 +13,7 @@ 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'
+import { EmailTrackingCodeSigner } from './helpers/tracking-code'
class ThrottlingException extends Error {
constructor(message: string) {
@@ -92,7 +93,8 @@ describe('EmailService', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
mockFetch.mockClear()
})
@@ -106,7 +108,8 @@ describe('EmailService', () => {
hub.integrationManager,
new TeamWorkflowsConfigService(hub.postgres),
hub.ENCRYPTION_SALT_KEYS,
- hub.SITE_URL
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
expect(serviceWithoutSES.sesV2Client).toBeNull()
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 4a89d5a032d3..fe6731fb725f 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -14,11 +14,7 @@ import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.se
import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'
import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'
import { maybeAddPreheaderToEmail } from './helpers/preheader'
-import {
- TRACKING_CODE_HEADER_NAME,
- generateEmailTrackingCode,
- generateShortEmailTrackingCode,
-} from './helpers/tracking-code'
+import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'
import { RecipientTokensService } from './recipient-tokens.service'
const sesThrottleResponsesTotal = new Counter({
@@ -111,7 +107,8 @@ export class EmailService {
private integrationManager: IntegrationManagerService,
private teamWorkflowsConfigService: TeamWorkflowsConfigService,
encryptionSaltKeys: string,
- siteUrl: string
+ siteUrl: string,
+ private trackingCodeSigner: EmailTrackingCodeSigner
) {
this.sesV2Client = this.sesConfig.sesRegion
? new SESv2Client({
@@ -266,7 +263,9 @@ export class EmailService {
to: params.to.name ? `"${params.to.name}" <${params.to.email}>` : params.to.email,
subject: sanitizeEmailSubject(params.subject),
text: params.text,
- ...(params.html ? { html: addTrackingToEmail(params.html, result.invocation, isTest) } : {}),
+ ...(params.html
+ ? { html: addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest) }
+ : {}),
}
const ccAddresses = parseAddressList(params.cc)
@@ -301,14 +300,14 @@ export class EmailService {
// 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 trackingCode = this.trackingCodeSigner.generate({ ...result.invocation, distinctId }, isTest)
+ const shortTrackingCode = this.trackingCodeSigner.generateShort(result.invocation)
const htmlBody = params.html
? {
Html: {
Data: maybeAddPreheaderToEmail(
- addTrackingToEmail(params.html, result.invocation, isTest),
+ addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest),
params.preheader
),
Charset: 'UTF-8',
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index de4ba8020b58..740c4bc04ef6 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -1,13 +1,17 @@
+import { defaultConfig } from '~/config/config'
+
import { SesWebhookHandler } from './ses'
-import { generateEmailTrackingCode, generateShortEmailTrackingCode } from './tracking-code'
+import { EmailTrackingCodeSigner } from './tracking-code'
// Hardcoded (not imported) so a change to the header constant fails this test.
const TRACKING_CODE_HEADER = 'X-PostHog-Tracking-Code'
+const signer = new EmailTrackingCodeSigner(defaultConfig.ENCRYPTION_SALT_KEYS, 'http://localhost:8010')
+
describe('SesWebhookHandler', () => {
let handler: SesWebhookHandler
beforeEach(() => {
- handler = new SesWebhookHandler()
+ handler = new SesWebhookHandler(signer)
})
// Mirrors what the sender writes: the custom header carries the full signed code (including
@@ -26,9 +30,9 @@ describe('SesWebhookHandler', () => {
source: '[email protected]',
messageId: 'msg-123',
destination: ['[email protected]'],
- headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation) }],
+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation) }],
tags: {
- ph_id: [generateShortEmailTrackingCode(baseInvocation)],
+ ph_id: [signer.generateShort(baseInvocation)],
},
}
@@ -207,8 +211,8 @@ describe('SesWebhookHandler', () => {
...baseMail,
// isTest rides on the signed header code (preferred by the webhook); the short tag
// code stays legacy-shaped without it.
- headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation, true) }],
- tags: { ph_id: [generateShortEmailTrackingCode(baseInvocation)] },
+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation, true) }],
+ tags: { ph_id: [signer.generateShort(baseInvocation)] },
}
const body = [{ eventType, mail: testMail, ...eventFields }]
const result = await handler.handleWebhook({ body, headers: {} })
@@ -221,8 +225,8 @@ describe('SesWebhookHandler', () => {
...baseMail,
// isTest rides on the signed header code (preferred by the webhook); the short tag
// code stays legacy-shaped without it.
- headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation, true) }],
- tags: { ph_id: [generateShortEmailTrackingCode(baseInvocation)] },
+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation, true) }],
+ tags: { ph_id: [signer.generateShort(baseInvocation)] },
}
const body = [
{
@@ -438,10 +442,8 @@ describe('SesWebhookHandler', () => {
}
const mailWithParentRun = {
...baseMail,
- headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(batchInvocation) }],
- tags: {
- ph_id: [generateShortEmailTrackingCode(batchInvocation)],
- },
+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(batchInvocation) }],
+ tags: { ph_id: [signer.generateShort(batchInvocation)] },
}
const body = [
{
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 043a587e925d..55f0b5a90844 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -6,7 +6,7 @@ import { parseJSON } from '~/utils/json-parse'
import { logger } from '~/utils/logger'
import { fetch } from '~/utils/request'
-import { TRACKING_CODE_HEADER_NAME, parseEmailTrackingCode, trackingCodeFormatCounter } from './tracking-code'
+import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME, trackingCodeFormatCounter } from './tracking-code'
/**
* ---------- SNS envelope types ----------
@@ -159,6 +159,8 @@ const EVENT_TYPE_TO_METRIC_NAME: Partial<Record<SesEventRecord['eventType'], Min
export class SesWebhookHandler {
certCache: Record<string, Promise<string> | undefined> = {}
+ constructor(private trackingCodeSigner: EmailTrackingCodeSigner) {}
+
private async fetchText(url: string): Promise<string> {
const response = await fetch(url)
if (response.status >= 400) {
@@ -395,7 +397,7 @@ export class SesWebhookHandler {
(h) => h.name.toLowerCase() === TRACKING_CODE_HEADER_NAME.toLowerCase()
)?.value
const tagValue = rec.mail.tags?.ph_id?.[0]
- const parsedCode = parseEmailTrackingCode(headerValue ?? tagValue ?? '')
+ const parsedCode = this.trackingCodeSigner.parse(headerValue ?? tagValue ?? '')
if (parsedCode) {
trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })
}
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 765244d487d8..08faf6fb5d3d 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
@@ -1,19 +1,24 @@
import { defaultConfig } from '~/config/config'
-import { generateEmailTrackingCode, generateShortEmailTrackingCode, parseEmailTrackingCode } from './tracking-code'
+import { EmailTrackingCodeSigner } from './tracking-code'
-// 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 TRACKING_URL = 'http://localhost:8010'
+
+// Hand-encode a raw payload the same way the signer does, so we can test
+// pre-fix legacy/forged shapes without pulling in the generator.
const encodeRaw = (payload: string): string =>
Buffer.from(payload, 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
describe('email tracking code', () => {
- describe('parseEmailTrackingCode', () => {
+ // Runs with ENCRYPTION_SALT_KEYS set in the test env, so codes are signed by default.
+ const signer = new EmailTrackingCodeSigner(defaultConfig.ENCRYPTION_SALT_KEYS, TRACKING_URL)
+
+ describe('parse', () => {
it.each([
{
// Generated codes are signed in the test env (ENCRYPTION_SALT_KEYS is set).
name: 'roundtrips all invocation fields including distinctId (signed)',
- encoded: generateEmailTrackingCode({
+ encoded: signer.generate({
functionId: 'fn-1',
id: 'inv-2',
teamId: 3,
@@ -34,7 +39,7 @@ describe('email tracking code', () => {
},
{
name: 'roundtrips the isTest flag for test sends',
- encoded: generateEmailTrackingCode(
+ encoded: signer.generate(
{
functionId: 'fn-1',
id: 'inv-2',
@@ -59,7 +64,7 @@ describe('email tracking code', () => {
{
// isTest sits after actionId/parentRunId, so it must survive both being empty.
name: 'roundtrips isTest when neither actionId nor parentRunId is supplied',
- encoded: generateEmailTrackingCode({ functionId: 'fn-1', id: 'inv-2', teamId: 3 }, true),
+ encoded: signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3 }, true),
expected: {
functionId: 'fn-1',
invocationId: 'inv-2',
@@ -73,7 +78,7 @@ describe('email tracking code', () => {
},
{
name: 'roundtrips with UUID distinctId (signed)',
- encoded: generateEmailTrackingCode({
+ encoded: signer.generate({
functionId: 'abc-123',
id: 'xyz-456',
teamId: 7,
@@ -92,7 +97,7 @@ describe('email tracking code', () => {
},
{
name: 'omits parentRunId and distinctId when not supplied (signed)',
- encoded: generateEmailTrackingCode({
+ encoded: signer.generate({
functionId: 'fn-1',
id: 'inv-2',
teamId: 3,
@@ -112,7 +117,7 @@ describe('email tracking code', () => {
{
// 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({
+ encoded: signer.generateShort({
functionId: 'fn-1',
id: 'inv-2',
teamId: 3,
@@ -197,98 +202,84 @@ describe('email tracking code', () => {
expected: null,
},
])('$name', ({ encoded, expected }) => {
- expect(parseEmailTrackingCode(encoded)).toEqual(expected)
+ expect(signer.parse(encoded)).toEqual(expected)
})
})
describe('signed tracking codes', () => {
it('emits codes with a `.` separator when signing keys are configured', () => {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
expect(code).toContain('.')
})
it('does not sign the short code used for the SES tag', () => {
- const short = generateShortEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const short = signer.generateShort({ functionId: 'fn', id: 'inv', teamId: 1 })
expect(short).not.toContain('.')
- expect(parseEmailTrackingCode(short)?.format).toBe('unsigned')
+ expect(signer.parse(short)?.format).toBe('unsigned')
})
it('rejects a signed code with a tampered payload', () => {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const code = signer.generate({ 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}`
- expect(parseEmailTrackingCode(tampered)).toBeNull()
+ expect(signer.parse(tampered)).toBeNull()
})
it('rejects a signed code with a tampered signature', () => {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
const payload = code.split('.')[0]
// 16 raw bytes -> 22 base64url chars
const badSig = 'A'.repeat(22)
- expect(parseEmailTrackingCode(`${payload}.${badSig}`)).toBeNull()
+ expect(signer.parse(`${payload}.${badSig}`)).toBeNull()
})
it('rejects a signed code with a malformed (wrong-length) signature', () => {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
const payload = code.split('.')[0]
- expect(parseEmailTrackingCode(`${payload}.short`)).toBeNull()
+ expect(signer.parse(`${payload}.short`)).toBeNull()
})
it('rejects a code with extra `.` segments appended', () => {
// Both payload and signature are base64url (no dots), so a legitimate signed code
// is structurally exactly `<payload>.<signature>`. Anything else is malformed.
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
- expect(parseEmailTrackingCode(`${code}.junk`)).toBeNull()
+ const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
+ expect(signer.parse(`${code}.junk`)).toBeNull()
})
it('rejects when no signing key matches', () => {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
- const original = defaultConfig.ENCRYPTION_SALT_KEYS
- defaultConfig.ENCRYPTION_SALT_KEYS = 'a-completely-different-key-32-chr'
- try {
- expect(parseEmailTrackingCode(code)).toBeNull()
- } finally {
- defaultConfig.ENCRYPTION_SALT_KEYS = original
- }
+ const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const otherSigner = new EmailTrackingCodeSigner('a-completely-different-key-32-chr', TRACKING_URL)
+ expect(otherSigner.parse(code)).toBeNull()
})
it('verifies against any key in the rotation list', () => {
- const original = defaultConfig.ENCRYPTION_SALT_KEYS
- defaultConfig.ENCRYPTION_SALT_KEYS = 'old-key-aaaaaaaaaaaaaaaaaaaaaaaa'
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const oldSigner = new EmailTrackingCodeSigner('old-key-aaaaaaaaaaaaaaaaaaaaaaaa', TRACKING_URL)
+ const code = oldSigner.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
// 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')
- } finally {
- defaultConfig.ENCRYPTION_SALT_KEYS = original
- }
+ const rotatedSigner = new EmailTrackingCodeSigner(
+ 'new-key-bbbbbbbbbbbbbbbbbbbbbbbb,old-key-aaaaaaaaaaaaaaaaaaaaaaaa',
+ TRACKING_URL
+ )
+ expect(rotatedSigner.parse(code)?.format).toBe('signed')
})
it('trims whitespace around keys in the rotation list', () => {
- const original = defaultConfig.ENCRYPTION_SALT_KEYS
- defaultConfig.ENCRYPTION_SALT_KEYS = 'signing-key-cccccccccccccccccccc'
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
+ const signingSigner = new EmailTrackingCodeSigner('signing-key-cccccccccccccccccccc', TRACKING_URL)
+ const code = signingSigner.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
// Same keys, but configured with a space after the comma — must still verify.
- defaultConfig.ENCRYPTION_SALT_KEYS = 'other-key-dddddddddddddddddddddd, signing-key-cccccccccccccccccccc'
- try {
- expect(parseEmailTrackingCode(code)?.format).toBe('signed')
- } finally {
- defaultConfig.ENCRYPTION_SALT_KEYS = original
- }
+ const spacedSigner = new EmailTrackingCodeSigner(
+ 'other-key-dddddddddddddddddddddd, signing-key-cccccccccccccccccccc',
+ TRACKING_URL
+ )
+ expect(spacedSigner.parse(code)?.format).toBe('signed')
})
it('emits unsigned codes when no signing key is configured', () => {
- const original = defaultConfig.ENCRYPTION_SALT_KEYS
- defaultConfig.ENCRYPTION_SALT_KEYS = ''
- try {
- const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })
- expect(code).not.toContain('.')
- expect(parseEmailTrackingCode(code)?.format).toBe('unsigned')
- } finally {
- defaultConfig.ENCRYPTION_SALT_KEYS = original
- }
+ const unsignedSigner = new EmailTrackingCodeSigner('', TRACKING_URL)
+ const code = unsignedSigner.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
+ expect(code).not.toContain('.')
+ expect(unsignedSigner.parse(code)?.format).toBe('unsigned')
})
})
})
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
index 0ae423179fc9..278a781c7230 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
@@ -2,14 +2,13 @@ import crypto from 'node:crypto'
import { Counter } from 'prom-client'
import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
-import { defaultConfig } from '~/config/config'
const SIGNATURE_BYTES = 16
// Custom MIME header carrying the signed tracking code. HMAC adds ~23 chars to the code,
// which pushes a batch-flow code past the SES `EmailTags` 256-char cap. Header values have
// no such limit, so the signed code rides here; the SES tag carries the short unsigned code
-// (see generateShortEmailTrackingCode) purely as a backwards-compat fallback.
+// (see generateShort) purely as a backwards-compat fallback.
export const TRACKING_CODE_HEADER_NAME = 'X-PostHog-Tracking-Code'
// Tracks the rotation curve from unsigned to signed tracking codes.
@@ -36,33 +35,7 @@ function fromBase64UrlSafe(b64url: string): string {
return fromBase64UrlSafeBuffer(b64url).toString('utf8')
}
-function getSigningKeys(): string[] {
- return (defaultConfig.ENCRYPTION_SALT_KEYS || '')
- .split(',')
- .map((key) => key.trim())
- .filter(Boolean)
-}
-
-function signPayload(payload: string, key: string): string {
- const mac = crypto.createHmac('sha256', key).update(payload).digest().subarray(0, SIGNATURE_BYTES)
- return toBase64UrlSafe(mac)
-}
-
-function verifySignature(payload: string, signature: string): boolean {
- const expected = fromBase64UrlSafeBuffer(signature)
- if (expected.length !== SIGNATURE_BYTES) {
- return false
- }
- for (const key of getSigningKeys()) {
- const candidate = crypto.createHmac('sha256', key).update(payload).digest().subarray(0, SIGNATURE_BYTES)
- if (crypto.timingSafeEqual(expected, candidate)) {
- return true
- }
- }
- return false
-}
-
-type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functionId' | 'id' | 'teamId'> & {
+export type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functionId' | 'id' | 'teamId'> & {
parentRunId?: string | null
state?: { actionId?: string }
distinctId?: string
@@ -70,9 +43,7 @@ type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functionId' |
export type TrackingCodeFormat = 'signed' | 'unsigned'
-export const parseEmailTrackingCode = (
- encodedTrackingCode: string
-): {
+export type ParsedTrackingCode = {
functionId: string
invocationId: string
teamId: string
@@ -81,83 +52,132 @@ export const parseEmailTrackingCode = (
isTest: boolean
distinctId?: string
format: TrackingCodeFormat
-} | null => {
- if (!encodedTrackingCode) {
- return null
+}
+
+// Generates, signs, verifies and renders email tracking codes. Signing keys and the public
+// tracking URL are read once in the constructor so callers can be injected with a configured
+// instance (see cdp-services.ts) instead of reaching into global config — and tests can pass
+// keys directly rather than mutating `defaultConfig`.
+export class EmailTrackingCodeSigner {
+ private signingKeys: string[]
+
+ constructor(
+ encryptionSaltKeys: string,
+ private trackingUrl: string
+ ) {
+ this.signingKeys = (encryptionSaltKeys || '')
+ .split(',')
+ .map((key) => key.trim())
+ .filter(Boolean)
}
- let payloadB64 = encodedTrackingCode
- let format: TrackingCodeFormat = 'unsigned'
+ private signPayload(payload: string, key: string): string {
+ const mac = crypto.createHmac('sha256', key).update(payload).digest().subarray(0, SIGNATURE_BYTES)
+ return toBase64UrlSafe(mac)
+ }
- const parts = encodedTrackingCode.split('.')
- if (parts.length > 1) {
- // A legitimate signed code is exactly `<payload>.<signature>`; both halves are base64url
- // (no dots), so any code with more than one `.` is malformed and rejected outright.
- if (parts.length !== 2 || !verifySignature(parts[0], parts[1])) {
- return null
+ private verifySignature(payload: string, signature: string): boolean {
+ const expected = fromBase64UrlSafeBuffer(signature)
+ if (expected.length !== SIGNATURE_BYTES) {
+ return false
}
- payloadB64 = parts[0]
- format = 'signed'
+ // Accept a signature made with any configured key so key rotation doesn't invalidate
+ // in-flight codes signed with the previous key.
+ for (const key of this.signingKeys) {
+ const candidate = crypto.createHmac('sha256', key).update(payload).digest().subarray(0, SIGNATURE_BYTES)
+ if (crypto.timingSafeEqual(expected, candidate)) {
+ return true
+ }
+ }
+ return false
}
- try {
- const decoded = fromBase64UrlSafe(payloadB64)
- // 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) {
+ parse(encodedTrackingCode: string): ParsedTrackingCode | null {
+ if (!encodedTrackingCode) {
return null
}
- return {
- functionId,
- invocationId,
- teamId,
- 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,
+
+ let payloadB64 = encodedTrackingCode
+ let format: TrackingCodeFormat = 'unsigned'
+
+ const parts = encodedTrackingCode.split('.')
+ if (parts.length > 1) {
+ // A legitimate signed code is exactly `<payload>.<signature>`; both halves are base64url
+ // (no dots), so any code with more than one `.` is malformed and rejected outright.
+ if (parts.length !== 2 || !this.verifySignature(parts[0], parts[1])) {
+ return null
+ }
+ payloadB64 = parts[0]
+ format = 'signed'
+ }
+
+ try {
+ const decoded = fromBase64UrlSafe(payloadB64)
+ // 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
+ }
+ return {
+ functionId,
+ invocationId,
+ teamId,
+ 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 {
+ return null
}
- } catch {
- return null
}
-}
-// Full tracking code, HMAC-signed when a signing key is configured. Rides in the custom MIME
-// header and the pixel/link URLs — carriers with no length cap — and the signature lets the
-// public tracking endpoint reject forged `ph_id` values.
-export const generateEmailTrackingCode = (invocation: TrackingInvocation, isTest = false): string => {
- const actionId = invocation.state?.actionId ?? ''
- const parentRunId = invocation.parentRunId ?? ''
- 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' : ''}:${distinctId}`
- )
- const keys = getSigningKeys()
- if (keys.length === 0) {
- // Fail open while signing rolls out so sends never break; tighten to throw once enforced (#62624).
- return payload
+ // Full tracking code, HMAC-signed when a signing key is configured. Rides in the custom MIME
+ // header and the pixel/link URLs — carriers with no length cap — and the signature lets the
+ // public tracking endpoint reject forged `ph_id` values.
+ generate(invocation: TrackingInvocation, isTest = false): string {
+ const actionId = invocation.state?.actionId ?? ''
+ const parentRunId = invocation.parentRunId ?? ''
+ 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' : ''}:${distinctId}`
+ )
+ if (this.signingKeys.length === 0) {
+ // Fail open while signing rolls out so sends never break; tighten to throw once enforced (#62624).
+ return payload
+ }
+ return `${payload}.${this.signPayload(payload, this.signingKeys[0])}`
}
- return `${payload}.${signPayload(payload, keys[0])}`
-}
-// Unsigned tracking code for the SES `EmailTags` carrier. Omitting the signature keeps the
-// value short enough to stay within the 256-char tag cap; the tag arrives via the SNS webhook,
-// which is already integrity-protected by SNS signing, so it does not need its own signature.
-// This is a legacy backwards-compat carrier only — new fields (e.g. isTest) live on the signed
-// code in generateEmailTrackingCode, which the webhook reads first.
-export const generateShortEmailTrackingCode = (invocation: TrackingInvocation): string => {
- const actionId = invocation.state?.actionId ?? ''
- const parentRunId = invocation.parentRunId ?? ''
- return toBase64UrlSafe(`${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}`)
-}
+ // Unsigned tracking code for the SES `EmailTags` carrier. Omitting the signature keeps the
+ // value short enough to stay within the 256-char tag cap; the tag arrives via the SNS webhook,
+ // which is already integrity-protected by SNS signing, so it does not need its own signature.
+ // This is a legacy backwards-compat carrier only — new fields (e.g. isTest, distinctId) live on
+ // the signed code in generate, which the webhook reads first.
+ generateShort(invocation: TrackingInvocation): string {
+ const actionId = invocation.state?.actionId ?? ''
+ const parentRunId = invocation.parentRunId ?? ''
+ return toBase64UrlSafe(
+ `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}`
+ )
+ }
-export const generateEmailTrackingPixelUrl = (invocation: TrackingInvocation, isTest = false): string => {
- return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/pixel?ph_id=${generateEmailTrackingCode(invocation, isTest)}`
+ pixelUrl(invocation: TrackingInvocation, isTest = false): string {
+ return `${this.trackingUrl}/public/m/pixel?ph_id=${this.generate(invocation, isTest)}`
+ }
+
+ redirectUrl(invocation: TrackingInvocation, targetUrl: string, isTest = false): string {
+ return `${this.trackingUrl}/public/m/redirect?ph_id=${this.generate(invocation, isTest)}&target=${encodeURIComponent(targetUrl)}`
+ }
}
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index a3f24e78ae8f..b0ba0574526d 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -14,6 +14,7 @@ import { PluginsServerConfig } from '../../../types'
import { HogExecutorService } from '../../services/hog-executor.service'
import { HogInputsService } from '../../services/hog-inputs.service'
import { EmailService } from '../../services/messaging/email.service'
+import { EmailTrackingCodeSigner } from '../../services/messaging/helpers/tracking-code'
import { RecipientTokensService } from '../../services/messaging/recipient-tokens.service'
import {
CyclotronJobInvocationHogFunction,
@@ -199,7 +200,8 @@ export class TemplateTester {
undefined as any,
undefined as any,
config.ENCRYPTION_SALT_KEYS,
- config.SITE_URL
+ config.SITE_URL,
+ new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
)
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
return new HogExecutorService(