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(messaging): protect sensitive data on transactional email templates (#120520)

Harley Alexandercb4e4529d786
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 65a0120794dd..83adc533cf88 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -48,6 +48,7 @@ import {
import { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'
import { checkHogFlowQuotaLimits } from './services/hogflows/hogflow-quota-limiting'
+import { TRANSACTIONAL_EMAIL_EVENT } from './services/hogflows/hogflow-sensitivity'
import { matchesWaitUntilCondition } from './services/hogflows/hogflow-utils'
import { WorkflowStepResumeSchema } from './services/hogflows/step-resume.service'
import {
@@ -1167,7 +1168,7 @@ export class CdpApi {
const event: HogFunctionInvocationGlobals['event'] = {
uuid: new UUIDT().toString(),
- event: '$transactional_email',
+ event: TRANSACTIONAL_EMAIL_EVENT,
distinct_id: distinctId,
timestamp: DateTime.now().toISO(),
url: '',
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index 18ef155c4700..45c95c9aebf5 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -14,6 +14,7 @@ import { HogFunctionManagerService } from '../services/managers/hog-function-man
import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
import {
HogInvocationResultsService,
+ SENSITIVE_VARIABLES_OMITTED,
decodeInvocationGlobals,
} from '../services/monitoring/hog-invocation-results.service'
import {
@@ -767,6 +768,14 @@ export class RerunPaginatorService {
return null
}
const persistedState = parsedGlobals as Record<string, any>
+ if (persistedState[SENSITIVE_VARIABLES_OMITTED]) {
+ logger.warn('⚠️', 'Skipping rerun of a sensitive email whose message data was not stored', {
+ functionId,
+ teamId,
+ invocation_id: row.invocation_id,
+ })
+ return null
+ }
const eventForFilter = persistedState.event ?? {}
const filterGlobals: HogFunctionFilterGlobals = convertToHogFunctionFilterGlobal({
event: eventForFilter,
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index cdf723847b2c..f1481b1034b1 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -243,6 +243,10 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
// When false, no open pixel is injected, links are not rewritten, and the send uses the
// untracked SES configuration set. Absent/true means tracked (existing behavior).
tracking_enabled: z.boolean().optional(),
+ // Set from a transactional template marked sensitive: the stored asset keeps a placeholder instead
+ // of the body, events keep no subject, clicked links keep only their origin, and the run
+ // snapshot keeps no variables.
+ sensitive: z.boolean().optional(),
// When true, links get utm_source, utm_medium and utm_campaign tags they don't already carry.
utm_tags_enabled: z.boolean().optional(),
// Liquid templates that replace the default tag values. An empty value keeps the default.
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 32b5b912b362..5111bd938bbe 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -39,6 +39,7 @@ import { WaitUntilTimeWindowHandler } from './actions/wait_until_time_window'
import { buildConversionWatcher } from './conversion-watcher'
import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'
import { HogFlowFunctionsService } from './hogflow-functions.service'
+import { hasSensitiveEmailStep } from './hogflow-sensitivity'
import {
WorkflowChangedError,
actionIdForLogging,
@@ -95,6 +96,7 @@ export function createHogFlowInvocation(
// manager may be serving a newer version. A message step re-pins this to the version
// that actually sent (see HogFunctionHandler); until then this is the best answer.
flowVersion: hogFlow.version,
+ ...(hasSensitiveEmailStep(hogFlow) ? { sensitive: true } : {}),
},
teamId: hogFlow.team_id,
// The version lives on `state.flowVersion` rather than here — functionId is the cyclotron
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-sensitivity.ts b/nodejs/src/cdp/services/hogflows/hogflow-sensitivity.ts
new file mode 100644
index 000000000000..67971ac50ecb
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/hogflow-sensitivity.ts
@@ -0,0 +1,8 @@
+import { HogFlow } from '../../schema/hogflow'
+
+// The trigger event of every transactional email run. Only transactional templates can be sensitive.
+export const TRANSACTIONAL_EMAIL_EVENT = '$transactional_email'
+
+export const hasSensitiveEmailStep = (hogFlow: Partial<Pick<HogFlow, 'actions'>> | undefined): boolean =>
+ Array.isArray(hogFlow?.actions) &&
+ hogFlow.actions.some((action) => action?.type === 'function_email' && action.config?.sensitive === true)
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index 235f12d934ea..ddfddec81416 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -1042,8 +1042,18 @@ describe('EmailService', () => {
)
})
- it('should send an email if verified', async () => {
- invocation.hogFunction.metadata = { message_category_type: 'transactional' }
+ it.each([
+ ['an ordinary template', {}, [{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) }]],
+ [
+ 'a sensitive template',
+ { sensitive: true },
+ [
+ { Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) },
+ { Name: 'ph_sensitive', Value: 'true' },
+ ],
+ ],
+ ])('should send an email if verified, for %s', async (_name, extraMetadata, expectedTags) => {
+ invocation.hogFunction.metadata = { message_category_type: 'transactional', ...extraMetadata }
sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
const result = await service.executeSendEmail(invocation)
expect(result.error).toBeUndefined()
@@ -1063,7 +1073,7 @@ describe('EmailService', () => {
},
},
Destination: { ToAddresses: ['"Test User" <[email protected]>'] },
- EmailTags: [{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) }],
+ EmailTags: expectedTags,
FeedbackForwardingEmailAddress: '[email protected]',
FromEmailAddress: '"Test User" <[email protected]>',
})
@@ -1779,28 +1789,36 @@ describe('EmailService', () => {
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',
- $email_tracking_enabled: true,
- },
- })
- })
+ it.each([
+ ['an ordinary template', {}, 'Test Subject'],
+ ['a sensitive template', { sensitive: true }, undefined],
+ ])(
+ 'should capture a $workflows_email_sent PostHog event on success, for %s',
+ async (_name, extraMetadata, subject) => {
+ // 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)
+ invocation.hogFunction.metadata = { ...invocation.hogFunction.metadata, ...extraMetadata }
+ 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_tracking_enabled: true,
+ },
+ })
+ expect(result.capturedPostHogEvents[0].properties.$email_subject).toEqual(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.
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 204a87f93836..bfbb4a1d50a9 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -29,6 +29,7 @@ import {
} from './email-tracking.service'
import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'
import { maybeAddPreheaderToEmail } from './helpers/preheader'
+import { SES_SENSITIVE_TAG } from './helpers/ses'
import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'
import { addUtmTagsToEmail, renderUtmOverrides, resolveUtmTags } from './helpers/utm'
import { MessageAssetsService } from './message-assets.service'
@@ -733,7 +734,8 @@ export class EmailService {
$workflow_id: invocation.functionId,
$workflow_action_id: invocation.state.actionId,
$email_to: params.to.email,
- $email_subject: params.subject,
+ // A sensitive template's subject can carry a login code, so its events leave it out.
+ ...(invocation.hogFunction?.metadata?.sensitive === true ? {} : { $email_subject: params.subject }),
// Always set, never conditional: an untracked send can never produce a
// `$workflows_email_opened` or `$workflows_email_link_clicked`, so without this
// dimension on the send there is no way to build an open rate in an insight that
@@ -1135,7 +1137,12 @@ export class EmailService {
ConfigurationSetName: this.resolveConfigurationSetName(trackingEnabled, result.invocation),
// 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 }],
+ EmailTags: [
+ { Name: 'ph_id', Value: shortTrackingCode },
+ ...(result.invocation.hogFunction?.metadata?.sensitive === true
+ ? [{ Name: SES_SENSITIVE_TAG, Value: 'true' }]
+ : []),
+ ],
FeedbackForwardingEmailAddress: from.email,
}
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index d5c5301a6598..ace2fd9dcbb6 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -1,6 +1,7 @@
import { register } from 'prom-client'
import { defaultConfig } from '~/common/config/config'
+import { logger } from '~/common/utils/logger'
import { SesWebhookHandler, normalizeClickUrl, resolveClickDestination } from './ses'
import { EmailTrackingCodeSigner } from './tracking-code'
@@ -131,6 +132,31 @@ describe('SesWebhookHandler', () => {
})
})
+ it('records a click from a sensitive email with only the link origin and no subject', async () => {
+ const body = [
+ {
+ eventType: 'Click',
+ mail: {
+ ...baseMail,
+ commonHeaders: { subject: 'Your login code is 482913' },
+ tags: { ...baseMail.tags, ph_sensitive: ['true'] },
+ },
+ click: {
+ link: 'https://app.posthog.com/reset/Xk3pR9mQ2a?token=s3cret',
+ linkTags: { phl: ['1'] },
+ timestamp: '2025-10-03T12:02:00Z',
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.metrics?.[0].properties).toEqual({
+ $email_to: '[email protected]',
+ $link_url: 'https://app.posthog.com',
+ $link_index: '1',
+ })
+ expect(result.metrics?.[1].instanceIdOverride).toEqual('act789|1|https://app.posthog.com')
+ })
+
it('emits a per-link companion metric keyed by action, link index and normalized url', async () => {
const body = [
{
@@ -608,14 +634,19 @@ describe('SesWebhookHandler', () => {
}
)
- it('returns 200 and no metrics if tracking code is missing from both carriers', async () => {
+ it('returns 200, no metrics and no logged payload if tracking code is missing from both carriers', async () => {
+ const logSpies = (['info', 'warn', 'error'] as const).map((level) => jest.spyOn(logger, level))
const body = [
{
- eventType: 'Open',
- mail: { ...baseMail, tags: {}, headers: [] },
- open: {
- ipAddress: '1.2.3.4',
- userAgent: 'UA',
+ eventType: 'Click',
+ mail: {
+ ...baseMail,
+ commonHeaders: { subject: 'Your login code is 482913' },
+ tags: { ph_sensitive: ['true'] },
+ headers: [],
+ },
+ click: {
+ link: 'https://app.example.com/reset?token=s3cret',
timestamp: '2025-10-03T12:01:00Z',
},
},
@@ -623,6 +654,10 @@ describe('SesWebhookHandler', () => {
const result = await handler.handleWebhook({ body, headers: {} })
expect(result.status).toBe(200)
expect(result.metrics).toEqual([])
+ const logged = JSON.stringify(logSpies.flatMap((spy) => spy.mock.calls))
+ expect(logged).not.toContain('s3cret')
+ expect(logged).not.toContain('482913')
+ logSpies.forEach((spy) => spy.mockRestore())
})
it('labels a dropped record "missing" when no code is present and "invalid" when it is present but unparseable', async () => {
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 7d7e7741ea8b..04a6ced57eac 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -211,6 +211,21 @@ const sesUnattributedEventsCounter = new Counter({
// cheap enough to carry here.
export const SES_LINK_INDEX_TAG = 'phl'
+// SES message tag set at send time on emails whose template is marked sensitive, and echoed back on
+// every event for that message. Such an email's subject and link paths can carry a login code or a
+// reset token, so its events keep no subject and only each clicked link's origin. `$link_index` still
+// tells the links apart.
+export const SES_SENSITIVE_TAG = 'ph_sensitive'
+
+const sensitiveLinkOrigin = (link: string): string => {
+ try {
+ const url = new URL(link)
+ return url.host ? `${url.protocol}//${url.host}` : url.protocol
+ } catch {
+ return ''
+ }
+}
+
// Path of our own click-tracking redirect, which used to wrap every anchor before SES saw it.
const TRACKING_REDIRECT_PATH = '/public/m/redirect'
@@ -598,10 +613,10 @@ export class SesWebhookHandler {
timestamp?: string
}[]
}> {
- logger.info('[SesWebhookHandler] handleWebhook', { body: opts.body, headers: opts.headers })
+ // Payloads carry recipients and clicked links, including reset links from sensitive emails,
+ // so the logs keep identifiers only.
const parsed = this.parseIncomingBody(opts.body)
-
- logger.info('[SesWebhookHandler] parsed', { parsed })
+ logger.info('[SesWebhookHandler] handleWebhook', { mode: parsed.mode })
// 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.
@@ -609,7 +624,10 @@ export class SesWebhookHandler {
if (!('envelope' in parsed)) {
return { status: 403, body: { error: 'Unsigned raw delivery not allowed' } }
}
- logger.info('[SesWebhookHandler] verifying signature', { envelope: parsed.envelope })
+ logger.info('[SesWebhookHandler] verifying signature', {
+ type: parsed.envelope.Type,
+ messageId: parsed.envelope.MessageId,
+ })
const ok = await this.verifySnsSignature(parsed.envelope)
logger.info('[SesWebhookHandler] signature verified', { ok })
if (!ok) {
@@ -698,7 +716,10 @@ export class SesWebhookHandler {
}[] = []
for (const rec of records) {
- logger.info('[SesWebhookHandler] processing record', { rec })
+ logger.info('[SesWebhookHandler] processing record', {
+ eventType: rec.eventType,
+ messageId: rec.mail.messageId,
+ })
// 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`.
@@ -719,7 +740,11 @@ export class SesWebhookHandler {
// record which occurred. An empty `rawCode` means neither carrier held a value.
const reason = rawCode === '' ? 'missing' : 'invalid'
sesUnattributedEventsCounter.inc({ event_type: rec.eventType, reason })
- logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })
+ logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', {
+ eventType: rec.eventType,
+ messageId: rec.mail.messageId,
+ reason,
+ })
continue
}
@@ -728,9 +753,10 @@ 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) {
+ const isSensitive = rec.mail.tags?.[SES_SENSITIVE_TAG]?.[0] === 'true'
const properties: Record<string, any> = {
$email_to: rec.mail.destination?.[0],
- $email_subject: rec.mail.commonHeaders?.subject,
+ ...(isSensitive ? {} : { $email_subject: rec.mail.commonHeaders?.subject }),
}
// Each SES event detail carries its own timestamp (open.timestamp, click.timestamp, etc.)
@@ -741,7 +767,8 @@ export class SesWebhookHandler {
timestamp = rec.open.timestamp
} else if ('click' in rec && rec.click) {
timestamp = rec.click.timestamp
- properties.$link_url = resolveClickDestination(rec.click.link)
+ const destination = resolveClickDestination(rec.click.link)
+ properties.$link_url = isSensitive ? sensitiveLinkOrigin(destination) : destination
const linkIndex = rec.click.linkTags?.[SES_LINK_INDEX_TAG]?.[0]
if (linkIndex !== undefined) {
properties.$link_index = linkIndex
@@ -797,7 +824,9 @@ export class SesWebhookHandler {
instanceIdOverride: buildLinkInstanceId(
actionId,
rec.click.linkTags?.[SES_LINK_INDEX_TAG]?.[0] ?? '',
- normalizeClickUrl(resolveClickDestination(rec.click.link))
+ isSensitive
+ ? sensitiveLinkOrigin(resolveClickDestination(rec.click.link))
+ : normalizeClickUrl(resolveClickDestination(rec.click.link))
),
timestamp,
workflowVersion,
diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.test.ts b/nodejs/src/cdp/services/messaging/message-assets.service.test.ts
index 595d19340105..8919ec5fbc78 100644
--- a/nodejs/src/cdp/services/messaging/message-assets.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/message-assets.service.test.ts
@@ -129,6 +129,28 @@ describe('MessageAssetsService', () => {
expect(row!.recipient).toBe('[email protected]')
expect(row!.subject).toBe('Welcome aboard')
})
+
+ it('keeps a placeholder instead of the body when the template is marked sensitive', () => {
+ const invocation = invocationWithAction('flow-1')
+ invocation.hogFunction.metadata = { message_category_type: 'transactional', sensitive: true }
+ invocation.hogFunction.inputs = { email: { value: { subject: 'Your code is {{ variables.code }}' } } }
+
+ const row = service.buildRowForEmail(
+ invocation,
+ emailParams({
+ subject: 'Your code is 482913',
+ html: '<a href="https://example.com/reset?token=s3cret">Reset</a>',
+ })
+ )
+
+ expect(row).toMatchObject({
+ recipient: '[email protected]',
+ subject: 'Your code is {{ variables.code }}',
+ status: 'sent',
+ })
+ expect(row!.html).toContain('Email body not stored')
+ expect(row!.html).not.toContain('s3cret')
+ })
})
describe('buildRowForPush', () => {
diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.ts b/nodejs/src/cdp/services/messaging/message-assets.service.ts
index a0d041c5a5d2..4fb0d62fc361 100644
--- a/nodejs/src/cdp/services/messaging/message-assets.service.ts
+++ b/nodejs/src/cdp/services/messaging/message-assets.service.ts
@@ -108,6 +108,14 @@ const oversizedPlaceholderHtml = (bytes: number): string => {
return `<!doctype html><meta charset="utf-8"><div style="padding:1rem;font-family:ui-sans-serif,system-ui,sans-serif;color:#555;max-width:640px;margin:2rem auto"><h3 style="margin:0 0 0.5rem">Email too large to capture</h3><p style="margin:0">The rendered email was ${mb}&nbsp;MB, which exceeds the ${MAX_HTML_BYTES / 1024 / 1024}&nbsp;MB capture limit. The send itself succeeded — this placeholder is stored so the &ldquo;View email&rdquo; link works, but the original body is not viewable here.</p></div>`
}
+// Stored instead of the body when the template is marked sensitive, so the person view still shows the send.
+const SENSITIVE_PLACEHOLDER_HTML = `<!doctype html><meta charset="utf-8"><div style="padding:1rem;font-family:ui-sans-serif,system-ui,sans-serif;color:#555;max-width:640px;margin:2rem auto"><h3 style="margin:0 0 0.5rem">Email body not stored</h3><p style="margin:0">This email was sent. Its template is marked sensitive, so PostHog doesn't keep a copy of its content.</p></div>`
+
+const sensitiveSubject = (invocation: CyclotronJobInvocationHogFunction): string => {
+ const subject = invocation.hogFunction.inputs?.email?.value?.subject
+ return typeof subject === 'string' ? subject : 'Subject not stored'
+}
+
/**
* Buffers rendered-email snapshots and flushes them as a single bulk Kafka
* produce at the batch boundary — one round-trip per partition for the whole
@@ -138,8 +146,11 @@ export class MessageAssetsService {
return null
}
const bodyBytes = Buffer.byteLength(body, 'utf8')
+ const sensitive = invocation.hogFunction.metadata?.sensitive === true
let html = body
- if (bodyBytes > MAX_HTML_BYTES) {
+ if (sensitive) {
+ html = SENSITIVE_PLACEHOLDER_HTML
+ } else if (bodyBytes > MAX_HTML_BYTES) {
counterMessageAssetsTruncated.inc()
html = oversizedPlaceholderHtml(bodyBytes)
}
@@ -154,7 +165,9 @@ export class MessageAssetsService {
distinct_id: resolveEmailEngagementDistinctId(invocation) ?? '',
person_id: invocation.state.globals.person?.id ?? '',
recipient: params.to.email,
- subject: params.subject,
+ // A sensitive template's rendered subject can carry a login code, so the row keeps the unrendered
+ // template subject, which still names the email without the values.
+ subject: sensitive ? sensitiveSubject(invocation) : params.subject,
status: 'sent',
sent_at: isoMicroseconds(new Date()),
version: microsecondsSinceEpoch(),
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
index a1001161a2f9..4d14cf409695 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
@@ -3,7 +3,9 @@ import { DateTime } from 'luxon'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { parseJSON } from '~/common/utils/json-parse'
+import { FixtureHogFlowBuilder } from '../../_tests/builders/hogflow.builder'
import { createExampleInvocation } from '../../_tests/fixtures'
+import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'
import { CdpOutput } from '../../cdp-services'
import {
HogInvocationResultRow,
@@ -142,6 +144,43 @@ describe('HogInvocationResultsService', () => {
expect(decoded).not.toContain('abc123')
})
+ it.each([
+ ['an ordinary email', false, {}, { code: '482913' }],
+ ['a sensitive email', true, {}, undefined],
+ ['a recovery stub of a sensitive run', undefined, { sensitive: true }, undefined],
+ [
+ 'a recovery stub of an unstamped transactional run',
+ undefined,
+ { event: { event: '$transactional_email' } },
+ undefined,
+ ],
+ ['a recovery stub of an ordinary run', undefined, {}, { code: '482913' }],
+ ])('keeps the message data in a workflow snapshot only for %s', async (_name, sensitive, state, variables) => {
+ const hogFlow =
+ sensitive === undefined
+ ? ({ id: 'flow-1' } as any)
+ : new FixtureHogFlowBuilder()
+ .withWorkflow({
+ actions: {
+ email: {
+ type: 'function_email',
+ config: { template_id: 'template-email', sensitive, inputs: {} },
+ } as any,
+ },
+ edges: [],
+ })
+ .build()
+ const invocation = createExampleHogFlowInvocation(hogFlow, { variables: { code: '482913' } })
+ Object.assign(invocation.state, state, { event: { ...invocation.state.event, ...(state as any).event } })
+ await expect(service.recordTerminalFailureDurably(invocation)).resolves.toBe(true)
+
+ const globals = (await decodeInvocationGlobals(parseProducedRows(outputs)[0].invocation_globals)) as Record<
+ string,
+ any
+ >
+ expect(globals.variables).toEqual(variables)
+ })
+
it('strips groups and person from invocation_globals — rebuilt downstream on rerun', async () => {
const invocation = createExampleInvocation({}, {
groups: {
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
index 2fadfa43abed..379df2ee06ee 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
@@ -17,6 +17,7 @@ import {
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
} from '../../types'
+import { TRANSACTIONAL_EMAIL_EVENT, hasSensitiveEmailStep } from '../hogflows/hogflow-sensitivity'
const counterHogInvocationResultRowsProduced = new Counter({
name: 'cdp_hog_invocation_result_rows_produced',
@@ -203,7 +204,13 @@ const extractTriggerFields = (
// current hog function config + integration store, so this is also a no-op
// for rerun correctness — we'll always pick up the latest secrets, not a
// snapshot from when the original invocation ran.
-const stripInputs = <T>(value: T): T => {
+const INPUT_KEYS: ReadonlySet<string> = new Set(['inputs'])
+// A sensitive email's message data carries reset links and login codes, so its snapshot keeps no
+// variables either, and a rerun can't rebuild the send.
+const SENSITIVE_KEYS: ReadonlySet<string> = new Set(['inputs', 'variables'])
+export const SENSITIVE_VARIABLES_OMITTED = 'sensitive_variables_omitted'
+
+const stripKeys = <T>(value: T, keys: ReadonlySet<string>): T => {
if (value === null || typeof value !== 'object') {
return value
}
@@ -211,15 +218,15 @@ const stripInputs = <T>(value: T): T => {
// We don't expect inputs to live inside arrays today; this branch is a
// defensive cheap pass-through so a future schema change doesn't have
// to come back here.
- return value.map((item) => stripInputs(item)) as unknown as T
+ return value.map((item) => stripKeys(item, keys)) as unknown as T
}
const obj = value as Record<string, unknown>
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(obj)) {
- if (k === 'inputs') {
+ if (keys.has(k)) {
continue
}
- out[k] = stripInputs(v)
+ out[k] = stripKeys(v, keys)
}
return out as T
}
@@ -229,16 +236,34 @@ const stripInputs = <T>(value: T): T => {
// rehydrates `groups`/`person` (loadHogFunctions) and the executor rebuilds
// `inputs` when an invocation arrives without them — so the rerun reconstructs
// everything from the event against the latest config. `inputs` must be
-// dropped anyway for security (resolved secrets — see `stripInputs`).
+// dropped anyway for security (resolved secrets — see `stripKeys`).
+// Recovery paths pass a workflow stub with only an id. A run that started before its template became
+// sensitive carries no stamp, so a transactional email run without the actions is treated as sensitive.
+const sendsSensitiveEmail = (invocation: CyclotronJobInvocationHogFlow): boolean => {
+ if (invocation.state?.sensitive === true) {
+ return true
+ }
+ if (!Array.isArray(invocation.hogFlow?.actions)) {
+ return invocation.state?.event?.event === TRANSACTIONAL_EMAIL_EVENT
+ }
+ return hasSensitiveEmailStep(invocation.hogFlow)
+}
+
const serializeInvocationGlobals = (invocation: CyclotronJobInvocation): string => {
if (isHogFunctionInvocation(invocation)) {
const { groups: _groups, person: _person, ...globals } = invocation.state.globals
- return JSON.stringify(stripInputs(globals))
+ return JSON.stringify(stripKeys(globals, INPUT_KEYS))
}
if (isHogFlowInvocation(invocation)) {
// Hog flow state can carry a per-action `currentAction.hogFunctionState.globals.inputs`
- // — `stripInputs` walks the tree and removes those too.
- return JSON.stringify(stripInputs(invocation.state ?? {}))
+ // — `stripKeys` walks the tree and removes those too.
+ if (sendsSensitiveEmail(invocation)) {
+ return JSON.stringify({
+ ...stripKeys(invocation.state ?? {}, SENSITIVE_KEYS),
+ [SENSITIVE_VARIABLES_OMITTED]: true,
+ })
+ }
+ return JSON.stringify(stripKeys(invocation.state ?? {}, INPUT_KEYS))
}
return '{}'
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 858ef2adb310..84024f82610f 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -468,6 +468,9 @@ export type HogFlowInvocationContext = {
// Absent on runs parked before this was introduced — those attribute to no version at all
// rather than to a wrong one.
flowVersion?: number
+ // Stamped at run start and persisted with the state, so a recovery path that holds only the
+ // workflow id still keeps a sensitive run's message data out of its snapshot.
+ sensitive?: boolean
actionStepCount: number
// Missing on legacy runs, which must keep run:action keys even when no function state was persisted.
customerTaskIdempotencyVersion?: 1
diff --git a/products/messaging/backend/facade/templates.py b/products/messaging/backend/facade/templates.py
index 91fa113d6cfc..4ddaca4df6d0 100644
--- a/products/messaging/backend/facade/templates.py
+++ b/products/messaging/backend/facade/templates.py
@@ -36,6 +36,7 @@ class MessageTemplateRow:
deleted: bool
transactional_hog_flow_id: UUID | None
draft_content: dict[str, Any] | None
+ sensitive: bool
def _to_contract(row: MessageTemplate) -> MessageTemplateRow:
@@ -52,6 +53,7 @@ def _to_contract(row: MessageTemplate) -> MessageTemplateRow:
deleted=row.deleted,
transactional_hog_flow_id=row.transactional_hog_flow_id,
draft_content=row.draft_content,
+ sensitive=row.sensitive,
)
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 2a2980ea374c..52abf0918117 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -207,6 +207,11 @@ class MessageTemplateSerializer(serializers.Serializer):
deleted = serializers.BooleanField(
required=False, help_text="Soft-delete flag. Set true to remove the template from the library."
)
+ sensitive = serializers.BooleanField(
+ required=False,
+ help_text="For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent "
+ "email's body or filled-in subject, and clicked links keep only the site address. Can change at any time.",
+ )
transactional_hog_flow_id = serializers.UUIDField(
read_only=True,
allow_null=True,
diff --git a/products/messaging/backend/services/transactional_email.py b/products/messaging/backend/services/transactional_email.py
index ef62de81b0d6..28c162a366a5 100644
--- a/products/messaging/backend/services/transactional_email.py
+++ b/products/messaging/backend/services/transactional_email.py
@@ -67,6 +67,7 @@ def _content(template: MessageTemplate, from_integration_id: int | None) -> Tran
text=email.get("text") or "",
from_integration_id=from_integration_id,
message_category_id=template.message_category_id,
+ sensitive=template.sensitive,
)
diff --git a/products/messaging/backend/tests/api/test_message_templates.py b/products/messaging/backend/tests/api/test_message_templates.py
index e02d8f6fc09b..e65057fc9481 100644
--- a/products/messaging/backend/tests/api/test_message_templates.py
+++ b/products/messaging/backend/tests/api/test_message_templates.py
@@ -140,11 +140,14 @@ class TestMessageTemplatesAPI(APIBaseTest):
"name": "Valid Template",
"content": {"email": {"subject": "Hello", "html": "<p>Hello</p>"}},
"type": "email",
+ "sensitive": True,
},
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
assert response.json()["name"] == "Valid Template"
+ assert response.json()["sensitive"] is True
+ assert MessageTemplate.objects.get(id=response.json()["id"]).sensitive is True
assert response.json()["content"]["email"]["subject"] == "Hello"
# The AI-first experiment counts creations from the editor and the agent with this one event.
mock_report.assert_called_once()
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 9721de92e8d2..1d6365fe58a4 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -397,6 +397,8 @@ export interface MessageTemplateApi {
message_category?: string | null
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
+ /** For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time. */
+ sensitive?: boolean
/**
* The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
@@ -441,6 +443,8 @@ export interface PatchedMessageTemplateApi {
message_category?: string | null
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
+ /** For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time. */
+ sensitive?: boolean
/**
* The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index d94129d9c234..748b379518df 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -346,6 +346,12 @@ export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Message category ID to file the template under. Must belong to the same project.'),
deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),
+ sensitive: zod
+ .boolean()
+ .optional()
+ .describe(
+ "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time."
+ ),
draft_content: zod
.union([
zod.object({
@@ -520,6 +526,12 @@ export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Message category ID to file the template under. Must belong to the same project.'),
deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),
+ sensitive: zod
+ .boolean()
+ .optional()
+ .describe(
+ "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time."
+ ),
draft_content: zod
.union([
zod.object({
@@ -695,6 +707,12 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Message category ID to file the template under. Must belong to the same project.'),
deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),
+ sensitive: zod
+ .boolean()
+ .optional()
+ .describe(
+ "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time."
+ ),
draft_content: zod
.union([
zod.object({
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index ad8a510fccec..c20ef4276fdf 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -583,6 +583,8 @@ class TransactionalEmailContent:
# None uses the project's default sender on create, and keeps the workflow's sender on update.
from_integration_id: int | None
message_category_id: UUID | None
+ # Sends keep a placeholder instead of the body, and clicks drop the link's query string.
+ sensitive: bool = False
class TransactionalEmailSenderUnavailable(Exception):
diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.py
index 5f247b6d0a04..15717ac9c0c1 100644
--- a/products/workflows/backend/services/hog_flow_writes.py
+++ b/products/workflows/backend/services/hog_flow_writes.py
@@ -112,6 +112,26 @@ def _save_live(instance: HogFlow, validated_data: dict, **overrides: object) ->
instance.save()
+def _keep_live_sensitivity(before: HogFlow, validated_data: dict) -> dict:
+ # A transactional email's protection follows its template, and only the template sync writes it.
+ # Every other write, such as publishing a restored version, keeps the live setting.
+ if before.origin_product != HogFlow.OriginProduct.TRANSACTIONAL_EMAILS or "actions" not in validated_data:
+ return validated_data
+ sensitive = any(
+ isinstance(action, dict)
+ and action.get("type") == "function_email"
+ and (action.get("config") or {}).get("sensitive") is True
+ for action in before.actions or []
+ )
+ actions = [
+ {**action, "config": {**(action.get("config") or {}), "sensitive": sensitive}}
+ if isinstance(action, dict) and action.get("type") == "function_email"
+ else action
+ for action in validated_data["actions"] or []
+ ]
+ return {**validated_data, "actions": actions}
+
+
def save_validated_workflow(*, team_id: int, hog_flow_id: UUID, validated_data: dict) -> None:
"""Write a workflow's validated fields to the live row, with no draft routing, revision bump or
follow-ups. For callers outside a request: enabling a workflow and the bytecode refresh."""
@@ -294,6 +314,7 @@ def update_workflow(
base_live_updated_at: Optional[str],
includes_staged_draft: bool,
validated_status: str,
+ keeps_live_sensitivity: bool = True,
) -> WorkflowWriteResult:
# Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.
# If the stored row is strictly newer, another channel (a second UI tab, MCP, or the API) wrote in
@@ -355,6 +376,8 @@ def update_workflow(
_save_live(instance, remaining)
else:
validated_data = _derive_from_locked_graph(before_update, validated_data)
+ if keeps_live_sensitivity:
+ validated_data = _keep_live_sensitivity(before_update, validated_data)
_refresh_action_redirects(instance, before_update, validated_data.get("actions"))
bump = _stage_revision_bump(instance, before_update, validated_data)
if clears_staged_draft:
@@ -413,6 +436,7 @@ def edit_workflow_content(
validated_data = edit(to_edit_state(locked), base_actions, base_edges)
before_update = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)
+ validated_data = _keep_live_sensitivity(before_update, validated_data)
if route_to_draft:
_write_draft(locked, locked, validated_data)
else:
@@ -456,7 +480,7 @@ def publish_draft(
before_update = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)
# The draft goes back through the normal serializer so publish revalidates strictly and
# recompiles bytecode - a stored blob is never trusted to be execution-ready.
- validated_data = validate(to_edit_state(locked), dict(locked.draft))
+ validated_data = _keep_live_sensitivity(before_update, validate(to_edit_state(locked), dict(locked.draft)))
_refresh_action_redirects(locked, before_update, validated_data.get("actions"))
bump = _stage_revision_bump(locked, before_update, validated_data)
# Validation recovered the draft's secrets (from the merged live+draft encrypted maps), and
diff --git a/products/workflows/backend/services/transactional_email_workflows.py b/products/workflows/backend/services/transactional_email_workflows.py
index e02cbbc5aff8..e9e6ef1b8483 100644
--- a/products/workflows/backend/services/transactional_email_workflows.py
+++ b/products/workflows/backend/services/transactional_email_workflows.py
@@ -54,6 +54,7 @@ def transactional_email_actions(content: TransactionalEmailContent, from_integra
"message_category_id": str(content.message_category_id) if content.message_category_id else None,
# Puts the send on the email queue's fast lane and skips marketing opt-outs.
"message_category_type": "transactional",
+ "sensitive": content.sensitive,
"inputs": {
"email": {
"templating": "liquid",
@@ -166,4 +167,5 @@ def update_transactional_email_workflow(
base_live_updated_at=None,
includes_staged_draft=False,
validated_status=flow.status,
+ keeps_live_sensitivity=False,
)
diff --git a/products/workflows/backend/test/test_transactional_email_workflows.py b/products/workflows/backend/test/test_transactional_email_workflows.py
index 227ab83e7d6b..bcdb89b99817 100644
--- a/products/workflows/backend/test/test_transactional_email_workflows.py
+++ b/products/workflows/backend/test/test_transactional_email_workflows.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from posthog.models import Team
from posthog.models.integration import Integration
+from posthog.models.scoping import team_scope
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from products.cdp.backend.templates.hog_function_template import sync_template_to_db
@@ -24,6 +25,8 @@ from products.workflows.backend.facade.transactional_emails import (
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
from products.workflows.backend.presentation.views.hog_flow import HogFlowSerializer
+from products.workflows.backend.services.hog_flow_revisions import restore_revision
+from products.workflows.backend.services.hog_flow_writes import publish_confirm_value, publish_draft
def _content(
@@ -31,6 +34,7 @@ def _content(
from_integration_id: int | None = None,
html: str = "<a href='{{ variables.link }}'>Reset</a>",
text: str = "Reset: {{ variables.link }}",
+ sensitive: bool = False,
) -> TransactionalEmailContent:
return TransactionalEmailContent(
message_template_id=uuid4(),
@@ -41,6 +45,7 @@ def _content(
text=text,
from_integration_id=from_integration_id,
message_category_id=None,
+ sensitive=sensitive,
)
@@ -65,10 +70,11 @@ class TestTransactionalEmailWorkflows(BaseTest):
team_id=self.team.id,
user_id=self.user.id,
hog_flow_id=flow_id,
- content=_content(subject="New subject"),
+ content=_content(subject="New subject", sensitive=True),
)
flow = HogFlow.objects.get(id=flow_id)
+ assert flow.actions[1]["config"]["sensitive"] is True
assert flow.status == HogFlow.State.ACTIVE
assert flow.origin_product == "transactional_emails"
assert flow.version == 2
@@ -83,6 +89,25 @@ class TestTransactionalEmailWorkflows(BaseTest):
)
assert list(versions) == [1, 2]
+ def test_publishing_an_older_version_keeps_the_protection_set_on_the_template(self):
+ flow_id = create_transactional_email_workflow(team_id=self.team.id, user_id=self.user.id, content=_content())
+ update_transactional_email_workflow(
+ team_id=self.team.id, user_id=self.user.id, hog_flow_id=flow_id, content=_content(sensitive=True)
+ )
+
+ with team_scope(self.team.id):
+ restore_revision(hog_flow_id=flow_id, version=1, overwrite=False, expected_draft_updated_at=None)
+ draft_updated_at = HogFlow.objects.get(id=flow_id).draft_updated_at
+ publish_draft(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ hog_flow_id=flow_id,
+ previewed_value=publish_confirm_value(hog_flow_id=flow_id, draft_updated_at=draft_updated_at),
+ validate=lambda _state, content: content,
+ )
+
+ assert HogFlow.objects.get(id=flow_id).actions[1]["config"]["sensitive"] is True
+
def test_the_stored_workflow_passes_the_workflows_api_validation(self):
flow = HogFlow.objects.get(
id=create_transactional_email_workflow(team_id=self.team.id, user_id=self.user.id, content=_content())
diff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
index f5494845e0b0..885f5ce10d86 100644
--- a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx
@@ -1,12 +1,14 @@
import { BindLogic, useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { IconTrash } from '@posthog/icons'
+import { IconLock, IconTrash } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
+ LemonCard,
LemonDivider,
LemonMenuOverlay,
+ LemonSwitch,
LemonTag,
Spinner,
SpinnerOverlay,
@@ -66,6 +68,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem
keepMyTemplateVersion,
setTransactionalTab,
discardDraft,
+ setSensitive,
} = useActions(logic)
const {
template,
@@ -84,6 +87,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem
hasUnsavedChanges,
isSavingDraft,
isDiscardingDraft,
+ isSavingSensitive,
} = useValues(logic)
const transactionalEmailsEnabled = useFeatureFlag('WORKFLOWS_TRANSACTIONAL_EMAIL_API')
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
@@ -170,7 +174,31 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem
key: 'api',
label: 'API',
content: transactionalHogFlowId ? (
- <TransactionalEmailApiExample templateId={props.id} />
+ <div className="flex flex-col gap-4">
+ <LemonCard hoverEffect={false} className="max-w-200 p-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex items-start gap-3 min-w-0">
+ <IconLock className="text-xl text-secondary shrink-0 mt-0.5" />
+ <div className="min-w-0">
+ <div className="font-semibold">Protect sensitive data</div>
+ <p className="text-secondary text-sm m-0 mt-1">
+ For emails with login codes or reset links. PostHog keeps no copy of
+ what each email contained, and clicked links keep only the site address.
+ </p>
+ </div>
+ </div>
+ <LemonSwitch
+ checked={!!originalTemplate.sensitive}
+ onChange={setSensitive}
+ loading={isSavingSensitive}
+ disabledReason={isSavingSensitive ? 'Saving the setting' : undefined}
+ aria-label="Protect sensitive data"
+ data-attr="message-template-sensitive-toggle"
+ />
+ </div>
+ </LemonCard>
+ <TransactionalEmailApiExample templateId={props.id} />
+ </div>
) : (
<MakeTransactionalPrompt {...props} />
),
@@ -202,6 +230,18 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem
<LemonTag type="success" className="ml-1">
Transactional
</LemonTag>
+ {originalTemplate.sensitive && (
+ <Tooltip title="PostHog keeps no copy of what each email contained, and clicked links keep only the site address.">
+ <LemonTag
+ type="highlight"
+ icon={<IconLock />}
+ className="ml-1"
+ data-attr="message-template-sensitive-tag"
+ >
+ Sensitive
+ </LemonTag>
+ </Tooltip>
+ )}
{(hasDraft || hasUnsavedChanges) && (
<Tooltip title="Your changes save as a draft. Sends use the live version until you publish.">
<LemonTag
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
index 5a5aef1b91cd..82ec3c92b9cb 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts
@@ -340,6 +340,7 @@ describe('messageTemplateLogic', () => {
content: live,
draft_content: draft,
transactional_hog_flow_id: 'flow-id',
+ sensitive: false,
updated_at: '2026-01-01T00:00:00Z',
}
let bodies: Record<string, unknown>[]
@@ -403,6 +404,17 @@ describe('messageTemplateLogic', () => {
expect(bodies).toEqual([{ draft_content: edited }])
})
+ it('protecting sensitive data saves only the flag, so the draft stays unpublished', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setSensitive(true)
+ }).toDispatchActions(['setSensitiveDone'])
+
+ expect(bodies).toEqual([{ sensitive: true }])
+ expect(logic.values.originalTemplate.sensitive).toBe(true)
+ expect(logic.values.templateChanged).toBe(false)
+ expect(logic.values.hasDraft).toBe(true)
+ })
+
it('publishing sends the content and leaves no draft behind', async () => {
await expectLogic(logic, () => {
logic.actions.submitTemplate()
@@ -413,6 +425,7 @@ describe('messageTemplateLogic', () => {
expect(bodies).toHaveLength(1)
expect(bodies[0].content).toEqual(draft)
expect(bodies[0]).not.toHaveProperty('draft_content')
+ expect(bodies[0]).not.toHaveProperty('sensitive')
})
})
diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
index 900ad72d28a4..f5bafce1ea72 100644
--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts
@@ -3,6 +3,7 @@ import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { beforeUnload, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import { LemonDialog } from '@posthog/lemon-ui'
@@ -62,6 +63,7 @@ export interface messageTemplateLogicValues {
isDiscardingDraft: boolean
isMakingTransactional: boolean
isSavingDraft: boolean
+ isSavingSensitive: boolean
isSyncingExternalEdit: boolean
isTemplateSubmitting: boolean
isTemplateValid: boolean
@@ -87,6 +89,7 @@ export interface messageTemplateLogicValues {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
},
@@ -110,6 +113,7 @@ export interface messageTemplateLogicValues {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
},
@@ -195,6 +199,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}) => {
@@ -209,6 +214,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}
@@ -266,6 +272,12 @@ export interface messageTemplateLogicActions {
setOriginalTemplate: (template: MessageTemplate) => {
template: MessageTemplate
}
+ setSensitive: (sensitive: boolean) => {
+ sensitive: boolean
+ }
+ setSensitiveDone: () => {
+ value: true
+ }
setSyncingExternalEdit: (syncing: boolean) => {
syncing: boolean
}
@@ -297,6 +309,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}>
@@ -312,6 +325,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}>
@@ -340,6 +354,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}) => {
@@ -354,6 +369,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}
@@ -369,6 +385,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}) => {
@@ -383,6 +400,7 @@ export interface messageTemplateLogicActions {
draft_content?: MessageTemplateContentApi | null | undefined
id: string
name: string
+ sensitive?: boolean | undefined
transactional_hog_flow_id?: string | null | undefined
updated_at: string | null
}
@@ -462,6 +480,8 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
setSyncingExternalEdit: (syncing: boolean) => ({ syncing }),
makeTransactional: true,
makeTransactionalDone: (hogFlowId: string | null) => ({ hogFlowId }),
+ setSensitive: (sensitive: boolean) => ({ sensitive }),
+ setSensitiveDone: true,
setTransactionalTab: (tab: TransactionalTemplateTab) => ({ tab }),
setDraftState: (draft: TemplateContent | null, published: TemplateContent) => ({ draft, published }),
autoSaveDraft: true,
@@ -519,6 +539,13 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
makeTransactionalDone: () => false,
},
],
+ isSavingSensitive: [
+ false,
+ {
+ setSensitive: () => true,
+ setSensitiveDone: () => false,
+ },
+ ],
// The draft as last saved, and the content sends use. Both come from the server.
savedDraft: [
null as TemplateContent | null,
@@ -648,11 +675,13 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
return form
},
saveTemplate: async (template) => {
- // Saving the content publishes it, and the server clears the draft.
+ // Saving the content publishes it, and the server clears the draft. The sensitive setting
+ // saves on its own, so a publish never sends it and can't undo a change still in flight.
+ const { sensitive: _sensitive, ...content } = template
const saved =
template.id === 'new'
? await api.messaging.createTemplate(template)
- : await api.messaging.updateTemplate(template.id, template)
+ : await api.messaging.updateTemplate(template.id, content)
const { form, draft, published } = splitDraft(saved)
actions.setDraftState(draft, published)
return form
@@ -679,6 +708,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
if (
values.templateLoading ||
values.isMakingTransactional ||
+ values.isSavingSensitive ||
values.isSavingDraft ||
values.isDiscardingDraft
) {
@@ -815,6 +845,26 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([
lemonToast.error(error?.detail ?? 'Could not make the template transactional.')
}
},
+ setSensitive: async ({ sensitive }) => {
+ try {
+ // Saved on its own, so it applies to sends at once and leaves any content draft untouched.
+ const updated = await messagingTemplatesPartialUpdate(String(values.currentTeamIdStrict), props.id, {
+ sensitive,
+ })
+ const changes = { sensitive: updated.sensitive, updated_at: updated.updated_at }
+ actions.setOriginalTemplate({ ...values.originalTemplate, ...changes })
+ if (values.templateChanged) {
+ actions.setTemplateValues(changes)
+ } else {
+ actions.resetTemplate({ ...values.template, ...changes })
+ }
+ posthog.capture('email template sensitive changed', { template_id: props.id, sensitive })
+ } catch (error: any) {
+ lemonToast.error(error?.detail ?? "Couldn't change the setting. Try again.")
+ }
+ actions.setSensitiveDone()
+ actions.replayDeferredExternalEdit()
+ },
loadTemplateFailure: () => {
// The form is still the stale copy. The banner keeps the conflict visible and offers the retry.
if (values.isSyncingExternalEdit) {
diff --git a/products/workflows/frontend/TemplateLibrary/types.ts b/products/workflows/frontend/TemplateLibrary/types.ts
index 68af8ed5b4ce..b7abd6019c09 100644
--- a/products/workflows/frontend/TemplateLibrary/types.ts
+++ b/products/workflows/frontend/TemplateLibrary/types.ts
@@ -17,4 +17,5 @@ export interface MessageTemplate {
created_by: UserBasicType | null
transactional_hog_flow_id?: MessageTemplateApi['transactional_hog_flow_id']
draft_content?: MessageTemplateApi['draft_content']
+ sensitive?: MessageTemplateApi['sensitive']
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 759785b86ee4..e03a0a0a3b52 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -68446,6 +68446,8 @@ export namespace Schemas {
message_category?: string | null;
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
+ /** For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time. */
+ sensitive?: boolean;
/**
* The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
@@ -84405,6 +84407,8 @@ export namespace Schemas {
message_category?: string | null;
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
+ /** For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time. */
+ sensitive?: boolean;
/**
* The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.ts
index b14e2124fd18..6f2070c225fb 100644
--- a/services/mcp/src/generated/email_templates/api.ts
+++ b/services/mcp/src/generated/email_templates/api.ts
@@ -116,6 +116,12 @@ export const MessagingTemplatesCreateBody = () => zod.object({
.nullish()
.describe('Message category ID to file the template under. Must belong to the same project.'),
deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),
+ sensitive: zod
+ .boolean()
+ .optional()
+ .describe(
+ "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time."
+ ),
})
export const MessagingTemplatesRetrieveParams = () => zod.object({
@@ -224,6 +230,12 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
.nullish()
.describe('Message category ID to file the template under. Must belong to the same project.'),
deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),
+ sensitive: zod
+ .boolean()
+ .optional()
+ .describe(
+ "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time."
+ ),
})
export const MessagingTemplatesDesignPartialUpdateParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.ts
index 7a39142642a4..316692ea3039 100644
--- a/services/mcp/src/tools/generated/email_templates.ts
+++ b/services/mcp/src/tools/generated/email_templates.ts
@@ -40,6 +40,9 @@ const workflowsCreateEmailTemplate = (): ToolBase<
if (params.deleted !== undefined) {
body['deleted'] = params.deleted
}
+ if (params.sensitive !== undefined) {
+ body['sensitive'] = params.sensitive
+ }
const result = await context.api.request<Schemas.MessageTemplate>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/`,
@@ -202,6 +205,9 @@ const workflowsUpdateEmailTemplate = (): ToolBase<
if (params.deleted !== undefined) {
body['deleted'] = params.deleted
}
+ if (params.sensitive !== undefined) {
+ body['sensitive'] = params.sensitive
+ }
const result = await context.api.request<Schemas.MessageTemplate>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
index 3c07f5185db1..e1a73f067ef9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
@@ -120,6 +120,10 @@
"maxLength": 400,
"type": "string"
},
+ "sensitive": {
+ "description": "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time.",
+ "type": "boolean"
+ },
"type": {
"description": "Message channel of the template. Currently 'email'.",
"maxLength": 24,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
index ca9e1972466e..03e3c404741a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
@@ -124,6 +124,10 @@
"maxLength": 400,
"type": "string"
},
+ "sensitive": {
+ "description": "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time.",
+ "type": "boolean"
+ },
"type": {
"description": "Message channel of the template. Currently 'email'.",
"maxLength": 24,