:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): HMAC-sign email tracking codes (#60229)
Daniel Marchuk3b11f5ccd397
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 47d66ea7ad8e..922e0f09690a 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -16,6 +16,7 @@ import {generateEmailTrackingCode,generateEmailTrackingPixelUrl,parseEmailTrackingCode,+ trackingCodeFormatCounter,} from './helpers/tracking-code'export const PIXEL_GIF = Buffer.from('R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'base64')@@ -235,6 +236,9 @@ export class EmailTrackingService {// Support both combined ph_id format and legacy separate paramsif (query.ph_id) {const parsed = parseEmailTrackingCode(query.ph_id as string)+ if (parsed) {+ trackingCodeFormatCounter.inc({ format: parsed.format, source: 'tracking' })+ }return {functionId: parsed?.functionId,invocationId: parsed?.invocationId,diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex 46b405471b67..4fe41b65e8a1 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -295,8 +295,10 @@ describe('EmailService', () => {await waitForExpect(async () => expect(mailDevAPI.getEmails()).resolves.toHaveLength(1))const emails = await mailDevAPI.getEmails()expect(emails).toHaveLength(1)- expect(emails[0].html).toEqual(- `<body>Hi! <a href="http://localhost:8010/public/m/redirect?ph_id=ZnVuY3Rpb24tMTppbnZvY2F0aW9uLTE6Mjo6&target=https%3A%2F%2Fexample.com">Click me</a><img src="http://localhost:8010/public/m/pixel?ph_id=ZnVuY3Rpb24tMTppbnZvY2F0aW9uLTE6Mjo6" style="display: none;" /></body>`+ // ph_id may be unsigned (base64url only) or signed (base64url + `.` + signature) depending on+ // ENCRYPTION_SALT_KEYS. Match the structure, not the exact value.+ expect(emails[0].html).toMatch(+ /^<body>Hi! <a href="http:\/\/localhost:8010\/public\/m\/redirect\?ph_id=[A-Za-z0-9._-]+&target=https%3A%2F%2Fexample\.com">Click me<\/a><img src="http:\/\/localhost:8010\/public\/m\/pixel\?ph_id=[A-Za-z0-9._-]+" style="display: none;" \/><\/body>$/)})})@@ -345,42 +347,23 @@ describe('EmailService', () => {expect(result.error).toBeUndefined()expect(sendEmailSpy).toHaveBeenCalledTimes(1)const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }- expect(sentCommand.input).toMatchInlineSnapshot(`- {- "ConfigurationSetName": "posthog-messaging",- "Content": {- "Simple": {- "Body": {- "Html": {- "Charset": "UTF-8",- "Data": "Test HTML",+ // The SES tag carries the short unsigned code (no dot); the signed code rides in the header.+ expect(sentCommand.input).toMatchObject({+ ConfigurationSetName: 'posthog-messaging',+ Content: {+ Simple: {+ Body: {+ Html: { Charset: 'UTF-8', Data: 'Test HTML' },+ Text: { Charset: 'UTF-8', Data: 'Test Text' },},- "Text": {- "Charset": "UTF-8",- "Data": "Test Text",- },- },- "Subject": {- "Charset": "UTF-8",- "Data": "Test Subject",- },- },- },- "Destination": {- "ToAddresses": [- "\"Test User\" <[email protected]>",- ],- },- "EmailTags": [- {- "Name": "ph_id",- "Value": "ZnVuY3Rpb24tMTppbnZvY2F0aW9uLTE6Mjo6",+ Subject: { Charset: 'UTF-8', Data: 'Test Subject' },},- ],- "FeedbackForwardingEmailAddress": "[email protected]",- "FromEmailAddress": "\"Test User\" <[email protected]>",- }- `)+ },+ Destination: { ToAddresses: ['"Test User" <[email protected]>'] },+ EmailTags: [{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) }],+ FeedbackForwardingEmailAddress: '[email protected]',+ FromEmailAddress: '"Test User" <[email protected]>',+ })})it('should include cc addresses in SES destination', async () => {@@ -532,13 +515,30 @@ describe('EmailService', () => {)})- it('should not include unsubscribe headers for transactional emails', async () => {+ it('should not include unsubscribe headers for transactional emails (but tracking-code header is still set)', async () => {+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ invocation.hogFunction.metadata = { message_category_type: 'transactional' }+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }+ const headerNames = (sentCommand.input.Content.Simple.Headers ?? []).map((h: { Name: string }) => h.Name)+ expect(headerNames).not.toContain('List-Unsubscribe')+ expect(headerNames).not.toContain('List-Unsubscribe-Post')+ expect(headerNames).toContain('X-PostHog-Tracking-Code')+ })++ it('attaches the X-PostHog-Tracking-Code header carrying the full signed code', async () => {sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })invocation.hogFunction.metadata = { message_category_type: 'transactional' }const result = await service.executeSendEmail(invocation)expect(result.error).toBeUndefined()const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }- expect(sentCommand.input.Content.Simple.Headers).toBeUndefined()+ const trackingHeader = sentCommand.input.Content.Simple.Headers.find(+ (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(sentCommand.input.EmailTags[0].Value).not.toEqual(trackingHeader.Value)})it('should report a missing message id', async () => {diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex b0d836b0af39..27133fdc8fec 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -11,7 +11,11 @@ import { RecipientManagerRecipient } from '../managers/recipients-manager.servicimport { addTrackingToEmail } from './email-tracking.service'import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'import { maybeAddPreheaderToEmail } from './helpers/preheader'-import { generateEmailTrackingCode } from './helpers/tracking-code'+import {+ TRACKING_CODE_HEADER_NAME,+ generateEmailTrackingCode,+ generateShortEmailTrackingCode,+} from './helpers/tracking-code'import { RecipientTokensService } from './recipient-tokens.service'export interface EmailServiceConfig {@@ -192,6 +196,9 @@ export class EmailService {throw new Error('SES is not configured - set SES_REGION and AWS credentials')}const trackingCode = generateEmailTrackingCode(result.invocation)+ // Short carrier (unsigned) for the SES EmailTag — guaranteed under the 256-char tag-value+ // limit. The full signed code rides in the header below.+ const shortTrackingCode = generateShortEmailTrackingCode(result.invocation)const htmlBody = params.html? {@@ -226,17 +233,27 @@ export class EmailService {},},ConfigurationSetName: 'posthog-messaging',- EmailTags: [{ Name: 'ph_id', Value: trackingCode }],+ // Short unsigned tag kept as a backwards-compat carrier for in-flight messages and+ // environments where the configuration set isn't yet emitting original headers.+ EmailTags: [{ Name: 'ph_id', Value: shortTrackingCode }],FeedbackForwardingEmailAddress: from.email,}+ // 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.+ const trackingHeader: MessageHeader = { Name: TRACKING_CODE_HEADER_NAME, Value: trackingCode }+const isTransactionalEmail = result.invocation.hogFunction?.metadata?.message_category_type === 'transactional'- // Automatically add unsubscribe headers for non-transactional emails- if (sendEmailParams.Content?.Simple && !isTransactionalEmail) {- sendEmailParams.Content.Simple.Headers = this.generateUnsubscribeHeaders({- team_id: result.invocation.teamId,- identifier: params.to.email,- })+ if (sendEmailParams.Content?.Simple) {+ const unsubscribeHeaders = !isTransactionalEmail+ ? this.generateUnsubscribeHeaders({+ team_id: result.invocation.teamId,+ identifier: params.to.email,+ })+ : []+ sendEmailParams.Content.Simple.Headers = [...unsubscribeHeaders, trackingHeader]}const replyToAddresses = parseAddressList(params.replyTo)diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex d75764fe1d36..959e7ba33f03 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -1,5 +1,8 @@import { SesWebhookHandler } from './ses'-import { generateEmailTrackingCode } from './tracking-code'+import { generateEmailTrackingCode, generateShortEmailTrackingCode } from './tracking-code'++// Hardcoded (not imported) so a change to the header constant fails this test.+const TRACKING_CODE_HEADER = 'X-PostHog-Tracking-Code'describe('SesWebhookHandler', () => {let handler: SesWebhookHandler@@ -7,22 +10,23 @@ 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.+ const baseInvocation = {+ functionId: 'abc123',+ id: 'inv456',+ teamId: 1,+ state: { actionId: 'act789' },+ } as const+const baseMail = {timestamp: '2025-10-03T12:00:00Z',source: '[email protected]',messageId: 'msg-123',destination: ['[email protected]'],+ headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation) }],tags: {- ph_id: [- generateEmailTrackingCode({- functionId: 'abc123',- id: 'inv456',- teamId: 1,- state: {- actionId: 'act789',- },- }),- ],+ ph_id: [generateShortEmailTrackingCode(baseInvocation)],},}@@ -76,6 +80,34 @@ describe('SesWebhookHandler', () => {expect(result.metrics).toHaveLength(0)})+ it('parses the signed code from the header when the SES tag is absent', async () => {+ 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]).toMatchObject({ functionId: 'abc123', invocationId: 'inv456' })+ })++ it('falls back to the SES tag when the custom header is absent (in-flight backwards compat)', async () => {+ 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]).toMatchObject({ functionId: 'abc123', invocationId: 'inv456' })+ })+it('parses a raw Delivery event', async () => {const body = [{@@ -138,6 +170,31 @@ describe('SesWebhookHandler', () => {expect(result.optOutRecipients).toEqual([])})+ it('rejects raw (non-SNS) deliveries when signature verification is required', async () => {+ const body = [+ {+ eventType: 'Bounce',+ mail: baseMail,+ bounce: {+ bounceType: 'Permanent',+ bouncedRecipients: [+ {+ emailAddress: '[email protected]',+ action: 'failed',+ status: '5.1.1',+ diagnosticCode: 'bad',+ },+ ],+ timestamp: '2025-10-03T12:04:00Z',+ reportingMTA: 'mta',+ },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {}, verifySignature: true })+ expect(result.status).toBe(403)+ expect(result.optOutRecipients).toBeUndefined()+ })+it('parses a raw Complaint event', async () => {const body = [{@@ -158,7 +215,7 @@ describe('SesWebhookHandler', () => {const body = [{eventType: 'Open',- mail: { ...baseMail, tags: {} },+ mail: { ...baseMail, tags: {}, headers: [] },open: {ipAddress: '1.2.3.4',userAgent: 'UA',@@ -230,19 +287,17 @@ describe('SesWebhookHandler', () => {})it('propagates parentRunId from the tracking code so batch runs get correct attribution', async () => {+ const batchInvocation = {+ functionId: 'workflow-id',+ id: 'child-invocation-id',+ teamId: 1,+ parentRunId: 'batch-run-id',+ state: { actionId: 'email-action' },+ }const mailWithParentRun = {...baseMail,- tags: {- ph_id: [- generateEmailTrackingCode({- functionId: 'workflow-id',- id: 'child-invocation-id',- teamId: 1,- parentRunId: 'batch-run-id',- state: { actionId: 'email-action' },- }),- ],- },+ headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(batchInvocation) }],+ tags: { ph_id: [generateShortEmailTrackingCode(batchInvocation)] },}const body = [{diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 147303b9ae90..008cecba40ae 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 { parseEmailTrackingCode } from './tracking-code'+import { TRACKING_CODE_HEADER_NAME, parseEmailTrackingCode, trackingCodeFormatCounter } from './tracking-code'/*** ---------- SNS envelope types ----------@@ -326,8 +326,12 @@ export class SesWebhookHandler {logger.info('[SesWebhookHandler] parsed', { parsed })- // If SNS envelope present and verification requested, verify signature- if ('envelope' in parsed && opts.verifySignature) {+ // When verification is required the message must be a signed SNS envelope. Raw deliveries+ // carry no signature, and prod uses envelope delivery, so reject them to block forged events.+ if (opts.verifySignature) {+ if (!('envelope' in parsed)) {+ return { status: 403, body: { error: 'Unsigned raw delivery not allowed' } }+ }logger.info('[SesWebhookHandler] verifying signature', { envelope: parsed.envelope })const ok = await this.verifySnsSignature(parsed.envelope)logger.info('[SesWebhookHandler] signature verified', { ok })@@ -377,9 +381,18 @@ export class SesWebhookHandler {for (const rec of records) {logger.info('[SesWebhookHandler] processing record', { rec })- const tags = rec.mail.tags- const { functionId, invocationId, teamId, actionId, parentRunId } =- parseEmailTrackingCode(tags?.ph_id?.[0] || '') || {}+ // 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`.+ const headerValue = rec.mail.headers?.find(+ (h) => h.name.toLowerCase() === TRACKING_CODE_HEADER_NAME.toLowerCase()+ )?.value+ const tagValue = rec.mail.tags?.ph_id?.[0]+ const parsedCode = parseEmailTrackingCode(headerValue ?? tagValue ?? '')+ if (parsedCode) {+ trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })+ }+ const { functionId, invocationId, teamId, actionId, parentRunId } = parsedCode || {}if (!functionId && !invocationId) {logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.tsindex 7b934ea6e3e8..827fad12b4c7 100644--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts@@ -1,4 +1,6 @@-import { generateEmailTrackingCode, parseEmailTrackingCode } from './tracking-code'+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.@@ -23,6 +25,7 @@ describe('email tracking code', () => {teamId: '3',actionId: 'act-5',parentRunId: 'batch-4',+ format: 'signed',},},{@@ -39,11 +42,12 @@ describe('email tracking code', () => {teamId: '3',actionId: 'act-5',parentRunId: undefined,+ format: 'signed',},},{// Webhooks for emails already in flight when the fix deploys must still parse.- name: 'parses legacy 4-segment codes emitted before parentRunId existed',+ name: 'parses legacy 4-segment unsigned codes emitted before parentRunId existed',encoded: encodeRaw('fn-1:inv-2:3:act-5'),expected: {functionId: 'fn-1',@@ -51,6 +55,19 @@ describe('email tracking code', () => {teamId: '3',actionId: 'act-5',parentRunId: undefined,+ format: 'unsigned',+ },+ },+ {+ name: 'parses legacy 5-segment unsigned codes emitted before signing existed',+ encoded: encodeRaw('fn-1:inv-2:3:act-5:batch-4'),+ expected: {+ functionId: 'fn-1',+ invocationId: 'inv-2',+ teamId: '3',+ actionId: 'act-5',+ parentRunId: 'batch-4',+ format: 'unsigned',},},{@@ -62,4 +79,95 @@ describe('email tracking code', () => {expect(parseEmailTrackingCode(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 })+ expect(code).toContain('.')+ })++ it('does not sign the short code used for the SES tag', () => {+ const short = generateShortEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })+ expect(short).not.toContain('.')+ expect(parseEmailTrackingCode(short)?.format).toBe('unsigned')+ })++ it('rejects a signed code with a tampered payload', () => {+ 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}`+ expect(parseEmailTrackingCode(tampered)).toBeNull()+ })++ it('rejects a signed code with a tampered signature', () => {+ const code = generateEmailTrackingCode({ 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()+ })++ it('rejects a signed code with a malformed (wrong-length) signature', () => {+ const code = generateEmailTrackingCode({ functionId: 'fn', id: 'inv', teamId: 1 })+ const payload = code.split('.')[0]+ expect(parseEmailTrackingCode(`${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()+ })++ 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+ }+ })++ 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 })+ // Rotation: new key first, old key kept for 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+ }+ })++ 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 })+ // 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+ }+ })++ 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+ }+ })+ })})diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.tsindex f10f3161598d..cff6b09feb08 100644--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts@@ -1,21 +1,65 @@+import crypto from 'node:crypto'+import { Counter } from 'prom-client'+import { CyclotronJobInvocationHogFunction } from '~/cdp/types'import { defaultConfig } from '~/config/config'-function toBase64UrlSafe(input: string) {- // Encode to normal base64- const b64 = Buffer.from(input, 'utf8').toString('base64')- // Make URL safe and strip padding+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.+export const TRACKING_CODE_HEADER_NAME = 'X-PostHog-Tracking-Code'++// Tracks the rotation curve from unsigned to signed tracking codes.+export const trackingCodeFormatCounter = new Counter({+ name: 'email_tracking_code_format_total',+ help: 'Count of email tracking codes parsed by signature format',+ labelNames: ['format', 'source'],+})++function toBase64UrlSafe(input: string | Buffer): string {+ const b64 = Buffer.isBuffer(input) ? input.toString('base64') : Buffer.from(input, 'utf8').toString('base64')return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}-function fromBase64UrlSafe(b64url: string) {- // Restore base64 from URL-safe variant+function fromBase64UrlSafeBuffer(b64url: string): Buffer {let b64 = b64url.replace(/-/g, '+').replace(/_/g, '/')- // Pad to length multiple of 4while (b64.length % 4) {b64 += '='}- return Buffer.from(b64, 'base64').toString('utf8')+ return Buffer.from(b64, 'base64')+}++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'> & {@@ -23,6 +67,8 @@ type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functionId' |state?: { actionId?: string }}+export type TrackingCodeFormat = 'signed' | 'unsigned'+export const parseEmailTrackingCode = (encodedTrackingCode: string): {@@ -31,12 +77,29 @@ export const parseEmailTrackingCode = (teamId: stringactionId?: stringparentRunId?: string+ format: TrackingCodeFormat} | null => {- const decodedTrackingCode = fromBase64UrlSafe(encodedTrackingCode)+ if (!encodedTrackingCode) {+ return null+ }++ 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 || !verifySignature(parts[0], parts[1])) {+ return null+ }+ payloadB64 = parts[0]+ format = 'signed'+ }+try {- // Tracking codes emitted before the parentRunId field was added are 4 segments;- // newer codes append parentRunId as a 5th segment. Missing segment = undefined.- const [functionId, invocationId, teamId, actionId, parentRunId] = decodedTrackingCode.split(':')+ const decoded = fromBase64UrlSafe(payloadB64)+ const [functionId, invocationId, teamId, actionId, parentRunId] = decoded.split(':')if (!functionId || !invocationId) {return null}@@ -46,14 +109,34 @@ export const parseEmailTrackingCode = (teamId,actionId: actionId || undefined,parentRunId: parentRunId || undefined,+ format,}} 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): string => {- // Generate a base64 encoded string free of equal signs+ const actionId = invocation.state?.actionId ?? ''+ const parentRunId = invocation.parentRunId ?? ''+ const payload = toBase64UrlSafe(+ `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}`+ )+ 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+ }+ 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.+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}`)