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): run transactional email workflows from an authenticated route (#117673)

Harley Alexander0e30f4724078
diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.ts
index 106beb34a79a..71791a375815 100644
--- a/nodejs/src/cdp/cdp-api.serial.test.ts
+++ b/nodejs/src/cdp/cdp-api.serial.test.ts
@@ -33,6 +33,7 @@ import { insertHogFlow as _insertHogFlow } from './_tests/fixtures-hogflows'
import { CdpApi } from './cdp-api'
import { CdpConsumerBaseDeps } from './consumers/cdp-base.consumer'
import { posthogFilterOutPlugin } from './legacy-plugins/_transformations/posthog-filter-out-plugin/template'
+import { transactionalEmailRequestsTotal } from './services/hogflows/transactional-email'
import { BASE_REDIS_KEY, HogWatcherState } from './services/monitoring/hog-watcher.service'
import { compileHog } from './templates/compiler'
import { HogFunctionInvocationGlobals, HogFunctionType } from './types'
@@ -2036,6 +2037,130 @@ describe('CDP API', () => {
})
})
+ describe('transactional email', () => {
+ let mockQueueInvocations: jest.Mock
+ let hogFlow: HogFlow
+ const body = {
+ distinct_id: 'distinct_A_1',
+ variables: { reset_link: 'https://example.com/reset' },
+ }
+
+ // Raw audience literal and Python claim names: the wire contract with Django's
+ // WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_PURPOSE, so drift on either side breaks here.
+ const mintToken = (
+ teamId: number,
+ hogFlowId: string,
+ {
+ secret = 'local-dev-workflows-transactional-email-jwt',
+ audience = 'posthog:workflows:send_transactional_email',
+ } = {}
+ ) => jwt.sign({ team_id: teamId, hog_flow_id: hogFlowId }, secret, { audience, expiresIn: '2m' })
+
+ const transactionalFlow = (trigger: 'api' | 'schedule', status: HogFlow['status']): HogFlow =>
+ new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus(status)
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: { type: 'trigger', config: { type: trigger } },
+ email: { type: 'function_email', config: { template_id: 'template-email', inputs: {} } },
+ },
+ edges: [{ from: 'trigger', to: 'email', type: 'continue' }],
+ })
+ .build()
+
+ // The alerts on this endpoint key on these outcome labels.
+ const outcomeCount = async (outcome: string): Promise<number> =>
+ (await transactionalEmailRequestsTotal.get()).values.find((v) => v.labels.outcome === outcome)?.value ?? 0
+
+ const send = (flowId: string, headers: Record<string, string>) =>
+ supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flowId}/transactional_email`)
+ .set(headers)
+ .send(body)
+
+ beforeEach(async () => {
+ mockQueueInvocations = jest.fn().mockResolvedValue(undefined)
+ api['hogflowQueue'] = { queueInvocations: mockQueueInvocations } as any
+ hogFlow = await insertHogFlow(transactionalFlow('api', 'active'))
+ })
+
+ it('queues one run on the email fast lane with the recipient and the data', async () => {
+ const queueAppMetric = jest.spyOn(api['hogFunctionMonitoringService'], 'queueAppMetric')
+ const queuedBefore = await outcomeCount('queued')
+
+ const res = await send(hogFlow.id, { Authorization: `Bearer ${mintToken(team.id, hogFlow.id)}` })
+
+ expect(res.status).toEqual(202)
+ expect(await outcomeCount('queued')).toEqual(queuedBefore + 1)
+ expect(mockQueueInvocations).toHaveBeenCalledTimes(1)
+ const [invocation] = mockQueueInvocations.mock.calls[0][0]
+ expect(invocation).toMatchObject({
+ id: res.body.invocation_id,
+ teamId: team.id,
+ functionId: hogFlow.id,
+ queue: 'email',
+ queuePriority: 0,
+ state: {
+ event: { distinct_id: 'distinct_A_1', properties: { to: '[email protected]' } },
+ variables: { reset_link: 'https://example.com/reset' },
+ },
+ })
+ // The run counts as started in the workflow's metrics, like an event-triggered run.
+ expect(queueAppMetric).toHaveBeenCalledWith(
+ expect.objectContaining({ app_source_id: hogFlow.id, metric_name: 'triggered', count: 1 }),
+ 'hog_flow'
+ )
+ })
+
+ it('refuses a send when the team is over its email quota', async () => {
+ jest.spyOn(api['deps'].quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(true)
+ const limitedBefore = await outcomeCount('quota_limited')
+
+ const res = await send(hogFlow.id, { Authorization: `Bearer ${mintToken(team.id, hogFlow.id)}` })
+
+ expect(res.status).toEqual(429)
+ expect(await outcomeCount('quota_limited')).toEqual(limitedBefore + 1)
+ expect(mockQueueInvocations).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['a workflow with another trigger', 'schedule', 'active'],
+ ['a transactional email that is not active', 'api', 'draft'],
+ ] as const)('refuses to run %s', async (_desc, trigger, status) => {
+ const other = await insertHogFlow(transactionalFlow(trigger, status))
+
+ const res = await send(other.id, { Authorization: `Bearer ${mintToken(team.id, other.id)}` })
+
+ expect(res.status).toEqual(400)
+ expect(mockQueueInvocations).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['no token', () => ({})],
+ [
+ "another workflow's token",
+ () => ({ Authorization: `Bearer ${mintToken(team.id, new UUIDT().toString())}` }),
+ ],
+ ["another team's token", () => ({ Authorization: `Bearer ${mintToken(team.id + 1, hogFlow.id)}` })],
+ [
+ 'a step-resume-audience token',
+ () => ({
+ Authorization: `Bearer ${mintToken(team.id, hogFlow.id, {
+ audience: 'posthog:workflows:step_resume',
+ })}`,
+ }),
+ ],
+ ])('rejects a request with %s', async (_desc, headers) => {
+ const res = await send(hogFlow.id, headers())
+
+ expect(res.status).toEqual(401)
+ expect(mockQueueInvocations).not.toHaveBeenCalled()
+ })
+ })
+
describe('hogflow cancel invocations auth', () => {
let mockCancelJobs: jest.Mock
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index ae46852b622c..0bd16cbe3e8a 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -46,15 +46,23 @@ import {
} from './services/hogflows/batch-resolver.types'
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 { matchesWaitUntilCondition } from './services/hogflows/hogflow-utils'
import { WorkflowStepResumeSchema } from './services/hogflows/step-resume.service'
+import {
+ TransactionalEmailOutcome,
+ TransactionalEmailRequestSchema,
+ transactionalEmailRequestsTotal,
+} from './services/hogflows/transactional-email'
import { InvocationResultsService } from './services/invocation-results.service'
import { JobQueue } from './services/job-queue/job-queue.interface'
import { GroupsManagerService } from './services/managers/groups-manager.service'
import { HogFunctionManagerService } from './services/managers/hog-function-manager.service'
+import { EMAIL_QUEUE_PRIORITY } from './services/messaging/email-priority'
import { EmailTrackingService } from './services/messaging/email-tracking.service'
import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
+import { HogFunctionMonitoringService } from './services/monitoring/hog-function-monitoring.service'
import {
HogWatcherService,
HogWatcherState,
@@ -168,6 +176,8 @@ export class CdpApi {
private cancelInvocationsJwt: ScopedServiceJwt
private cancelBatchJwt: ScopedServiceJwt
private stepResumeJwt: ScopedServiceJwt
+ private transactionalEmailJwt: ScopedServiceJwt
+ private hogFunctionMonitoringService: HogFunctionMonitoringService
constructor(
private config: PluginsServerConfig,
@@ -198,6 +208,7 @@ export class CdpApi {
this.hogQueue = jobQueues.hogQueue
this.hogflowQueue = jobQueues.hogflowQueue
this.cdpSourceWebhooksConsumer = new CdpSourceWebhooksConsumer(config, deps, jobQueues)
+ this.hogFunctionMonitoringService = services.hogFunctionMonitoringService
this.emailTrackingService = new EmailTrackingService(
this.hogFunctionManager,
this.hogFlowManager,
@@ -235,6 +246,10 @@ export class CdpApi {
PosthogJwtAudience.WORKFLOWS_STEP_RESUME,
config.WORKFLOWS_STEP_RESUME_JWT_SECRET || ''
)
+ this.transactionalEmailJwt = new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOWS_SEND_TRANSACTIONAL_EMAIL,
+ config.WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_SECRET || ''
+ )
}
public get service(): PluginServerService {
@@ -316,6 +331,10 @@ export class CdpApi {
asyncHandler(this.postHogFlowCancelBatchJob)
)
router.post('/api/projects/:team_id/workflow_steps/resume', asyncHandler(this.postWorkflowStepResume))
+ router.post(
+ '/api/projects/:team_id/hog_flows/:id/transactional_email',
+ asyncHandler(this.postTransactionalEmail)
+ )
router.get('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.getFunctionStatus()))
router.patch('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.patchFunctionStatus()))
router.get('/api/hog_functions/states', asyncHandler(this.getFunctionStates()))
@@ -1082,6 +1101,106 @@ export class CdpApi {
// narrower claims via extraClaims and every one must match too; a route without a workflow
// in its path (step resume) pins the job through extraClaims instead. Writes the 401 itself
// and returns false on any mismatch.
+ // Run a transactional email's workflow once. Django checks the template and the workflow, then calls this
+ // once per send. The job goes straight onto the email queue's fast lane.
+ //
+ // Auth: a per-call JWT minted by Django on its own audience and key, pinned to the team and the workflow,
+ // never the fleet-wide internal secret.
+ private postTransactionalEmail = async (req: ModifiedRequest, res: express.Response): Promise<any> => {
+ const reply = (outcome: TransactionalEmailOutcome, status: number, body: Record<string, unknown>) => {
+ transactionalEmailRequestsTotal.inc({ outcome })
+ return res.status(status).json(body)
+ }
+ try {
+ if (!this.transactionalEmailJwt.enabled) {
+ return reply('not_configured', 503, {
+ error: 'Transactional email auth not configured (WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_SECRET unset)',
+ })
+ }
+ if (!this.verifyScopedWorkflowJwt(this.transactionalEmailJwt, req, res, 'transactional email')) {
+ transactionalEmailRequestsTotal.inc({ outcome: 'unauthorized' })
+ return
+ }
+ const parsed = TransactionalEmailRequestSchema.safeParse(req.body)
+ if (!parsed.success) {
+ return reply('invalid_request', 400, { error: parsed.error.message })
+ }
+ const { to, distinct_id: distinctId, variables } = parsed.data
+
+ const team = await this.deps.teamManager.getTeam(parseInt(req.params.team_id)).catch(() => null)
+ if (!team) {
+ return reply('not_found', 404, { error: 'Team not found' })
+ }
+ const hogFlow = await this.hogFlowManager.getHogFlow(req.params.id)
+ if (!hogFlow || hogFlow.team_id !== team.id) {
+ return reply('not_found', 404, { error: 'Workflow not found' })
+ }
+ if (hogFlow.trigger?.type !== 'api' || hogFlow.status !== 'active') {
+ return reply('not_sendable', 400, { error: 'Workflow is not an active transactional email' })
+ }
+ const { isLimited } = await checkHogFlowQuotaLimits(hogFlow, team.id, this.deps.quotaLimiting)
+ if (isLimited) {
+ return reply('quota_limited', 429, { error: 'quota_limited' })
+ }
+
+ const event: HogFunctionInvocationGlobals['event'] = {
+ uuid: new UUIDT().toString(),
+ event: '$transactional_email',
+ distinct_id: distinctId,
+ timestamp: DateTime.now().toISO(),
+ url: '',
+ // The email step's recipient reads this.
+ properties: { to },
+ elements_chain: '',
+ }
+ const triggerGlobals: HogFunctionInvocationGlobals = {
+ event,
+ project: {
+ id: team.id,
+ name: team.name,
+ url: `${this.config.SITE_URL ?? 'http://localhost:8000'}/project/${team.id}`,
+ },
+ variables,
+ }
+ const filterGlobals = convertToHogFunctionFilterGlobal({ event, person: undefined, groups: {}, variables })
+
+ const invocation = createHogFlowInvocation(triggerGlobals, hogFlow, filterGlobals)
+ // Straight to the email queue: the flow's only step is the email, so a hop through the
+ // workflow queue would only add latency to a password reset or a verification code.
+ invocation.queue = 'email'
+ invocation.queuePriority = EMAIL_QUEUE_PRIORITY.fast
+
+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')
+ try {
+ await this.hogflowQueue.queueInvocations([invocation])
+ } catch (error) {
+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor([invocation.id])
+ throw error
+ }
+ await this.invocationResultsService.invocationResultsRowsService.flush()
+ // The run skips the trigger pipeline that counts runs for event-triggered workflows.
+ this.hogFunctionMonitoringService.queueAppMetric(
+ {
+ team_id: team.id,
+ app_source_id: hogFlow.id,
+ metric_kind: 'other',
+ metric_name: 'triggered',
+ count: 1,
+ app_source_version: { id: hogFlow.id, version: hogFlow.version },
+ },
+ 'hog_flow'
+ )
+ await this.hogFunctionMonitoringService.flush()
+
+ return reply('queued', 202, { status: 'queued', invocation_id: invocation.id })
+ } catch (e) {
+ logger.error('Error queueing transactional email', {
+ error: e instanceof Error ? e.message : String(e),
+ })
+ return reply('error', 500, { error: e instanceof Error ? e.message : String(e) })
+ }
+ }
+
private verifyScopedWorkflowJwt(
jwt: ScopedServiceJwt,
req: ModifiedRequest,
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 46404d81caed..cf973ce6788f 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -220,6 +220,9 @@ export type CdpConfig = ClickhouseConfig & {
// workflow step). Its own key: the Celery and Temporal workers mint it, no other tier does.
// Same comma-separated rotation and fail-closed-when-empty semantics.
WORKFLOWS_STEP_RESUME_JWT_SECRET: string
+ // Scoped JWT keys verifying Django's transactional email sends. Its own key: only Django
+ // mints it. Same comma-separated rotation and fail-closed-when-empty semantics.
+ WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_SECRET: string
// Scoped JWT keys signing the workflow engine's task-create calls to Django, with the same
// comma-separated rotation and fail-closed-when-empty semantics as the secret above.
TASKS_CREATE_JWT_SECRET: string
@@ -435,6 +438,9 @@ export function getDefaultCdpConfig(): CdpConfig {
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOWS_STEP_RESUME_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-step-resume-jwt' : '',
// Dev/test default must match Django's (posthog/settings/data_stores.py).
+ WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_SECRET:
+ isTestEnv() || isDevEnv() ? 'local-dev-workflows-transactional-email-jwt' : '',
+ // Dev/test default must match Django's (posthog/settings/data_stores.py).
TASKS_CREATE_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-tasks-create-jwt' : '',
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOW_SCOUT_RUN_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-scout-run-jwt' : '',
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
index edcac442d0a8..211b4b90f0b3 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
@@ -8,7 +8,12 @@ import { PluginsServerConfig } from '~/types'
import { isRowScopedTrigger } from '../schema/hogflow'
import { JobQueue } from '../services/job-queue/job-queue.interface'
-import { CyclotronJobInvocation, CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '../types'
+import {
+ CyclotronJobInvocation,
+ CyclotronJobInvocationHogFlow,
+ CyclotronJobInvocationResult,
+ CyclotronPerson,
+} from '../types'
import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
import { createInvocationResult } from '../utils/invocation-utils'
import { CdpConsumerBaseDeps } from './cdp-base.consumer'
@@ -19,6 +24,16 @@ type LoadHogFlowsResult = {
canceledResults: CyclotronJobInvocationResult[]
}
+// A transactional email's caller holds only a send key, which grants no access to person data, so its
+// template never sees person properties, or the display name derived from them. The person stays attached
+// so the send is recorded against them.
+function personForFlow(
+ hogFlow: HogFlow,
+ person: CyclotronPerson | null | undefined
+): CyclotronPerson | null | undefined {
+ return person && hogFlow.trigger?.type === 'api' ? { ...person, properties: {}, name: '' } : person
+}
+
export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
protected override name = 'CdpCyclotronWorkerHogFlow'
@@ -159,7 +174,7 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
// otherwise read the person cached when the wait parked, without the write that woke it.
const forceFreshPerson =
hasPushActions(hogFlow.actions) || hogFlowInvocationState.currentAction?.eventMatched === true
- const [person, groups] = await Promise.all([
+ const [resolvedPerson, groups] = await Promise.all([
personIdOrDistinctId
? this.personsManager.getCyclotronPerson(hogFlow.team_id, personIdOrDistinctId, kind, {
forceFresh: forceFreshPerson,
@@ -172,6 +187,8 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
),
])
+ const person = personForFlow(hogFlow, resolvedPerson)
+
if (!person && hogFlow.trigger?.type === 'event') {
logger.warn('⚠️', 'Person not found for hog flow invocation', {
hogFlowId: hogFlow.id,
@@ -214,11 +231,11 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
if (personIdOrDistinctId) {
loaded.refreshPerson = async () => {
- const fresh = await this.personsManager.getCyclotronPerson(
- hogFlow.team_id,
- personIdOrDistinctId,
- kind,
- { forceFresh: true }
+ const fresh = personForFlow(
+ hogFlow,
+ await this.personsManager.getCyclotronPerson(hogFlow.team_id, personIdOrDistinctId, kind, {
+ forceFresh: true,
+ })
)
return {
person: fresh ?? undefined,
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
index 670df3c4e068..f1d624cc7c69 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
@@ -393,6 +393,39 @@ describe('CdpCyclotronWorkerHogFlow', () => {
expect(personManagerSpy).not.toHaveBeenCalled()
})
+ it('attaches the person to a transactional email without their properties', async () => {
+ const transactional = await insertHogFlow(
+ hub.postgres,
+ new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withWorkflow({
+ actions: {
+ trigger: { type: 'trigger', config: { type: 'api' } },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [{ from: 'trigger', to: 'exit', type: 'continue' }],
+ })
+ .build()
+ )
+ const invocation = createSerializedHogFlowInvocation(transactional, {
+ event: { distinct_id: 'distinct_A_1', properties: { to: '[email protected]' } } as any,
+ })
+
+ const results = (await processor.processInvocations([
+ invocation,
+ ])) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]
+
+ // The send is still recorded against the person, but the template can't read what they hold.
+ expect(results[0].invocation.person).toMatchObject({
+ id: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',
+ properties: {},
+ name: '',
+ })
+ const refreshed = await results[0].invocation.refreshPerson!()
+ expect(refreshed.person).toMatchObject({ properties: {}, name: '' })
+ })
+
it('should make minimal calls to the person manager', async () => {
const personManagerSpy = jest.spyOn(processor['personsManager'] as any, 'fetchPersonsByDistinctIds')
await processor.processInvocations(invocations)
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index f5a262099462..cdf723847b2c 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -69,6 +69,10 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('schedule'),
}),
+ // A transactional email: Django's send endpoint runs the workflow once per call.
+ z.object({
+ type: z.literal('api'),
+ }),
z.object({
type: z.literal('cohort'),
cohort_id: z.number(),
diff --git a/nodejs/src/cdp/services/hogflows/transactional-email.ts b/nodejs/src/cdp/services/hogflows/transactional-email.ts
new file mode 100644
index 000000000000..f3c13f3c1f1f
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/transactional-email.ts
@@ -0,0 +1,27 @@
+import { Counter } from 'prom-client'
+import { z } from 'zod'
+
+// What Django sends to run a transactional email's workflow once.
+export const TransactionalEmailRequestSchema = z.object({
+ to: z.string().email(),
+ // The person the send is tracked against. Django falls back to the recipient's address.
+ distinct_id: z.string().min(1),
+ // The caller's `message_data`, available to the template as `variables`.
+ variables: z.record(z.string(), z.any()).default({}),
+})
+
+export type TransactionalEmailOutcome =
+ | 'queued'
+ | 'not_configured'
+ | 'unauthorized'
+ | 'invalid_request'
+ | 'not_found'
+ | 'not_sendable'
+ | 'quota_limited'
+ | 'error'
+
+export const transactionalEmailRequestsTotal = new Counter({
+ name: 'cdp_transactional_email_requests_total',
+ help: 'Requests from Django to run a transactional email, by outcome. Every outcome except `queued` means no email was queued.',
+ labelNames: ['outcome'],
+})
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index c56ad4a2a557..3a34f07f194e 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -7,6 +7,7 @@ export enum PosthogJwtAudience {
WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',
WORKFLOWS_CANCEL_BATCH = 'posthog:workflows:cancel_batch',
WORKFLOWS_STEP_RESUME = 'posthog:workflows:step_resume',
+ WORKFLOWS_SEND_TRANSACTIONAL_EMAIL = 'posthog:workflows:send_transactional_email',
CUSTOMER_TASKS_CREATE = 'posthog:customer-tasks:create',
TASKS_CREATE = 'posthog:tasks:create',
WORKFLOW_SCOUT_RUN = 'posthog:workflows:scout_run',
diff --git a/nodejs/src/common/api/middleware/internal-api-auth.ts b/nodejs/src/common/api/middleware/internal-api-auth.ts
index eb5696c253fe..17b598412185 100644
--- a/nodejs/src/common/api/middleware/internal-api-auth.ts
+++ b/nodejs/src/common/api/middleware/internal-api-auth.ts
@@ -36,6 +36,8 @@ const SCOPED_AUTH_PATH_PATTERNS = [
/^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/batch_jobs\/[^/]+\/cancel$/,
// CdpApi.postWorkflowStepResume, verified against WORKFLOWS_STEP_RESUME_JWT_SECRET, audience-pinned.
/^\/api\/projects\/[^/]+\/workflow_steps\/resume$/,
+ // CdpApi.postTransactionalEmail, verified against WORKFLOWS_TRANSACTIONAL_EMAIL_JWT_SECRET, audience-pinned.
+ /^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/transactional_email$/,
]
export interface InternalApiAuthOptions {