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(cdp): add the opt out of messages async function and template (#121239)

Harley Alexanderd5b513e22a57
diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.ts
index f584e4725752..2369b978136f 100644
--- a/nodejs/src/cdp/async-functions/index.ts
+++ b/nodejs/src/cdp/async-functions/index.ts
@@ -5,6 +5,7 @@ import './create-customer-task'
import './create-task'
import './customer_analytics'
import './fetch-handler'
+import './opt-out-of-messages'
import './replay-vision-scan'
import './run-scout'
import './send-email'
diff --git a/nodejs/src/cdp/async-functions/opt-out-of-messages.ts b/nodejs/src/cdp/async-functions/opt-out-of-messages.ts
new file mode 100644
index 000000000000..0529b8b675cf
--- /dev/null
+++ b/nodejs/src/cdp/async-functions/opt-out-of-messages.ts
@@ -0,0 +1,70 @@
+import { DateTime } from 'luxon'
+
+import { HogFlow } from '~/cdp/schema/hogflow'
+import { defaultConfig } from '~/common/config/config'
+
+import { registerAsyncFunction } from '../async-function-registry'
+import { PosthogJwtAudience } from '../utils/jwt-utils'
+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'
+import { callInternalApi } from './internal-api-call'
+
+let messageOptOutJwt: ScopedServiceJwt | undefined
+const getMessageOptOutJwt = (): ScopedServiceJwt =>
+ (messageOptOutJwt ??= new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOW_MESSAGE_OPT_OUT,
+ defaultConfig.WORKFLOW_MESSAGE_OPT_OUT_JWT_SECRET
+ ))
+
+const OPT_OUT_TIMEOUT_MS = 10_000
+
+// The step test panel mocks async functions by default, so `mock` runs these checks too.
+const parsePayload = (args: any[]): { category_id: string; identifier: string } => {
+ const [payload] = args as [{ category_id?: unknown; identifier?: unknown } | undefined]
+ const categoryId = typeof payload?.category_id === 'string' ? payload.category_id.trim() : ''
+ if (!categoryId) {
+ throw new Error('Choose a message category')
+ }
+ const identifier = typeof payload?.identifier === 'string' ? payload.identifier.trim() : ''
+ if (!identifier) {
+ throw new Error(
+ "There is no email to opt out. Check the step's recipient field, for example {person.properties.email}"
+ )
+ }
+ return { category_id: categoryId, identifier }
+}
+
+registerAsyncFunction('postHogOptOutOfMessages', {
+ execute: async (args, context, result) => {
+ const payload = parsePayload(args)
+
+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow
+ if (!hogFlow?.id) {
+ throw new Error('Opt out of messages only runs inside a workflow')
+ }
+
+ const jwt = getMessageOptOutJwt()
+ if (!jwt.enabled) {
+ throw new Error(
+ 'Opt out of messages is not configured. Set WORKFLOW_MESSAGE_OPT_OUT_JWT_SECRET on the worker and Django to matching keys.'
+ )
+ }
+ // Repeating the call is safe because opting out twice leaves the recipient opted out.
+ await callInternalApi(context, result, {
+ jwt,
+ path: `/api/projects/${context.invocation.teamId}/workflow_message_opt_outs/`,
+ method: 'POST',
+ entityClaims: { hog_flow_id: hogFlow.id },
+ body: JSON.stringify(payload),
+ timeoutMs: OPT_OUT_TIMEOUT_MS,
+ })
+ },
+ mock: (args, logs) => {
+ parsePayload(args)
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: 'Opt out of messages was mocked. Nobody was opted out.',
+ })
+ return { status: 200, body: { result: 'opted_out', detail: 'Opted out (mocked).' } }
+ },
+})
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 45a0652127c5..dd7198cb4a09 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -244,6 +244,8 @@ export type CdpConfig = ClickhouseConfig & {
WORKFLOW_VISION_REQUEST_JWT_SECRET: string
// Scoped JWT keys signing the workflow engine's "Add to static cohort" calls to Django. Its own key, for the same reason.
WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET: string
+ // Scoped JWT keys signing the workflow engine's "Opt out of messages" calls to Django. Its own key, for the same reason.
+ WORKFLOW_MESSAGE_OPT_OUT_JWT_SECRET: string
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: number
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: number
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: number
@@ -464,6 +466,8 @@ export function getDefaultCdpConfig(): CdpConfig {
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET:
isTestEnv() || isDevEnv() ? 'local-dev-workflow-add-to-static-cohort-jwt' : '',
+ // Dev/test default must match Django's (posthog/settings/data_stores.py).
+ WORKFLOW_MESSAGE_OPT_OUT_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-message-opt-out-jwt' : '',
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: 600,
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: 200,
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: 300,
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
index c2207b09e344..8f7b6850ff5f 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
@@ -98,6 +98,7 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {
},
},
personId: 'person-1',
+ messageOptOuts: [{ identifier: '[email protected]', categoryId: '$all' }],
}
const rows = [
{
@@ -128,6 +129,7 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {
// inputs re-render against the current config instead of the stale snapshot.
expect(invocation.state?.currentAction).toEqual({ id: 'send_email', startedAtTimestamp: 999 })
expect(invocation.state?.personId).toBe('person-1')
+ expect(invocation.state?.messageOptOuts).toEqual([{ identifier: '[email protected]', categoryId: '$all' }])
expect(invocation.state?.actionStepCount).toBe(3)
expect(invocation.state?.customerTaskIdempotencyVersion).toBe(version)
expect(invocation.state?.variables).toEqual({ ticket_id: '123' })
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index 45c95c9aebf5..5064d31e7c68 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -837,6 +837,8 @@ export class RerunPaginatorService {
? (restoredCurrentAction as CyclotronJobInvocationHogFlow['state']['currentAction'])
: undefined,
personId: persistedState.personId,
+ // Later message steps check these before the per-worker preferences cache, which can predate them.
+ messageOptOuts: persistedState.messageOptOuts,
// Sticky rerun counter — mirror the hog function path so the
// lifecycle row producer can derive `attempts` / `is_retry`
// for flows too, and the `max_attempts` guard actually trips.
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 1241accd5a82..5c2d6c693dfa 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -32,9 +32,22 @@ import { RecipientTokensService } from '../../messaging/recipient-tokens.service
import { CdpUsageReporterService } from '../../usage/cdp-usage-reporter.service'
import { HogFlowFunctionsService } from '../hogflow-functions.service'
import { findActionByType } from '../hogflow-utils'
-import { HogFunctionHandler } from './hog_function'
+import { HogFunctionHandler, messageOptOutsAfterStep } from './hog_function'
describe('HogFunctionHandler', () => {
+ describe('messageOptOutsAfterStep', () => {
+ const optOut = { identifier: '[email protected]', categoryId: '$all' }
+
+ it.each([
+ ['records an opt-out step', 'template-posthog-opt-out-of-messages', [optOut]],
+ ['ignores any other step', 'template-webhook', undefined],
+ ])('%s', (_name, templateId, expected) => {
+ expect(
+ messageOptOutsAfterStep(undefined, templateId, { identifier: ' [email protected] ', category_id: '$all' })
+ ).toEqual(expected)
+ })
+ })
+
let hub: Hub
let team: Team
let hogFunctionHandler: HogFunctionHandler
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index 1f9b42d9fcda..931326f1882f 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -14,6 +14,7 @@ import {
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
HogFlowInvocationContext,
+ MessageOptOutRecord,
MinimalLogEntry,
} from '../../../types'
import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'
@@ -26,6 +27,24 @@ import { actionIdForLogging, findContinueAction } from '../hogflow-utils'
import { observeMissingVariableReferences } from '../hogflow-variable-usage'
import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'
+const OPT_OUT_OF_MESSAGES_TEMPLATE_ID = 'template-posthog-opt-out-of-messages'
+
+/** The run's recorded opt-outs after a step that succeeded, adding the one an "Opt out of messages" step made. */
+export function messageOptOutsAfterStep(
+ optOuts: MessageOptOutRecord[] | undefined,
+ templateId: string,
+ inputs: Record<string, unknown> | undefined
+): MessageOptOutRecord[] | undefined {
+ if (
+ templateId !== OPT_OUT_OF_MESSAGES_TEMPLATE_ID ||
+ typeof inputs?.identifier !== 'string' ||
+ typeof inputs.category_id !== 'string'
+ ) {
+ return optOuts
+ }
+ return [...(optOuts ?? []), { identifier: inputs.identifier.trim(), categoryId: inputs.category_id }]
+}
+
type FunctionActionType = 'function' | 'function_email' | 'function_sms'
type HogFlowActionBillingType = 'fetch' | 'email' | 'push' | 'sms'
@@ -214,6 +233,14 @@ export class HogFunctionHandler implements ActionHandler {
}
}
+ if (!functionResult.error) {
+ result.invocation.state.messageOptOuts = messageOptOutsAfterStep(
+ result.invocation.state.messageOptOuts,
+ action.config.template_id,
+ functionResult.invocation.state.globals?.inputs
+ )
+ }
+
// Add billable_invocation metric only if the function actually executed (not skipped)
if (!functionResult.skipped) {
// A step that does not send leaves this undefined and bills as before.
@@ -393,7 +420,12 @@ export class HogFunctionHandler implements ActionHandler {
const skipReason = await instrumentFn(
{ key: 'hogFlow.action.hogFunction.recipientPreferences', sendException: false },
- () => this.recipientPreferencesService.shouldSkipAction(hogFunctionInvocation, action)
+ () =>
+ this.recipientPreferencesService.shouldSkipAction(
+ hogFunctionInvocation,
+ action,
+ invocation.state.messageOptOuts
+ )
)
if (skipReason) {
// Suppression and opt-out both short-circuit the send, but a customer reading the run
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
index 96425e584ae5..aee71553405d 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
@@ -168,6 +168,22 @@ describe('RecipientPreferencesService', () => {
)
})
+ it.each([
+ ['the same category', '123e4567-e89b-12d3-a456-426614174000', 'opted_out'],
+ ['all marketing', '$all', 'opted_out'],
+ ['another category', '00000000-0000-4000-8000-000000000000', null],
+ ])('uses an opt-out this run made for %s before the cache', async (_name, categoryId, expected) => {
+ const action = createEmailAction('[email protected]', '123e4567-e89b-12d3-a456-426614174000')
+ const invocation = createFunctionStepInvocation(action)
+ mockRecipientsManagerGet.mockResolvedValue(null)
+
+ const result = await service.shouldSkipAction(invocation, action, [
+ { identifier: '[email protected]', categoryId },
+ ])
+
+ expect(result).toBe(expected)
+ })
+
it('should return false if recipient is opted in', async () => {
const action = createEmailAction('[email protected]', '123e4567-e89b-12d3-a456-426614174000')
const invocation = createFunctionStepInvocation(action)
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
index d81061a8a2cb..fb3070ba79c0 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
@@ -2,7 +2,7 @@ import { HogFlowAction } from '~/cdp/schema/hogflow'
import { RedisV2 } from '~/common/redis/redis-v2'
import { logger } from '~/common/utils/logger'
-import { CyclotronJobInvocationHogFunction } from '../../types'
+import { CyclotronJobInvocationHogFunction, MessageOptOutRecord } from '../../types'
import { NATIVE_PUSH_TEMPLATE_ID, pushRecipientOtherThanRunPerson } from '../../utils/push-subscription-utils'
import { workflowStepDispatchKeyFromInvocation } from '../../utils/workflow-step-dispatch-key'
import { PersonsManagerService } from '../managers/persons-manager.service'
@@ -117,7 +117,8 @@ export class RecipientPreferencesService {
public async shouldSkipAction(
invocation: CyclotronJobInvocationHogFunction,
- hogFlowAction: HogFlowAction
+ hogFlowAction: HogFlowAction,
+ runOptOuts: MessageOptOutRecord[] = []
): Promise<RecipientSkipReason | null> {
const action = this.asMessageAction(hogFlowAction)
if (!action) {
@@ -137,7 +138,7 @@ export class RecipientPreferencesService {
return null
}
- return (await this.isRecipientOptedOutOfAction(invocation, action)) ? 'opted_out' : null
+ return (await this.isRecipientOptedOutOfAction(invocation, action, runOptOuts)) ? 'opted_out' : null
}
private async isRecipientSuppressed(
@@ -188,7 +189,8 @@ export class RecipientPreferencesService {
private async isRecipientOptedOutOfAction(
invocation: CyclotronJobInvocationHogFunction,
- action: MessageAction
+ action: MessageAction,
+ runOptOuts: MessageOptOutRecord[]
): Promise<boolean> {
let identifier
@@ -217,6 +219,19 @@ export class RecipientPreferencesService {
)
}
+ // Grab the recipient preferences for the action category
+ const categoryId = action.config.message_category_id || '$all'
+ const trimmedIdentifier = String(identifier).trim()
+ if (
+ runOptOuts.some(
+ (optOut) =>
+ optOut.identifier === trimmedIdentifier &&
+ (optOut.categoryId === categoryId || optOut.categoryId === '$all')
+ )
+ ) {
+ return true
+ }
+
try {
const recipient = await this.recipientsManager.get({
teamId: invocation.teamId,
@@ -232,9 +247,6 @@ export class RecipientPreferencesService {
return false
}
- // Grab the recipient preferences for the action category
- const categoryId = action.config.message_category_id || '$all'
-
const messageCategoryPreference = this.recipientsManager.getPreference(recipient, categoryId)
const allMarketingPreferences = this.recipientsManager.getAllMarketingMessagingPreference(recipient)
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.test.ts
new file mode 100644
index 000000000000..deb347d9edeb
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.test.ts
@@ -0,0 +1,73 @@
+import jwt from 'jsonwebtoken'
+
+import { defaultConfig } from '~/common/config/config'
+import { parseJSON } from '~/common/utils/json-parse'
+import * as requestModule from '~/common/utils/request'
+
+import { PosthogJwtAudience } from '../../../utils/jwt-utils'
+import { TemplateTester } from '../../test/test-helpers'
+import { template } from './posthog-opt-out-of-messages.template'
+
+describe('posthog opt out of messages template', () => {
+ const tester = new TemplateTester(template)
+ const workflowOptions = { hogFlow: { id: '0198c9f1-0000-0000-0000-000000000001' } }
+ const inputs = { category_id: '0198c9f1-0000-0000-0000-0000000000aa', identifier: '[email protected]' }
+
+ let fetchSpy: jest.SpyInstance
+ const internalResponse = (status: number, body: unknown): requestModule.FetchResponse => ({
+ status,
+ headers: {},
+ text: () => Promise.resolve(JSON.stringify(body)),
+ json: () => Promise.resolve(body),
+ dump: async () => {},
+ })
+ beforeEach(async () => {
+ await tester.beforeEach()
+ fetchSpy = jest
+ .spyOn(requestModule, 'internalFetch')
+ .mockResolvedValue(internalResponse(200, { result: 'opted_out', detail: 'Opted out of Product updates.' }))
+ })
+ afterEach(() => jest.restoreAllMocks())
+
+ it('opts the recipient out with a token scoped to this step and workflow', async () => {
+ const response = await tester.invoke(inputs, undefined, workflowOptions)
+ const resumed = await tester.resumeInvocation(response.invocation)
+
+ expect(resumed.error).toBeUndefined()
+ expect(resumed.logs.map((log) => log.message)).toContain('Opted out of Product updates.')
+ const [url, params] = fetchSpy.mock.calls[0] as [string, requestModule.FetchOptions]
+ expect(url).toBe(`${defaultConfig.INTERNAL_API_BASE_URL}/api/projects/1/workflow_message_opt_outs/`)
+ expect(parseJSON(params.body!.toString())).toEqual(inputs)
+ const token = (params.headers as Record<string, string>).Authorization.replace('Bearer ', '')
+ expect(
+ jwt.verify(token, defaultConfig.WORKFLOW_MESSAGE_OPT_OUT_JWT_SECRET, {
+ audience: PosthogJwtAudience.WORKFLOW_MESSAGE_OPT_OUT,
+ })
+ ).toMatchObject({ team_id: 1, hog_flow_id: workflowOptions.hogFlow.id })
+ })
+
+ it.each([
+ [409, 'The message category was deleted. Choose another category in the step.'],
+ [
+ 403,
+ "The saved workflow doesn't opt people out of this category. Save or publish the workflow, then try again.",
+ ],
+ ])('fails the step when Django refuses with %i', async (status, detail) => {
+ fetchSpy.mockResolvedValue(internalResponse(status, { result: 'refused', detail }))
+
+ const response = await tester.invoke(inputs, undefined, workflowOptions)
+ const resumed = await tester.resumeInvocation(response.invocation)
+
+ expect(resumed.error).toEqual(`Could not opt the recipient out (${status}): ${detail}`)
+ })
+
+ it.each([
+ ['an empty recipient', { ...inputs, identifier: ' ' }, /no email to opt out/],
+ ['no category', { ...inputs, category_id: '' }, /Choose a message category/],
+ ])('fails the step without calling Django for %s', async (_name, stepInputs, expected) => {
+ const response = await tester.invoke(stepInputs, undefined, workflowOptions)
+
+ expect(response.error).toMatch(expected)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.ts
new file mode 100644
index 000000000000..5bb5b2dc9667
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-opt-out-of-messages.template.ts
@@ -0,0 +1,51 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+import { hogApiErrorMessageFn } from '../../hog-helpers'
+
+export const template: HogFunctionTemplate = {
+ free: true,
+ status: 'hidden',
+ type: 'destination',
+ id: 'template-posthog-opt-out-of-messages',
+ name: 'Opt out of messages',
+ description: 'Opt the recipient out of a message category, or of all marketing messages.',
+ icon_url: '/static/posthog-icon.svg',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
+${hogApiErrorMessageFn}
+
+let response := postHogOptOutOfMessages({
+ 'category_id': inputs.category_id,
+ 'identifier': inputs.identifier
+})
+
+if (response.status >= 400) {
+ throw Error(f'Could not opt the recipient out ({response.status}): {apiErrorMessage(response)}')
+}
+
+print(response.body.detail)
+`,
+ inputs_schema: [
+ {
+ key: 'category_id',
+ type: 'string',
+ label: 'Message category',
+ required: true,
+ // The builder renders a category picker for this input. The callback compares the value with the
+ // categories the saved workflow names, so it can't be a template.
+ hidden: true,
+ templating: false,
+ description: 'The message category to opt the recipient out of, or $all for all marketing messages.',
+ },
+ {
+ key: 'identifier',
+ type: 'string',
+ label: 'Recipient',
+ required: true,
+ default: '{person.properties.email}',
+ description:
+ "Who to opt out. Use the same value as the email step's recipient, usually the person's email.",
+ },
+ ],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index ebafb94cc0b7..4bc0f084aec9 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -41,6 +41,7 @@ import { template as posthogRunScoutTemplate } from './_destinations/posthog_sig
import { template as posthogCreateTaskTemplate } from './_destinations/posthog_tasks/posthog-create-task.template'
import { template as posthogAddToStaticCohortTemplate } from './_destinations/posthog_workflows/posthog-add-to-static-cohort.template'
import { template as posthogClassifyTemplate } from './_destinations/posthog_workflows/posthog-classify.template'
+import { template as posthogOptOutOfMessagesTemplate } from './_destinations/posthog_workflows/posthog-opt-out-of-messages.template'
import { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'
import { template as pushTemplate } from './_destinations/push/push.template'
import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'
@@ -116,6 +117,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
posthogRunScoutTemplate,
posthogClassifyTemplate,
posthogAddToStaticCohortTemplate,
+ posthogOptOutOfMessagesTemplate,
posthogReplayVisionTemplate,
posthogCreateAccountTemplate,
posthogCreateCustomerTaskTemplate,
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index b06a005c0ced..25c0410db533 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -443,6 +443,12 @@ export type CyclotronJobInvocationHogFlow = CyclotronJobInvocation & {
refreshPerson?: () => Promise<{ person?: CyclotronPerson; filterGlobals: HogFunctionFilterGlobals }>
}
+export type MessageOptOutRecord = {
+ identifier: string
+ // A message category id, or '$all' for all marketing messages.
+ categoryId: string
+}
+
export type HogFlowInvocationContext = {
event: HogFunctionInvocationGlobals['event']
personId?: string // Persisted person UUID, used when distinct_id is not available (e.g. batch workflows, manual person triggers)
@@ -468,6 +474,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
+ // Opt-outs this run's "Opt out of messages" steps made. Message steps check them before the recipient cache,
+ // because a worker that resumes the run can hold the recipient's preferences from before the opt-out.
+ messageOptOuts?: MessageOptOutRecord[]
// 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
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 8bde14e7ee5d..24193d074546 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -17,6 +17,8 @@ export enum PosthogJwtAudience {
WORKFLOW_VISION_REQUEST = 'posthog:workflows:vision_request',
// Must match PosthogJwtAudience.WORKFLOW_ADD_TO_STATIC_COHORT in posthog/jwt.py exactly.
WORKFLOW_ADD_TO_STATIC_COHORT = 'posthog:workflows:add_to_static_cohort',
+ // Must match PosthogJwtAudience.WORKFLOW_MESSAGE_OPT_OUT in posthog/jwt.py exactly.
+ WORKFLOW_MESSAGE_OPT_OUT = 'posthog:workflows:message_opt_out',
// Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.
CONVERSATIONS_TICKETS = 'posthog:conversations:tickets',
// Must match PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS in posthog/jwt.py exactly.
diff --git a/nodejs/tests/fixtures/hog-bytecode/5816d1bfb47dee94de91fe4235f76c98a2c47e13b727cbf2f3802f06ec51c6c5.json b/nodejs/tests/fixtures/hog-bytecode/5816d1bfb47dee94de91fe4235f76c98a2c47e13b727cbf2f3802f06ec51c6c5.json
new file mode 100644
index 000000000000..6342bb60ac92
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/5816d1bfb47dee94de91fe4235f76c98a2c47e13b727cbf2f3802f06ec51c6c5.json
@@ -0,0 +1 @@
+["_H",1,32," ",38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/bf9ab6529a0efb3917acc5a37925306d71b676bac81c404f63aaf3f39467c708.json b/nodejs/tests/fixtures/hog-bytecode/bf9ab6529a0efb3917acc5a37925306d71b676bac81c404f63aaf3f39467c708.json
new file mode 100644
index 000000000000..7aba78e788ad
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/bf9ab6529a0efb3917acc5a37925306d71b676bac81c404f63aaf3f39467c708.json
@@ -0,0 +1 @@
+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"category_id",32,"category_id",32,"inputs",1,2,32,"identifier",32,"identifier",32,"inputs",1,2,42,2,2,"postHogOptOutOfMessages",1,33,400,36,1,32,"status",45,14,40,22,32,"Could not opt the recipient out (",36,1,32,"status",45,32,"): ",36,1,36,0,54,1,2,"concat",4,2,"Error",1,49,36,1,32,"body",45,32,"detail",45,2,"print",1,35,35,35]
diff --git a/nodejs/tests/fixtures/hog-bytecode/c37ee383d8bc8b6e4f4d4b19eae40ad3b7eebd8a4f671a611c2a98b5a780e956.json b/nodejs/tests/fixtures/hog-bytecode/c37ee383d8bc8b6e4f4d4b19eae40ad3b7eebd8a4f671a611c2a98b5a780e956.json
new file mode 100644
index 000000000000..41e223c5615c
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/c37ee383d8bc8b6e4f4d4b19eae40ad3b7eebd8a4f671a611c2a98b5a780e956.json
@@ -0,0 +1 @@
+["_H",1,32,"[email protected]",38]