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(workflows): add nodejs and frontend support for native push workflow action (#65807)

Daniel Marchuk28a938a1e1f8
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
index 6a34abb54fb1..797d3bb1df98 100644
--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
@@ -47,6 +47,7 @@ import { cyclotronJobInputLogic, formatJsonValue } from './cyclotronJobInputLogi
import { CyclotronJobTemplateSuggestionsButton } from './CyclotronJobTemplateSuggestions'
import { CyclotronJobInputIntegration } from './integrations/CyclotronJobInputIntegration'
import { CyclotronJobInputIntegrationField } from './integrations/CyclotronJobInputIntegrationField'
+import { CyclotronJobInputIntegrationMulti } from './integrations/CyclotronJobInputIntegrationMulti'
import { CyclotronJobInputConfiguration } from './types'
export const EXTEND_OBJECT_KEY = '$$_extend_object'
@@ -79,6 +80,7 @@ const INPUT_TYPE_LIST = [
'choice',
'json',
'integration',
+ 'integration_multi',
'email',
'native_email',
'non_failure_status_codes',
@@ -671,6 +673,14 @@ function CyclotronJobInputRenderer({
}}
/>
)
+ case 'integration_multi':
+ return (
+ <CyclotronJobInputIntegrationMulti
+ schema={schema}
+ value={input.value as number[] | undefined}
+ onChange={onValueChange}
+ />
+ )
case 'integration_field':
return (
<CyclotronJobInputIntegrationField
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/CyclotronJobInputIntegrationMulti.tsx b/frontend/src/lib/components/CyclotronJob/integrations/CyclotronJobInputIntegrationMulti.tsx
new file mode 100644
index 000000000000..ca3998ba91d1
--- /dev/null
+++ b/frontend/src/lib/components/CyclotronJob/integrations/CyclotronJobInputIntegrationMulti.tsx
@@ -0,0 +1,52 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, LemonInputSelect } from '@posthog/lemon-ui'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { getIntegrationNameFromKind } from 'lib/integrations/utils'
+
+import { CyclotronJobInputSchemaType } from '~/types'
+
+// Multi-select over the team's integration connections of one or more kinds. `schema.integration`
+// carries a comma-separated list of kinds (e.g. "firebase,apns"); only connections that actually
+// exist are offered, so platforms the team hasn't configured never show up as empty pickers.
+export function CyclotronJobInputIntegrationMulti({
+ schema,
+ value,
+ onChange,
+}: {
+ schema: CyclotronJobInputSchemaType
+ value?: number[]
+ onChange?: (value: number[]) => void
+}): JSX.Element {
+ const { integrations, integrationsLoading } = useValues(integrationsLogic)
+
+ const kinds = (schema.integration ?? '')
+ .split(',')
+ .map((k) => k.trim())
+ .filter(Boolean)
+ const available = (integrations ?? []).filter((integration) => kinds.includes(integration.kind))
+
+ if (!integrationsLoading && available.length === 0) {
+ return (
+ <LemonBanner type="warning" className="p-2">
+ No {kinds.map(getIntegrationNameFromKind).join(' or ')} channels are configured. Add one from the
+ Channels tab to send this notification.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <LemonInputSelect
+ mode="multiple"
+ placeholder="Select one or more channels"
+ loading={integrationsLoading}
+ value={(value ?? []).map(String)}
+ onChange={(values) => onChange?.(values.map(Number))}
+ options={available.map((integration) => ({
+ key: String(integration.id),
+ label: `${integration.display_name || integration.kind} (${getIntegrationNameFromKind(integration.kind)})`,
+ }))}
+ />
+ )
+}
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
index f080358c8780..5ccf21baf060 100644
--- a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
+++ b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
@@ -1,3 +1,6 @@
+// Side-effect import: register all integration setups
+import './integrationSetups'
+
import { useActions, useValues } from 'kea'
import { useEffect, useRef } from 'react'
@@ -13,9 +16,6 @@ import { urls } from 'scenes/urls'
import { findIntegrationByFormValue, matchesIntegrationIdValue } from './integrationLookup'
import { getAllRegisteredIntegrationSetups, getIntegrationSetup } from './integrationSetupRegistry'
-// Side-effect import: register all integration setups
-import './integrationSetups'
-
export type IntegrationConfigureProps = {
value?: number
onChange?: (value: number | null) => void
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 070aa020dc63..b1c346e3f001 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -536,7 +536,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
- WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: @Odin #team-workflows
+ WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
XAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features
} as const
export type FeatureFlagLookupKey = keyof typeof FEATURE_FLAGS
diff --git a/frontend/src/lib/integrations/IntegrationView.tsx b/frontend/src/lib/integrations/IntegrationView.tsx
index e2a94a78901e..1ed344c2d282 100644
--- a/frontend/src/lib/integrations/IntegrationView.tsx
+++ b/frontend/src/lib/integrations/IntegrationView.tsx
@@ -1,3 +1,4 @@
+import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
@@ -18,7 +19,7 @@ import { urls } from 'scenes/urls'
import { IntegrationType } from '~/types'
import { integrationsLogic } from './integrationsLogic'
-import { getIntegrationNameFromKind } from './utils'
+import { DARK_MODE_INVERT_ICON_KINDS, getIntegrationNameFromKind } from './utils'
export function IntegrationView({
integration,
@@ -74,7 +75,10 @@ export function IntegrationView({
src={integration.icon_url}
alt={`Integration for ${integrationName}`}
title={integrationName}
- className="w-10 h-10 rounded"
+ className={clsx(
+ 'w-10 h-10 rounded',
+ DARK_MODE_INVERT_ICON_KINDS.has(integration.kind) && 'dark:invert'
+ )}
/>
<div>
<div className="flex gap-2">
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index c682222bd0de..133ce840b031 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -2,6 +2,7 @@ import { capitalizeFirstLetter } from 'lib/utils/strings'
import { IntegrationKind } from '~/types'
+import IconApple from 'public/services/apple_search_ads.png'
import IconAwsS3 from 'public/services/aws-s3.png'
import IconAzureBlob from 'public/services/azure-blob-storage.png'
import IconBingAds from 'public/services/bing-ads.svg'
@@ -70,11 +71,16 @@ export const ICONS: Record<IntegrationKind, any> = {
'customerio-app': IconCustomerIO,
'customerio-webhook': IconCustomerIO,
'customerio-track': IconCustomerIO,
+ apns: IconApple,
postgresql: IconPostgres,
'aws-s3': IconAwsS3,
's3-compatible': IconS3Compatible,
}
+// Brand marks that are solid black/monochrome on a transparent background — they vanish against a dark
+// surface, so invert them in dark mode (`dark:invert`) wherever the integration icon is rendered.
+export const DARK_MODE_INVERT_ICON_KINDS = new Set<IntegrationKind>(['apns', 'github'])
+
export const getIntegrationNameFromKind = (kind: string): string => {
switch (kind) {
case 'google-pubsub':
@@ -107,6 +113,8 @@ export const getIntegrationNameFromKind = (kind: string): string => {
return 'GitHub'
case 'firebase':
return 'Firebase'
+ case 'apns':
+ return 'Apple Push Notification Service'
case 'postgresql':
return 'PostgreSQL'
case 'aws-s3':
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 58b3b022fa5d..f162e1df9eb5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -26841,6 +26841,7 @@
"customerio-app",
"customerio-webhook",
"customerio-track",
+ "apns",
"postgresql",
"aws-s3",
"s3-compatible"
diff --git a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
index fe6e9c1456ac..a5e195be331f 100644
--- a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
+++ b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
@@ -179,6 +179,11 @@ export const hogFunctionTemplateListLogic = kea<hogFunctionTemplateListLogicType
x.id !== 'template-source-vercel-log-drain' ||
!!featureFlags[FEATURE_FLAGS.CDP_VERCEL_LOG_DRAIN]
)
+ .filter(
+ (x) =>
+ x.id !== 'template-native-push' ||
+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS]
+ )
.filter((x) => x.id !== 'template-microsoft-ads' || !!featureFlags[FEATURE_FLAGS.CDP_MICROSOFT_ADS])
.sort((a, b) => (a.name || '').localeCompare(b.name || ''))
},
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 59fde864e90f..4cf8eedb3867 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5411,6 +5411,7 @@ export const INTEGRATION_KINDS = [
'customerio-app',
'customerio-webhook',
'customerio-track',
+ 'apns',
'postgresql',
'aws-s3',
's3-compatible',
@@ -6946,6 +6947,7 @@ export type CyclotronJobInputSchemaType = {
| 'choice'
| 'json'
| 'integration'
+ | 'integration_multi'
| 'integration_field'
| 'email'
| 'native_email'
diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.ts
index 99ebba277d03..c380596bf28d 100644
--- a/nodejs/src/cdp/async-functions/index.ts
+++ b/nodejs/src/cdp/async-functions/index.ts
@@ -2,4 +2,5 @@ import './conversations'
import './customer_analytics'
import './fetch-handler'
import './send-email'
+import './send-push-notification'
import './warehouse-webhooks'
diff --git a/nodejs/src/cdp/async-functions/send-push-notification.ts b/nodejs/src/cdp/async-functions/send-push-notification.ts
new file mode 100644
index 000000000000..a110b6d747b8
--- /dev/null
+++ b/nodejs/src/cdp/async-functions/send-push-notification.ts
@@ -0,0 +1,31 @@
+import { DateTime } from 'luxon'
+
+import { CyclotronInvocationQueueParametersSendPushNotificationSchema } from '~/cdp/schema/cyclotron'
+
+import { registerAsyncFunction } from '../async-function-registry'
+
+registerAsyncFunction('sendPushNotification', {
+ execute: (args, _context, result) => {
+ result.invocation.queueParameters = CyclotronInvocationQueueParametersSendPushNotificationSchema.parse({
+ ...args[0],
+ type: 'sendPushNotification',
+ })
+ },
+
+ mock: (args, logs) => {
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `Async function 'sendPushNotification' was mocked with arguments:`,
+ })
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `sendPushNotification(${JSON.stringify(args[0], null, 2)})`,
+ })
+
+ return {
+ success: true,
+ }
+ },
+})
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index adfdaa499d7d..222d586083cb 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -19,7 +19,7 @@ import {
import { CdpProducerName } from './outputs/producers'
import { createCdpOutputsRegistry } from './outputs/registry'
import { CapturedEventsService } from './services/captured-events/captured-events.service'
-import { HogExecutorService } from './services/hog-executor.service'
+import { HogExecutorService, MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './services/hog-executor.service'
import { HogInputsService } from './services/hog-inputs.service'
import { HogFlowDuplicateObserverService } from './services/hogflows/hogflow-duplicate-observer.service'
import { HogFlowExecutorService } from './services/hogflows/hogflow-executor.service'
@@ -35,6 +35,7 @@ import { EmailValidationService } from './services/messaging/email-validation.se
import { EmailService } from './services/messaging/email.service'
import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { MessageAssetsService } from './services/messaging/message-assets.service'
+import { PushNotificationService } from './services/messaging/push-notification.service'
import { RecipientPreferencesService } from './services/messaging/recipient-preferences.service'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService } from './services/monitoring/hog-function-monitoring.service'
@@ -387,7 +388,6 @@ export function createCdpCoreServices(
)
: null
- const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)
@@ -407,6 +407,16 @@ export function createCdpCoreServices(
messageAssetsService
)
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)
+ const pushNotificationService = new PushNotificationService(
+ deps.integrationManager,
+ deps.encryptedFields,
+ {
+ trackedFetch: cdpTrackedFetch,
+ maxFetchTimeoutMs: MAX_FETCH_TIMEOUT_MS,
+ },
+ redis
+ )
const hogExecutor = new HogExecutorService(
{
@@ -419,7 +429,8 @@ export function createCdpCoreServices(
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ pushNotificationService
)
const hogFunctionTemplateManager = new HogFunctionTemplateManagerService(deps.postgres)
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index ebb7dc37dfc7..b1152e7d9821 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -15,7 +15,7 @@ import { CyclotronJobInvocationResult, HogFunctionInvocationGlobals, HogFunction
import { isLegacyPluginHogFunction } from '../../cdp/utils'
import type { CommonConfig } from '../../common/config'
import { CdpCoreServicesConfig, createCdpReaderRedisPool, createCdpValkeyShadowPools } from '../cdp-services'
-import { HogExecutorService } from '../services/hog-executor.service'
+import { HogExecutorService, MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from '../services/hog-executor.service'
import { HogInputsService } from '../services/hog-inputs.service'
import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'
import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'
@@ -23,6 +23,7 @@ import { IntegrationManagerService } from '../services/managers/integration-mana
import { TeamWorkflowsConfigService } from '../services/managers/team-workflows-config.service'
import { EmailService } from '../services/messaging/email.service'
import { EmailTrackingCodeSigner } from '../services/messaging/helpers/tracking-code'
+import { PushNotificationService } from '../services/messaging/push-notification.service'
import { RecipientTokensService } from '../services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService, MonitoringOutput } from '../services/monitoring/hog-function-monitoring.service'
import { HogWatcherService, HogWatcherState } from '../services/monitoring/hog-watcher.service'
@@ -504,7 +505,8 @@ export function createHogTransformerService(
const valkeyShadow = createCdpValkeyShadowPools(config, 'hog-transformer-redis')
const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)
- const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)
const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
const emailService = new EmailService(
@@ -520,7 +522,15 @@ export function createHogTransformerService(
config.SITE_URL,
trackingCodeSigner
)
- const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const pushNotificationService = new PushNotificationService(
+ deps.integrationManager,
+ deps.encryptedFields,
+ {
+ trackedFetch: cdpTrackedFetch,
+ maxFetchTimeoutMs: MAX_FETCH_TIMEOUT_MS,
+ },
+ redis
+ )
const hogExecutor = new HogExecutorService(
{
hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
@@ -532,7 +542,8 @@ export function createHogTransformerService(
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ pushNotificationService
)
const pluginExecutor = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)
const hogFunctionMonitoringService = new HogFunctionMonitoringService(deps.monitoringOutputs)
diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.ts
index 0a659754bf06..6c4fe185617f 100644
--- a/nodejs/src/cdp/schema/cyclotron.ts
+++ b/nodejs/src/cdp/schema/cyclotron.ts
@@ -1,5 +1,7 @@
import { z } from 'zod'
+import { PushNotificationPayloadSchema } from './pushNotification'
+
export const CyclotronInputSchema = z.object({
value: z.any(),
templating: z.enum(['hog', 'liquid']).optional(),
@@ -17,12 +19,14 @@ export const CyclotronJobInputSchemaTypeSchema = z.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
'posthog_assignee',
'posthog_ticket_tags',
'posthog_business_hours',
+ 'push_subscription',
'customer_analytics_account_properties',
'customer_analytics_account_relationships',
]),
@@ -112,12 +116,27 @@ export const CyclotronInvocationQueueParametersEmailSchema = z.object({
html: z.string(),
})
+export const CyclotronInvocationQueueParametersSendPushNotificationSchema = z.object({
+ type: z.literal('sendPushNotification'),
+ integrationIds: z.array(z.number()),
+ distinctId: z.string(),
+ payload: PushNotificationPayloadSchema,
+ max_tries: z.number().optional(),
+ timeoutMs: z.number().optional(),
+})
+
+export type PushNotificationPayloadType = z.infer<typeof PushNotificationPayloadSchema>
+
export type CyclotronInvocationQueueParametersFetchAwsSigV4Type = z.infer<
typeof CyclotronInvocationQueueParametersFetchAwsSigV4Schema
>
export type CyclotronInvocationQueueParametersFetchType = z.infer<typeof CyclotronInvocationQueueParametersFetchSchema>
export type CyclotronInvocationQueueParametersEmailType = z.infer<typeof CyclotronInvocationQueueParametersEmailSchema>
+export type CyclotronInvocationQueueParametersSendPushNotificationType = z.infer<
+ typeof CyclotronInvocationQueueParametersSendPushNotificationSchema
+>
export type CyclotronInvocationQueueParametersType =
| CyclotronInvocationQueueParametersFetchType
| CyclotronInvocationQueueParametersEmailType
+ | CyclotronInvocationQueueParametersSendPushNotificationType
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index 07ca13cf6b44..8ae3f3cff980 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -205,6 +205,18 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
mappings: z.array(CyclotronInputMappingSchema).optional(),
}),
}),
+ z.object({
+ ..._commonActionFields,
+ type: z.literal('function_push'),
+ config: z.object({
+ message_category_id: z.string().uuid().optional(),
+ message_category_type: z.enum(['marketing', 'transactional']).optional(),
+ template_uuid: z.string().uuid().optional(),
+ template_id: z.literal('template-native-push'),
+ inputs: z.record(z.string(), CyclotronInputSchema),
+ mappings: z.array(CyclotronInputMappingSchema).optional(),
+ }),
+ }),
// Exit
z.object({
..._commonActionFields,
diff --git a/nodejs/src/cdp/schema/pushNotification.ts b/nodejs/src/cdp/schema/pushNotification.ts
new file mode 100644
index 000000000000..0a85894ac2f2
--- /dev/null
+++ b/nodejs/src/cdp/schema/pushNotification.ts
@@ -0,0 +1,47 @@
+import { z } from 'zod'
+
+export const PushNotificationPayloadSchema = z.object({
+ // Common notification fields
+ title: z.string(),
+ body: z.string().optional(),
+ image: z.string().url().optional(),
+ data: z.record(z.string(), z.string()).optional(),
+ collapseKey: z.string().optional(),
+ ttlSeconds: z.number().int().min(0).optional(),
+ // Android-specific overrides (used by FCM)
+ android: z
+ .object({
+ priority: z.enum(['normal', 'high']).optional(),
+ channelId: z.string().optional(),
+ sound: z.string().optional(),
+ tag: z.string().optional(),
+ icon: z.string().optional(),
+ color: z.string().optional(),
+ clickAction: z.string().optional(),
+ })
+ .optional(),
+ // iOS-specific overrides (used by FCM APNS bridge and direct APNS)
+ apns: z
+ .object({
+ sound: z
+ .union([
+ z.string(),
+ z.object({
+ name: z.string(),
+ critical: z.boolean().optional(),
+ volume: z.number().min(0).max(1).optional(),
+ }),
+ ])
+ .optional(),
+ badge: z.number().int().optional(),
+ category: z.string().optional(),
+ threadId: z.string().optional(),
+ interruptionLevel: z.enum(['passive', 'active', 'time-sensitive', 'critical']).optional(),
+ relevanceScore: z.number().min(0).max(1).optional(),
+ subtitle: z.string().optional(),
+ contentAvailable: z.boolean().optional(),
+ mutableContent: z.boolean().optional(),
+ targetContentId: z.string().optional(),
+ })
+ .optional(),
+})
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 0a95de3a17fd..f5e424fa79a0 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -53,7 +53,11 @@ describe('Hog Executor', () => {
jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
hub = await createHub()
- const hogInputsService = new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ const hogInputsService = new HogInputsService(
+ hub.integrationManager,
+ new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
+ hub.encryptedFields
+ )
const emailService = new EmailService(
{
sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
@@ -79,7 +83,8 @@ describe('Hog Executor', () => {
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ undefined as any
)
})
@@ -88,6 +93,26 @@ describe('Hog Executor', () => {
jest.restoreAllMocks()
})
+ describe('getSensitiveValues', () => {
+ it('masks the nested secrets of every integration in an integration_multi input', () => {
+ const hogFunction = {
+ inputs_schema: [{ type: 'integration_multi', key: 'channels' }],
+ } as unknown as HogFunctionType
+ const inputs = {
+ channels: [
+ { $integration_id: 1, access_token_raw: 'fcm-secret-token' },
+ { $integration_id: 2, signing_key: 'apns-signing-key-secret' },
+ ],
+ }
+
+ const values = executor.getSensitiveValues(hogFunction, inputs)
+
+ // Without integration_multi + array handling these secrets leak into team-visible logs.
+ expect(values).toContain('fcm-secret-token')
+ expect(values).toContain('apns-signing-key-secret')
+ })
+ })
+
describe('general event processing', () => {
let hogFunction: HogFunctionType
beforeEach(() => {
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index 1772dbef713c..a5ff1ab8b632 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -34,6 +34,7 @@ import { createInvocation, createInvocationResult } from '../utils/invocation-ut
import { isNonFailureStatus } from '../utils/non-failure-status-codes'
import { HogInputsService } from './hog-inputs.service'
import { EmailService } from './messaging/email.service'
+import { PushNotificationService } from './messaging/push-notification.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
import {
SELF_LOOP_MAX_DEPTH,
@@ -169,6 +170,7 @@ export const getNextRetryTime = (backoffBaseMs: number, backoffMaxMs: number, tr
export const MAX_ASYNC_STEPS = 5
export const MAX_HOG_LOGS = 25
export const EXTEND_OBJECT_KEY = '$$_extend_object'
+export const MAX_FETCH_TIMEOUT_MS = 10000
const hogExecutionDuration = new Histogram({
name: 'cdp_hog_function_execution_duration_ms',
@@ -204,7 +206,8 @@ export class HogExecutorService {
private asyncContext: HogExecutorAsyncContext,
private hogInputsService: HogInputsService,
private emailService: EmailService,
- private recipientTokensService: RecipientTokensService
+ private recipientTokensService: RecipientTokensService,
+ private pushNotificationService: PushNotificationService
) {}
async buildInputsWithGlobals(
@@ -394,7 +397,7 @@ export class HogExecutorService {
const nextInvocation: CyclotronJobInvocationHogFunction = result?.invocation ?? invocation
const queueParamsType = nextInvocation.queueParameters?.type
- if (['fetch', 'email'].includes(queueParamsType ?? '')) {
+ if (['fetch', 'sendPushNotification', 'email'].includes(queueParamsType ?? '')) {
asyncFunctionCount++
if (result && asyncFunctionCount > maxAsyncFunctions) {
@@ -421,6 +424,8 @@ export class HogExecutorService {
} else {
result = await this.executeFetch(nextInvocation, options)
}
+ } else if (queueParamsType === 'sendPushNotification') {
+ result = await this.pushNotificationService.executeSendPushNotification(nextInvocation)
} else if (queueParamsType === 'email') {
// Route to the email queue only if we're not already there and the
// caller hasn't asked for inline-only execution (e.g. the test panel).
@@ -794,7 +799,13 @@ export class HogExecutorService {
if (Object.keys(integrationInputs).length > 0) {
for (const [key, value] of Object.entries(integrationInputs)) {
- const accessToken: string = value.value?.access_token_raw
+ const inputValue = value.value
+ // integration_multi inputs resolve to an array of integrations (e.g. push channels)
+ // and don't participate in the single access-token placeholder substitution below.
+ if (Array.isArray(inputValue) || !inputValue) {
+ continue
+ }
+ const accessToken: string = inputValue.access_token_raw
if (!accessToken) {
continue
}
@@ -987,21 +998,38 @@ export class HogExecutorService {
getSensitiveValues(hogFunction: HogFunctionType, inputs: Record<string, any>): string[] {
const values: string[] = []
+ const collectStringValues = (obj: any): void => {
+ if (obj && typeof obj === 'object') {
+ // Assume the values are the sensitive parts
+ Object.values(obj).forEach((val: any) => {
+ if (typeof val === 'string') {
+ values.push(val)
+ }
+ })
+ }
+ }
+
hogFunction.inputs_schema?.forEach((schema) => {
- if (schema.secret || schema.type === 'integration') {
+ if (
+ schema.secret ||
+ schema.type === 'integration' ||
+ schema.type === 'integration_multi' ||
+ schema.type === 'push_subscription'
+ ) {
const value = inputs[schema.key]
if (typeof value === 'string') {
values.push(value)
+ } else if (schema.type === 'integration_multi' && Array.isArray(value)) {
+ // integration_multi resolves to an array of integration objects, each carrying its own
+ // sensitive_config (e.g. APNs signing_key, FCM access_token_raw) — mask every one.
+ value.forEach(collectStringValues)
} else if (
- (schema.type === 'dictionary' || schema.type === 'integration') &&
+ (schema.type === 'dictionary' ||
+ schema.type === 'integration' ||
+ schema.type === 'push_subscription') &&
typeof value === 'object'
) {
- // Assume the values are the sensitive parts
- Object.values(value).forEach((val: any) => {
- if (typeof val === 'string') {
- values.push(val)
- }
- })
+ collectStringValues(value)
}
}
})
diff --git a/nodejs/src/cdp/services/hog-inputs.service.test.ts b/nodejs/src/cdp/services/hog-inputs.service.test.ts
index eaeb530d235d..f392d3481709 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.test.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.test.ts
@@ -9,7 +9,41 @@ import { Hub, Team } from '~/types'
import { createHogExecutionGlobals, createHogFunction, insertIntegration } from '../_tests/fixtures'
import { compileHog } from '../templates/compiler'
import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'
-import { HogInputsService, formatHogInput } from './hog-inputs.service'
+import { HogInputsService, formatHogInput, getAppIdentifierForPush } from './hog-inputs.service'
+import { RecipientTokensService } from './messaging/recipient-tokens.service'
+
+describe('getAppIdentifierForPush', () => {
+ it('returns null when no integration inputs are present', () => {
+ expect(getAppIdentifierForPush({})).toBeNull()
+ expect(getAppIdentifierForPush({ push_provider: { value: null } })).toBeNull()
+ })
+
+ it('returns null when integration has no project_id or bundle_id', () => {
+ expect(getAppIdentifierForPush({ push_provider: { value: { key_id: 'abc' } } })).toBeNull()
+ })
+
+ it('returns project_id from a Firebase integration input', () => {
+ const result = getAppIdentifierForPush({
+ push_provider: { value: { project_id: 'my-firebase-project', key_id: 'abc' } },
+ })
+ expect(result).toBe('my-firebase-project')
+ })
+
+ it('returns bundle_id from an APNS integration input', () => {
+ const result = getAppIdentifierForPush({
+ push_provider: { value: { bundle_id: 'com.example.app', key_id: 'abc' } },
+ })
+ expect(result).toBe('com.example.app')
+ })
+
+ it('returns the first app identifier when multiple integrations are present', () => {
+ const result = getAppIdentifierForPush({
+ firebase_account: { value: { project_id: 'firebase-proj' } },
+ apns_account: { value: { bundle_id: 'com.example.app' } },
+ })
+ expect(result).toBe('firebase-proj')
+ })
+})
describe('Hog Inputs', () => {
let hub: Hub
@@ -44,7 +78,8 @@ describe('Hog Inputs', () => {
},
})
- hogInputsService = new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ hogInputsService = new HogInputsService(hub.integrationManager, recipientTokensService, hub.encryptedFields)
})
afterEach(async () => {
@@ -159,48 +194,35 @@ describe('Hog Inputs', () => {
expect(inputs.liquid_templated).toMatchInlineSnapshot(`"event: "test""`)
})
- it('should loads inputs with integration inputs', async () => {
- const inputs = await hogInputsService.buildInputs(hogFunction, globals)
-
- expect(inputs.oauth).toMatchInlineSnapshot(`
- {
- "access_token": "$$_access_token_placeholder_1",
- "access_token_raw": "token",
- "not_encrypted": "not-encrypted",
- "team": "foobar",
- }
- `)
- })
-
- it('access token should be replaced with placeholder', async () => {
+ it('should load integration inputs and replace access tokens with placeholders', async () => {
hogFunction = createHogFunction({
- id: 'hog-function-1',
- team_id: team.id,
- name: 'Hog Function 1',
- enabled: true,
- type: 'destination',
+ ...hogFunction,
inputs: {
- hog_templated: {
- value: 'event: "{event.event}"',
- templating: 'hog',
- bytecode: await compileHog('return f\'event: "{event.event}"\''),
- },
- liquid_templated: {
- value: 'event: "{{ event.event }}"',
- templating: 'liquid',
- },
+ hog_templated: hogFunction.inputs!.hog_templated,
+ liquid_templated: hogFunction.inputs!.liquid_templated,
+ oauth: { value: 1 },
auth: { value: 2 },
},
inputs_schema: [
{ key: 'hog_templated', type: 'string', required: true },
+ { key: 'oauth', type: 'integration', required: true },
{ key: 'auth', type: 'integration', required: true },
],
})
-
const inputs = await hogInputsService.buildInputs(hogFunction, globals)
+ expect(inputs.oauth).toMatchInlineSnapshot(`
+ {
+ "$integration_id": 1,
+ "access_token": "$$_access_token_placeholder_1",
+ "access_token_raw": "token",
+ "not_encrypted": "not-encrypted",
+ "team": "foobar",
+ }
+ `)
expect(inputs.auth).toMatchInlineSnapshot(`
{
+ "$integration_id": 2,
"access_token": "$$_access_token_placeholder_2",
"access_token_raw": "token",
"not_encrypted": "not-encrypted",
@@ -262,5 +284,33 @@ describe('Hog Inputs', () => {
`<div>Manage subscription preferences here <a href="http://localhost:8000/messaging-preferences/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZWFtX2lkIjoyLCJpZGVudGlmaWVyIjoidGVzdEBwb3N0aG9nLmNvbSIsImlhdCI6MTczNTY4OTYwMCwiZXhwIjoxNzM2Mjk0NDAwLCJhdWQiOiJwb3N0aG9nOm1lc3NhZ2luZzpzdWJzY3JpcHRpb25fcHJlZmVyZW5jZXMifQ.pBh-COzTEyApuxe8J5sViPanp1lV1IClepOTVFZNhIs/">here</a>Or, click <a href="http://localhost:8000/messaging-preferences/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZWFtX2lkIjoyLCJpZGVudGlmaWVyIjoidGVzdEBwb3N0aG9nLmNvbSIsImlhdCI6MTczNTY4OTYwMCwiZXhwIjoxNzM2Mjk0NDAwLCJhdWQiOiJwb3N0aG9nOm1lc3NhZ2luZzpzdWJzY3JpcHRpb25fcHJlZmVyZW5jZXMifQ.pBh-COzTEyApuxe8J5sViPanp1lV1IClepOTVFZNhIs/?one_click_unsubscribe=1">here</a> to immediately unsubscribe from all marketing emails</div>`
)
})
+
+ it('resolves push subscription inputs without a valid integration', async () => {
+ const hogFunction = createHogFunction({
+ id: 'hog-function-1',
+ team_id: team.id,
+ name: 'Hog Function 1',
+ enabled: true,
+ type: 'destination',
+ inputs: {
+ push_provider: { value: 999 },
+ push_subscription: { value: 'user-123' },
+ },
+ inputs_schema: [
+ {
+ key: 'push_provider',
+ type: 'integration',
+ },
+ {
+ key: 'push_subscription',
+ type: 'push_subscription',
+ platform: 'android',
+ },
+ ],
+ })
+
+ const inputs = await hogInputsService.buildInputs(hogFunction, globals)
+ expect(inputs.push_subscription).toBeNull()
+ })
})
})
diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.ts
index 87e9cb37bcde..e16f6576f16a 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.ts
@@ -2,25 +2,24 @@ import { convertHogToJS } from '@posthog/hogvm'
import { CyclotronInputType } from '~/cdp/schema/cyclotron'
import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
+import { logger } from '~/common/utils/logger'
import { HogFunctionInvocationGlobals, HogFunctionInvocationGlobalsWithInputs, HogFunctionType } from '../types'
+import { EncryptedFields } from '../utils/encryption-utils'
import { execHog } from '../utils/hog-exec'
import { LiquidRenderer } from '../utils/liquid'
+import { getDevicePushSubscriptionToken } from '../utils/push-subscription-utils'
import { IntegrationManagerService } from './managers/integration-manager.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
export const EXTEND_OBJECT_KEY = '$$_extend_object'
export class HogInputsService {
- private recipientTokensService: RecipientTokensService
-
constructor(
private integrationManager: IntegrationManagerService,
- encryptionSaltKeys: string,
- siteUrl: string
- ) {
- this.recipientTokensService = new RecipientTokensService(encryptionSaltKeys, siteUrl)
- }
+ private recipientTokensService: RecipientTokensService,
+ private encryptedFields: EncryptedFields
+ ) {}
public async buildInputs(
hogFunction: HogFunctionType,
@@ -28,20 +27,18 @@ export class HogInputsService {
additionalInputs?: Record<string, any>
): Promise<Record<string, any>> {
// TODO: Load the values from the integrationManager
-
+ const newGlobals: HogFunctionInvocationGlobalsWithInputs = {
+ ...globals,
+ inputs: {},
+ }
const inputs: HogFunctionType['inputs'] = {
// Include the inputs from the hog function
...hogFunction.inputs,
...hogFunction.encrypted_inputs,
// Plus any additional inputs
...additionalInputs,
- // and decode any integration inputs
- ...(await this.loadIntegrationInputs(hogFunction)),
- }
-
- const newGlobals: HogFunctionInvocationGlobalsWithInputs = {
- ...globals,
- inputs: {},
+ // and decode any integration inputs (and push subscription inputs when newGlobals provided)
+ ...(await this.loadIntegrationInputs(hogFunction, newGlobals)),
}
const _formatInput = async (input: CyclotronInputType, key: string): Promise<any> => {
@@ -119,52 +116,115 @@ export class HogInputsService {
}
}
- public async loadIntegrationInputs(
- hogFunction: HogFunctionType
- ): Promise<Record<string, { value: Record<string, any> | null }>> {
- const inputsToLoad: Record<string, number> = {}
+ private resolvePushSubscriptionInputs(
+ hogFunction: HogFunctionType,
+ integrationInputs: Record<string, { value: Record<string, any> | Record<string, any>[] | null }>,
+ newGlobals: HogFunctionInvocationGlobalsWithInputs
+ ): Record<string, { value: string | null }> {
+ const result: Record<string, { value: string | null }> = {}
+ const personProperties = newGlobals.person?.properties
+
+ const appIdentifier = getAppIdentifierForPush(integrationInputs)
hogFunction.inputs_schema?.forEach((schema) => {
+ if (schema.type !== 'push_subscription') {
+ return
+ }
+
+ if (!appIdentifier) {
+ logger.warn('🦔', '[HogInputsService] No push integration found for push subscription input', {
+ hogFunctionId: hogFunction.id,
+ hogFunctionName: hogFunction.name,
+ teamId: hogFunction.team_id,
+ inputKey: schema.key,
+ })
+ result[schema.key] = { value: null }
+ return
+ }
+
+ const token = getDevicePushSubscriptionToken(personProperties, appIdentifier, this.encryptedFields)
+ result[schema.key] = { value: token }
+ })
+
+ return result
+ }
+
+ public async loadIntegrationInputs(
+ hogFunction: HogFunctionType,
+ newGlobals?: HogFunctionInvocationGlobalsWithInputs
+ ): Promise<Record<string, { value: Record<string, any> | Record<string, any>[] | null }>> {
+ // Single integration inputs map a key to one id; integration_multi maps a key to a list of ids.
+ const singleInputsToLoad: Record<string, number> = {}
+ const multiInputsToLoad: Record<string, number[]> = {}
+
+ const allSchemas = [
+ ...(hogFunction.inputs_schema ?? []),
+ ...(hogFunction.mappings?.flatMap((m) => m.inputs_schema ?? []) ?? []),
+ ]
+ const allInputs: Record<string, CyclotronInputType | null | undefined> = {
+ ...hogFunction.inputs,
+ }
+ for (const mapping of hogFunction.mappings ?? []) {
+ Object.assign(allInputs, mapping.inputs)
+ }
+
+ allSchemas.forEach((schema) => {
+ const value = allInputs[schema.key]?.value
if (schema.type === 'integration') {
- const input = hogFunction.inputs?.[schema.key]
- const value = input?.value?.integrationId ?? input?.value
if (value && typeof value === 'number') {
- inputsToLoad[schema.key] = value
+ singleInputsToLoad[schema.key] = value
+ }
+ } else if (schema.type === 'integration_multi') {
+ if (Array.isArray(value)) {
+ const ids = value.filter((v): v is number => typeof v === 'number')
+ if (ids.length > 0) {
+ multiInputsToLoad[schema.key] = ids
+ }
}
}
})
- if (Object.keys(inputsToLoad).length === 0) {
+ const allIds = [...Object.values(singleInputsToLoad), ...Object.values(multiInputsToLoad).flat()]
+ if (allIds.length === 0) {
return {}
}
- const integrations = await this.integrationManager.getMany(Object.values(inputsToLoad))
- const returnInputs: Record<string, { value: Record<string, any> | null }> = {}
+ const integrations = await this.integrationManager.getMany(allIds)
+ const returnInputs: Record<string, { value: Record<string, any> | Record<string, any>[] | null }> = {}
- Object.entries(inputsToLoad).forEach(([key, value]) => {
- returnInputs[key] = {
- value: null,
+ // IMPORTANT: Check the team ID is correct — never resolve an integration from another team.
+ const resolveIntegration = (id: number): Record<string, any> | null => {
+ const integration = integrations[id]
+ if (!integration || integration.team_id !== hogFunction.team_id) {
+ return null
}
-
- const integration = integrations[value]
- // IMPORTANT: Check the team ID is correct
- if (integration && integration.team_id === hogFunction.team_id) {
- returnInputs[key] = {
- value: {
- ...integration.config,
- ...integration.sensitive_config,
- ...(integration.sensitive_config.access_token || integration.config.access_token
- ? {
- access_token: ACCESS_TOKEN_PLACEHOLDER + integration.id,
- access_token_raw:
- integration.sensitive_config.access_token ?? integration.config.access_token,
- }
- : {}),
- },
- }
+ return {
+ $integration_id: integration.id,
+ ...integration.config,
+ ...integration.sensitive_config,
+ ...(integration.sensitive_config.access_token || integration.config.access_token
+ ? {
+ access_token: ACCESS_TOKEN_PLACEHOLDER + integration.id,
+ access_token_raw:
+ integration.sensitive_config.access_token ?? integration.config.access_token,
+ }
+ : {}),
}
+ }
+
+ Object.entries(singleInputsToLoad).forEach(([key, id]) => {
+ returnInputs[key] = { value: resolveIntegration(id) }
+ })
+
+ Object.entries(multiInputsToLoad).forEach(([key, ids]) => {
+ returnInputs[key] = { value: ids.map(resolveIntegration).filter((v) => v !== null) }
})
+ if (newGlobals) {
+ const pushSubscriptionInputs = this.resolvePushSubscriptionInputs(hogFunction, returnInputs, newGlobals)
+ Object.assign(returnInputs, pushSubscriptionInputs)
+ }
+
return returnInputs
}
}
@@ -251,3 +311,23 @@ export const formatLiquidInput = (
return value
}
+
+/**
+ * Finds the app identifier (project_id for Firebase, bundle_id for APNS) from resolved
+ * integration inputs. Used to key the $device_push_subscription_<appIdentifier> person property.
+ */
+export function getAppIdentifierForPush(
+ integrationInputs: Record<string, { value: Record<string, any> | Record<string, any>[] | null }>
+): string | null {
+ for (const input of Object.values(integrationInputs)) {
+ const value = input?.value
+ if (!value || Array.isArray(value)) {
+ continue
+ }
+ const appId = value.project_id ?? value.bundle_id
+ if (typeof appId === 'string' && appId) {
+ return appId
+ }
+ }
+ return null
+}
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 cde61aeb1d47..deef580c38f1 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -44,7 +44,12 @@ describe('HogFunctionHandler', () => {
hub = await createHub()
team = await getFirstTeam(hub.postgres)
- const hogInputsService = new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ const hogInputsService = new HogInputsService(
+ hub.integrationManager,
+ recipientTokensService,
+ hub.encryptedFields
+ )
const emailService = new EmailService(
{
sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
@@ -58,7 +63,6 @@ describe('HogFunctionHandler', () => {
hub.SITE_URL,
new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL)
)
- const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
mockHogFunctionExecutor = new HogExecutorService(
{
hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
@@ -70,7 +74,8 @@ describe('HogFunctionHandler', () => {
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ undefined as any
)
mockHogFunctionTemplateManager = new HogFunctionTemplateManagerService(hub.postgres)
mockHogFlowFunctionsService = new HogFlowFunctionsService(
@@ -185,7 +190,7 @@ describe('HogFunctionHandler', () => {
[
"http://localhost/test",
{
- "body": "{"name":"John Doe","oauth":{"team":"foobar","access_token":"token","not_encrypted":"not-encrypted","access_token_raw":"token"}}",
+ "body": "{"name":"John Doe","oauth":{"$integration_id":1,"team":"foobar","access_token":"token","not_encrypted":"not-encrypted","access_token_raw":"token"}}",
"headers": {
"Content-Type": "application/json",
},
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index a011a4da58b9..49833555ff1c 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -63,7 +63,11 @@ describe('Hogflow Executor', () => {
hub = await createHub({
SITE_URL: 'http://localhost:8000',
})
- const hogInputsService = new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
+ const hogInputsService = new HogInputsService(
+ hub.integrationManager,
+ new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
+ hub.encryptedFields
+ )
const emailService = new EmailService(
{
sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
@@ -89,7 +93,8 @@ describe('Hogflow Executor', () => {
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ undefined as any
)
const hogFunctionTemplateManager = new HogFunctionTemplateManagerService(hub.postgres)
const hogFlowFunctionsService = new HogFlowFunctionsService(
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index ea2223a4910e..eed473ce55ac 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -114,6 +114,7 @@ export class HogFlowExecutorService {
random_cohort_branch: new RandomCohortBranchHandler(),
function: hogFunctionHandler,
function_sms: hogFunctionHandler,
+ function_push: hogFunctionHandler,
function_email: hogFunctionEmailHandler,
exit: new ExitHandler(),
}
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
new file mode 100644
index 000000000000..2cdc7c573325
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -0,0 +1,659 @@
+import { generateKeyPairSync } from 'crypto'
+
+import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '~/cdp/_tests/examples'
+import { createExampleInvocation, createHogFunction } from '~/cdp/_tests/fixtures'
+import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
+import { EncryptedFields } from '~/cdp/utils/encryption-utils'
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { IntegrationManagerService } from '../managers/integration-manager.service'
+import { PushNotificationFetchUtils, PushNotificationService } from './push-notification.service'
+
+const encryptedFields = new EncryptedFields('01234567890123456789012345678901')
+
+const testEcKey = generateKeyPairSync('ec', {
+ namedCurve: 'prime256v1',
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+}).privateKey
+
+const createSendPushNotificationInvocation = (
+ personProperties?: Record<string, any>
+): CyclotronJobInvocationHogFunction => {
+ const hogFunction = createHogFunction({
+ name: 'Test FCM function',
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ inputs_schema: [
+ {
+ type: 'push_subscription',
+ platform: 'android',
+ key: 'device_token',
+ label: 'Device Token',
+ },
+ ],
+ })
+
+ const invocation = createExampleInvocation(hogFunction)
+
+ invocation.queueParameters = {
+ type: 'sendPushNotification',
+ integrationIds: [1],
+ distinctId: 'test-distinct-id',
+ payload: {
+ title: 'Test notification',
+ body: 'Hello from PostHog',
+ },
+ } as any
+
+ invocation.state.vmState = { stack: [] } as any
+
+ if (personProperties) {
+ invocation.state.globals.person = {
+ ...(invocation.state.globals.person ?? { id: 'person-1', name: 'Test', url: '' }),
+ properties: personProperties,
+ }
+ }
+
+ return invocation
+}
+
+describe('PushNotificationService', () => {
+ let service: PushNotificationService
+ let integrationManager: IntegrationManagerService
+ let fetchUtils: PushNotificationFetchUtils
+ let redisStore: Map<string, string>
+ let mockRedisSet: jest.Mock
+ let mockRedis: any
+
+ const mockTrackedFetch = jest.fn()
+
+ const firebaseIntegration = {
+ id: 1,
+ team_id: 1,
+ kind: 'firebase' as const,
+ config: { project_id: 'test-project' },
+ sensitive_config: { access_token: 'test-access-token' },
+ }
+
+ beforeEach(() => {
+ integrationManager = {
+ get: jest.fn().mockResolvedValue(firebaseIntegration),
+ } as any
+
+ fetchUtils = {
+ trackedFetch: mockTrackedFetch,
+ maxFetchTimeoutMs: 10000,
+ }
+
+ redisStore = new Map<string, string>()
+ mockRedisSet = jest.fn((key: string, value: string) => {
+ redisStore.set(key, value)
+ return 'OK'
+ })
+ mockRedis = {
+ useClient: jest.fn((_opts: any, fn: any) =>
+ fn({
+ get: (key: string) => redisStore.get(key) ?? null,
+ set: mockRedisSet,
+ })
+ ),
+ } as any
+
+ service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockRedis)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ describe('executeSendPushNotification', () => {
+ it('throws when queue parameters type is not sendPushNotification', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ invocation.queueParameters = { type: 'fetch', url: 'http://example.com', method: 'POST' } as any
+
+ await expect(service.executeSendPushNotification(invocation)).rejects.toThrow('Bad invocation')
+ expect(mockTrackedFetch).not.toHaveBeenCalled()
+ })
+
+ it('calls trackedFetch with url and fetchParams', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ expect(mockTrackedFetch).toHaveBeenCalledWith({
+ url: 'https://fcm.googleapis.com/v1/projects/test-project/messages:send',
+ fetchParams: expect.objectContaining({ method: 'POST' }),
+ templateId: 'unknown',
+ })
+ })
+
+ it('returns result with metric push_sent on success', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.metrics).toContainEqual(
+ expect.objectContaining({
+ metric_name: 'push_sent',
+ count: 1,
+ })
+ )
+ expect(result.finished).toBe(true)
+ })
+
+ it('logs warning and records push_skipped when no device token found', async () => {
+ const invocation = createSendPushNotificationInvocation({})
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.logs.map((log) => log.message)).toContainEqual(
+ expect.stringContaining('No active FCM device token found')
+ )
+ // No token means nothing was delivered — record push_skipped, not push_sent.
+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_skipped', count: 1 }))
+ expect(result.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_sent' }))
+ })
+
+ it('does not match tokens for a different app identifier', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_other-project': encryptedFields.encrypt('other-token'),
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.logs.map((log) => log.message)).toContainEqual(
+ expect.stringContaining('No active FCM device token found')
+ )
+ expect(mockTrackedFetch).not.toHaveBeenCalled()
+ })
+
+ it('sets error when push fails', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 500,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ })
+
+ it('prunes an unregistered FCM token and skips the channel without erroring', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 404,
+ text: () =>
+ Promise.resolve(
+ JSON.stringify({ error: { status: 'NOT_FOUND', details: [{ errorCode: 'UNREGISTERED' }] } })
+ ),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ // Dead token: removed via a $unset person update, and the channel is skipped (not errored → no retry).
+ expect(result.error).toBeUndefined()
+ expect(result.capturedPostHogEvents).toContainEqual(
+ expect.objectContaining({
+ event: '$set',
+ distinct_id: 'test-distinct-id',
+ properties: { $unset: ['$device_push_subscription_test-project'] },
+ })
+ )
+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_skipped' }))
+ })
+
+ it('puts an iOS subtitle in the APNS alert, not the FCM notification (FCM rejects notification.subtitle)', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ })
+ invocation.queueParameters = {
+ ...invocation.queueParameters,
+ payload: { title: 'T', body: 'B', apns: { subtitle: 'Sub' } },
+ } as any
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ const body = parseJSON(mockTrackedFetch.mock.calls[0][0].fetchParams.body)
+ expect(body.message.notification.subtitle).toBeUndefined()
+ expect(body.message.apns.payload.aps.alert).toEqual({ title: 'T', body: 'B', subtitle: 'Sub' })
+ })
+
+ it('returns error when integration not found', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ ;(integrationManager.get as jest.Mock).mockResolvedValue(undefined)
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ expect(result.logs.map((log) => log.message)).toContain('Push notification integration not found')
+ })
+
+ it('handles missing person properties gracefully', async () => {
+ const invocation = createSendPushNotificationInvocation()
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.logs.map((log) => log.message)).toContainEqual(
+ expect.stringContaining('No active FCM device token found')
+ )
+ })
+ })
+
+ describe('APNS path', () => {
+ const apnsIntegration = {
+ id: 2,
+ team_id: 1,
+ kind: 'apns' as const,
+ config: { key_id: 'KEY123', team_id: 'TEAM456', bundle_id: 'com.example.app' },
+ sensitive_config: { signing_key: testEcKey },
+ }
+
+ beforeEach(() => {
+ ;(integrationManager.get as jest.Mock).mockResolvedValue(apnsIntegration)
+ })
+
+ it('sends push notification via APNS', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve(''),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 15,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.finished).toBe(true)
+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_sent', count: 1 }))
+ expect(mockTrackedFetch).toHaveBeenCalledWith({
+ url: 'https://api.push.apple.com/3/device/apns-device-token',
+ fetchParams: expect.objectContaining({
+ method: 'POST',
+ allowH2: true,
+ headers: expect.objectContaining({
+ 'apns-topic': 'com.example.app',
+ 'apns-push-type': 'alert',
+ }),
+ }),
+ templateId: 'unknown',
+ })
+ })
+
+ it('reuses a cached APNS provider token across sends instead of minting one each time', async () => {
+ const send = (): Promise<any> =>
+ service.executeSendPushNotification(
+ createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ )
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 15,
+ })
+
+ await send()
+ await send()
+
+ // The JWT is written to Redis once and read back on the second send. Minting a new token per
+ // send is what makes Apple return 429 TooManyProviderTokenUpdates.
+ expect(mockRedisSet).toHaveBeenCalledTimes(1)
+ })
+
+ it('sets apns-priority to 5 for passive interruption level', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ invocation.queueParameters = {
+ ...invocation.queueParameters,
+ payload: {
+ title: 'Test',
+ apns: { interruptionLevel: 'passive' },
+ },
+ } as any
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ expect(mockTrackedFetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fetchParams: expect.objectContaining({
+ headers: expect.objectContaining({ 'apns-priority': '5' }),
+ }),
+ })
+ )
+ })
+
+ it('sets apns-priority to 10 for active interruption level', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ invocation.queueParameters = {
+ ...invocation.queueParameters,
+ payload: {
+ title: 'Test',
+ apns: { interruptionLevel: 'active' },
+ },
+ } as any
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ expect(mockTrackedFetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fetchParams: expect.objectContaining({
+ headers: expect.objectContaining({ 'apns-priority': '10' }),
+ }),
+ })
+ )
+ })
+
+ it('includes apns-collapse-id and apns-expiration headers when set', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ invocation.queueParameters = {
+ ...invocation.queueParameters,
+ payload: {
+ title: 'Test',
+ collapseKey: 'my-collapse',
+ ttlSeconds: 3600,
+ },
+ } as any
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ expect(mockTrackedFetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fetchParams: expect.objectContaining({
+ headers: expect.objectContaining({
+ 'apns-collapse-id': 'my-collapse',
+ 'apns-expiration': expect.stringMatching(/^\d+$/),
+ }),
+ }),
+ })
+ )
+ })
+
+ it('logs warning when no APNS device token found', async () => {
+ const invocation = createSendPushNotificationInvocation({})
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.logs.map((log) => log.message)).toContainEqual(
+ expect.stringContaining('No active APNS device token found')
+ )
+ expect(mockTrackedFetch).not.toHaveBeenCalled()
+ })
+
+ it('throws when APNS integration is missing required fields', async () => {
+ ;(integrationManager.get as jest.Mock).mockResolvedValue({
+ ...apnsIntegration,
+ config: { key_id: 'KEY123' },
+ })
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ expect(result.error).toContain('missing required fields')
+ })
+
+ it('generates a valid ES256 JWT with ieee-p1363 signature', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ const authHeader = mockTrackedFetch.mock.calls[0][0].fetchParams.headers['Authorization']
+ const jwt = authHeader.replace('bearer ', '')
+ const [headerB64, claimsB64, signatureB64] = jwt.split('.')
+
+ const header = parseJSON(Buffer.from(headerB64, 'base64url').toString())
+ expect(header).toEqual({ alg: 'ES256', kid: 'KEY123' })
+
+ const claims = parseJSON(Buffer.from(claimsB64, 'base64url').toString())
+ expect(claims.iss).toBe('TEAM456')
+ expect(claims.iat).toBeGreaterThan(0)
+
+ // IEEE P1363 ES256 signatures are exactly 64 bytes (32 bytes r + 32 bytes s)
+ const signatureBytes = Buffer.from(signatureB64, 'base64url')
+ expect(signatureBytes.length).toBe(64)
+ })
+
+ it('sets error when APNS returns failure', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 403,
+ text: () => Promise.resolve(JSON.stringify({ reason: 'InvalidProviderToken' })),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ expect(result.error).toContain('InvalidProviderToken')
+ })
+
+ it('does not let custom data overwrite the reserved aps payload', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ // A custom data key named `aps` must not clobber the real notification payload.
+ invocation.queueParameters = {
+ ...invocation.queueParameters,
+ payload: { title: 'Real title', data: { aps: 'hijacked', custom: 'kept' } },
+ } as any
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 15,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ const body = parseJSON(mockTrackedFetch.mock.calls[0][0].fetchParams.body)
+ expect(body.aps.alert.title).toBe('Real title')
+ expect(body.custom).toBe('kept')
+ })
+
+ it('prunes an unregistered APNS token (410) and skips the channel', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-token'),
+ })
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 410,
+ text: () => Promise.resolve(JSON.stringify({ reason: 'Unregistered' })),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeUndefined()
+ expect(result.capturedPostHogEvents).toContainEqual(
+ expect.objectContaining({
+ event: '$set',
+ properties: { $unset: ['$device_push_subscription_com.example.app'] },
+ })
+ )
+ })
+ })
+
+ describe('multiple channels', () => {
+ const apnsIntegration = {
+ id: 2,
+ team_id: 1,
+ kind: 'apns' as const,
+ config: { key_id: 'KEY123', team_id: 'TEAM456', bundle_id: 'com.example.app' },
+ sensitive_config: { signing_key: testEcKey },
+ }
+ const ok200 = {
+ fetchError: null,
+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ }
+
+ it('delivers to every channel in the list, not just the first', async () => {
+ ;(integrationManager.get as jest.Mock).mockImplementation((id: number) =>
+ Promise.resolve(id === 1 ? firebaseIntegration : apnsIntegration)
+ )
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-token'),
+ })
+ invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 2] } as any
+ mockTrackedFetch.mockResolvedValue(ok200)
+
+ await service.executeSendPushNotification(invocation)
+
+ // The bug: a per-channel loop in hog only ran once, so only the first channel delivered.
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(2)
+ const urls = mockTrackedFetch.mock.calls.map((c: any) => c[0].url)
+ expect(urls.some((u: string) => u.includes('fcm.googleapis.com'))).toBe(true)
+ expect(urls.some((u: string) => u.includes('push.apple.com'))).toBe(true)
+ })
+
+ it('deduplicates repeated channel ids so a device is not notified twice', async () => {
+ ;(integrationManager.get as jest.Mock).mockResolvedValue(firebaseIntegration)
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ })
+ invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 1, 1] } as any
+ mockTrackedFetch.mockResolvedValue(ok200)
+
+ await service.executeSendPushNotification(invocation)
+
+ // Three duplicate ids resolve to one unique channel — deliver once, not three times.
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps delivering to healthy channels when one channel errors', async () => {
+ const brokenApns = { ...apnsIntegration, config: {}, sensitive_config: {} }
+ ;(integrationManager.get as jest.Mock).mockImplementation((id: number) =>
+ Promise.resolve(id === 1 ? firebaseIntegration : brokenApns)
+ )
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ })
+ invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 2] } as any
+ mockTrackedFetch.mockResolvedValue(ok200)
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ // FCM still delivers though the APNS channel throws; a partial success is not a hard error.
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(1)
+ expect(mockTrackedFetch.mock.calls[0][0].url).toContain('fcm.googleapis.com')
+ expect(result.error).toBeUndefined()
+ })
+
+ it('retries when one channel is skipped and another genuinely fails', async () => {
+ ;(integrationManager.get as jest.Mock).mockImplementation((id: number) =>
+ Promise.resolve(id === 1 ? firebaseIntegration : apnsIntegration)
+ )
+ // Only the APNS token is registered: FCM is skipped (not a delivery), APNS is attempted.
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-token'),
+ })
+ invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 2] } as any
+ // APNS fails - nothing was delivered, so this must retry rather than silently drop the push.
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: { status: 500, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ // The error is also surfaced to the hog template, so its failure message is not blank.
+ expect(result.invocation.state.vmState!.stack.at(-1)).toEqual({
+ success: false,
+ error: expect.any(String),
+ })
+ })
+ })
+})
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
new file mode 100644
index 000000000000..bc6055eeecf7
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -0,0 +1,568 @@
+import { createHash, createSign } from 'crypto'
+import { Counter } from 'prom-client'
+
+import {
+ CyclotronInvocationQueueParametersSendPushNotificationType,
+ PushNotificationPayloadType,
+} from '~/cdp/schema/cyclotron'
+import { RedisV2 } from '~/common/redis/redis-v2'
+import { instrumented } from '~/common/tracing/tracing-utils'
+import { parseJSON } from '~/common/utils/json-parse'
+import { FetchOptions, FetchResponse } from '~/common/utils/request'
+
+import type { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, IntegrationType } from '../../types'
+import { createAddLogFunction } from '../../utils'
+import { EncryptedFields } from '../../utils/encryption-utils'
+import { createInvocationResult } from '../../utils/invocation-utils'
+import { getDevicePushSubscriptionToken } from '../../utils/push-subscription-utils'
+import { IntegrationManagerService } from '../managers/integration-manager.service'
+
+const pushNotificationSentCounter = new Counter({
+ name: 'push_notification_sent_total',
+ help: 'Total number of push notifications successfully sent',
+ labelNames: ['platform'],
+})
+
+const pushNotificationTokenPrunedCounter = new Counter({
+ name: 'push_notification_token_pruned_total',
+ help: 'Total number of device tokens removed after the provider reported them no longer registered',
+ labelNames: ['platform'],
+})
+
+// Apple rate-limits new APNs provider tokens (returns 429 TooManyProviderTokenUpdates if refreshed more
+// than once every ~20 min per key) and accepts a token for up to 1 hour. Cache the signed JWT in Redis
+// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.
+const APNS_JWT_CACHE_PREFIX = '@posthog/apns-provider-jwt/'
+const APNS_JWT_TTL_SECONDS = 45 * 60
+
+// A push action fans out to its selected channels within one invocation. Cap the count so a workflow
+// crafted with a huge channel list can't tie up a worker with an unbounded outbound-request loop; a real
+// push targets a handful of provider integrations, not thousands.
+const MAX_PUSH_CHANNELS = 10
+
+export type PushNotificationFetchUtils = {
+ trackedFetch: (args: { url: string; fetchParams: FetchOptions; templateId: string }) => Promise<{
+ fetchError: Error | null
+ fetchResponse: FetchResponse | null
+ fetchDuration: number
+ }>
+ maxFetchTimeoutMs: number
+}
+
+export class PushNotificationService {
+ constructor(
+ private integrationManager: IntegrationManagerService,
+ private encryptedFields: EncryptedFields,
+ private fetchUtils: PushNotificationFetchUtils,
+ private redis: RedisV2 | null
+ ) {}
+
+ @instrumented('push-notification.executeSendPushNotification')
+ async executeSendPushNotification(
+ invocation: CyclotronJobInvocationHogFunction
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
+ if (invocation.queueParameters?.type !== 'sendPushNotification') {
+ throw new Error('Bad invocation')
+ }
+
+ const params = invocation.queueParameters as CyclotronInvocationQueueParametersSendPushNotificationType
+ const result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation, {}, { finished: true })
+ const addLog = createAddLogFunction(result.logs)
+
+ const pushMetric = (metricName: 'push_sent' | 'push_skipped' | 'push_failed'): void => {
+ result.metrics.push({
+ team_id: invocation.teamId,
+ app_source_id: invocation.parentRunId ?? invocation.functionId,
+ instance_id: invocation.state.actionId || invocation.id,
+ metric_kind: 'other',
+ metric_name: metricName,
+ count: 1,
+ })
+ }
+
+ // Fan out to every selected channel here rather than looping sendPushNotification in the hog
+ // template — a hog function only runs one async call per invocation, so a per-channel loop in
+ // hog would only ever deliver to the first channel. Each channel is isolated: one failing must
+ // not abort the others.
+ // Dedupe so duplicate channel entries can't notify the same device twice, and cap the fan-out so a
+ // crafted workflow can't occupy the worker with an unbounded loop.
+ const uniqueIntegrationIds = [...new Set(params.integrationIds)]
+ const integrationIds = uniqueIntegrationIds.slice(0, MAX_PUSH_CHANNELS)
+ if (uniqueIntegrationIds.length > MAX_PUSH_CHANNELS) {
+ addLog(
+ 'warn',
+ `Push notification has ${uniqueIntegrationIds.length} channels; only the first ${MAX_PUSH_CHANNELS} will be delivered.`
+ )
+ }
+
+ let errorCount = 0
+ let successCount = 0
+ let firstError: string | undefined
+ for (const integrationId of integrationIds) {
+ try {
+ const integration = await this.integrationManager.get(integrationId)
+ if (!integration || integration.team_id !== invocation.teamId) {
+ throw new Error('Push notification integration not found')
+ }
+
+ let sent: boolean
+ if (integration.kind === 'firebase') {
+ sent = await this.executeFcm(result, params, integration, invocation)
+ } else if (integration.kind === 'apns') {
+ sent = await this.executeApns(result, params, integration, invocation)
+ } else {
+ throw new Error(`Unsupported push integration kind: ${integration.kind}`)
+ }
+
+ if (sent) {
+ successCount++
+ pushMetric('push_sent')
+ } else {
+ // A channel with no registered device token for this recipient is skipped, not failed.
+ pushMetric('push_skipped')
+ }
+ } catch (error) {
+ errorCount++
+ firstError = firstError ?? error.message
+ addLog('error', error.message)
+ pushMetric('push_failed')
+ }
+ }
+
+ // Retry (by surfacing an error) only when a channel was attempted and failed and nothing was
+ // delivered. A skip (no device token) is not a delivery, so retrying is safe; but once any
+ // channel has delivered we must not retry, or it would re-deliver to that channel.
+ const success = successCount > 0 || errorCount === 0
+ if (!success) {
+ result.error = firstError
+ }
+ // Surface the error to the hog template too, otherwise its failure message renders blank.
+ result.invocation.state.vmState!.stack.push({ success, error: success ? null : (firstError ?? null) })
+
+ return result
+ }
+
+ /** Returns true if a notification was handed off to FCM, false if skipped (no device token). */
+ private async executeFcm(
+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
+ params: CyclotronInvocationQueueParametersSendPushNotificationType,
+ integration: IntegrationType,
+ invocation: CyclotronJobInvocationHogFunction
+ ): Promise<boolean> {
+ const addLog = createAddLogFunction(result.logs)
+ const payload = params.payload
+
+ const projectId = integration.config.project_id
+ const accessToken = integration.sensitive_config.access_token
+ if (!projectId || !accessToken) {
+ throw new Error('Firebase integration is missing project_id or access_token')
+ }
+
+ const personProperties = invocation.state.globals.person?.properties
+ const token = getDevicePushSubscriptionToken(personProperties, projectId, this.encryptedFields)
+
+ if (!token) {
+ addLog('warn', `No active FCM device token found for distinct_id: ${params.distinctId}`)
+ return false
+ }
+
+ const url = `https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`
+ const templateId = result.invocation.hogFunction.template_id ?? 'unknown'
+
+ const fcmMessage = this.buildFcmMessage(token, payload)
+
+ const fetchParams: FetchOptions = {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(fcmMessage),
+ }
+
+ if (params.timeoutMs !== undefined) {
+ fetchParams.timeoutMs = Math.min(params.timeoutMs, this.fetchUtils.maxFetchTimeoutMs)
+ }
+
+ const { fetchError, fetchResponse, fetchDuration } = await this.fetchUtils.trackedFetch({
+ url,
+ fetchParams,
+ templateId,
+ })
+
+ result.invocation.state.timings.push({
+ kind: 'async_function',
+ duration_ms: fetchDuration,
+ })
+
+ let body: unknown = undefined
+ try {
+ body = await fetchResponse?.text()
+ if (typeof body === 'string') {
+ try {
+ body = parseJSON(body)
+ } catch {
+ // Pass through
+ }
+ }
+ } catch (e) {
+ addLog('error', `Failed to parse response body: ${e.message}`)
+ }
+
+ const status = fetchResponse?.status
+
+ if (!fetchResponse || (status && status >= 400)) {
+ addLog(
+ 'error',
+ `FCM send error. Status: ${status ?? '(none)'}. Body: ${typeof body === 'string' ? body : JSON.stringify(body)}. Fetch error: ${fetchError?.message ?? 'none'}`
+ )
+ // A 404 / UNREGISTERED means FCM no longer knows this token (app uninstalled or token rotated).
+ // Prune it and treat the channel as skipped rather than retrying a token that will never work.
+ const fcmErrorCode = (body as any)?.error?.details?.find?.((d: any) => d?.errorCode)?.errorCode
+ if (status === 404 || fcmErrorCode === 'UNREGISTERED') {
+ this.pruneDeviceToken(result, invocation, params.distinctId, projectId, 'fcm')
+ addLog('warn', `Removed unregistered FCM token for distinct_id: ${params.distinctId}`)
+ return false
+ }
+ throw new Error(
+ `Push notification failed with status ${status ?? '(none)'}.${fetchError ? ` Error: ${fetchError.message}.` : ''}`
+ )
+ }
+
+ pushNotificationSentCounter.labels({ platform: 'fcm' }).inc()
+ addLog('info', `Push notification sent via FCM`)
+ return true
+ }
+
+ /** Returns true if a notification was handed off to APNS, false if skipped (no device token). */
+ private async executeApns(
+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
+ params: CyclotronInvocationQueueParametersSendPushNotificationType,
+ integration: IntegrationType,
+ invocation: CyclotronJobInvocationHogFunction
+ ): Promise<boolean> {
+ const addLog = createAddLogFunction(result.logs)
+ const payload = params.payload
+
+ const signingKey = integration.sensitive_config.signing_key
+ const keyId = integration.config.key_id
+ const appleTeamId = integration.config.team_id
+ const bundleId = integration.config.bundle_id
+ if (!signingKey || !keyId || !appleTeamId || !bundleId) {
+ throw new Error('APNS integration is missing required fields: signing_key, key_id, team_id, or bundle_id')
+ }
+
+ const personProperties = invocation.state.globals.person?.properties
+ const token = getDevicePushSubscriptionToken(personProperties, bundleId, this.encryptedFields)
+
+ if (!token) {
+ addLog('warn', `No active APNS device token found for distinct_id: ${params.distinctId}`)
+ return false
+ }
+
+ const jwt = await this.generateApnsJwt(appleTeamId, keyId, signingKey)
+
+ const apnsPayload = this.buildApnsPayload(payload)
+ const apnsHost =
+ integration.config.environment === 'sandbox' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'
+ const url = `https://${apnsHost}/3/device/${token}`
+
+ const headers: Record<string, string> = {
+ Authorization: `bearer ${jwt}`,
+ 'apns-topic': bundleId,
+ 'apns-push-type': 'alert',
+ }
+ if (payload.collapseKey) {
+ headers['apns-collapse-id'] = payload.collapseKey
+ }
+ if (payload.ttlSeconds !== undefined) {
+ headers['apns-expiration'] = String(Math.floor(Date.now() / 1000) + payload.ttlSeconds)
+ }
+ if (payload.apns?.interruptionLevel) {
+ headers['apns-priority'] = payload.apns.interruptionLevel === 'passive' ? '5' : '10'
+ }
+
+ const fetchParams: FetchOptions = {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(apnsPayload),
+ // APNs requires HTTP/2
+ allowH2: true,
+ }
+
+ if (params.timeoutMs !== undefined) {
+ fetchParams.timeoutMs = Math.min(params.timeoutMs, this.fetchUtils.maxFetchTimeoutMs)
+ }
+
+ const templateId = result.invocation.hogFunction.template_id ?? 'unknown'
+
+ const { fetchError, fetchResponse, fetchDuration } = await this.fetchUtils.trackedFetch({
+ url,
+ fetchParams,
+ templateId,
+ })
+
+ result.invocation.state.timings.push({
+ kind: 'async_function',
+ duration_ms: fetchDuration,
+ })
+
+ let body: unknown = undefined
+ try {
+ body = await fetchResponse?.text()
+ if (typeof body === 'string' && body.length > 0) {
+ try {
+ body = parseJSON(body)
+ } catch {
+ // Pass through
+ }
+ }
+ } catch (e) {
+ addLog('error', `Failed to parse response body: ${e.message}`)
+ }
+
+ const status = fetchResponse?.status
+
+ if (!fetchResponse || (status && status >= 400)) {
+ const reason =
+ body && typeof body === 'object' && 'reason' in body ? ` Reason: ${(body as any).reason}.` : ''
+ addLog(
+ 'error',
+ `APNS send error. Status: ${status ?? '(none)'}. Body: ${typeof body === 'string' ? body : JSON.stringify(body)}. Fetch error: ${fetchError?.message ?? 'none'}`
+ )
+ // 410 Unregistered is Apple's signal that the token is dead (app uninstalled). Prune it and
+ // skip rather than retrying. Other 4xx (e.g. BadDeviceToken) can be environment/config issues,
+ // so we don't prune on those to avoid dropping a token that is actually valid.
+ if (status === 410) {
+ this.pruneDeviceToken(result, invocation, params.distinctId, bundleId, 'apns')
+ addLog('warn', `Removed unregistered APNS token for distinct_id: ${params.distinctId}`)
+ return false
+ }
+ throw new Error(
+ `Push notification failed with status ${status ?? '(none)'}.${reason}${fetchError ? ` Error: ${fetchError.message}.` : ''}`
+ )
+ }
+
+ pushNotificationSentCounter.labels({ platform: 'apns' }).inc()
+ addLog('info', `Push notification sent via APNS`)
+ return true
+ }
+
+ private async generateApnsJwt(teamId: string, keyId: string, signingKey: string): Promise<string> {
+ // Key the cache on a fingerprint of the signing-key material, not on the team id / key id — those
+ // come from tenant-controlled integration config, so another team could set matching values to
+ // collide with or poison this shared cache entry. Hashing the signing key makes the key unforgeable
+ // while still letting the fleet reuse one token per signing key.
+ const keyFingerprint = createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')
+ const cacheKey = `${APNS_JWT_CACHE_PREFIX}${keyFingerprint}`
+
+ const cached = await this.redis?.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>
+ client.get(cacheKey)
+ )
+ if (cached) {
+ return cached
+ }
+
+ const header = Buffer.from(JSON.stringify({ alg: 'ES256', kid: keyId })).toString('base64url')
+ const now = Math.floor(Date.now() / 1000)
+ const claims = Buffer.from(JSON.stringify({ iss: teamId, iat: now })).toString('base64url')
+ const signingInput = `${header}.${claims}`
+ const sign = createSign('SHA256')
+ sign.update(signingInput)
+ const signature = sign.sign({ key: signingKey, dsaEncoding: 'ieee-p1363' }, 'base64url')
+ const jwt = `${signingInput}.${signature}`
+
+ await this.redis?.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>
+ client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)
+ )
+ return jwt
+ }
+
+ private buildApnsPayload(payload: PushNotificationPayloadType): Record<string, unknown> {
+ const alert: Record<string, unknown> = { title: payload.title }
+ if (payload.body) {
+ alert.body = payload.body
+ }
+ if (payload.apns?.subtitle) {
+ alert.subtitle = payload.apns.subtitle
+ }
+
+ const aps: Record<string, unknown> = { alert }
+
+ if (payload.apns) {
+ if (payload.apns.sound) {
+ aps.sound = payload.apns.sound
+ }
+ if (payload.apns.badge !== undefined) {
+ aps.badge = payload.apns.badge
+ }
+ if (payload.apns.category) {
+ aps.category = payload.apns.category
+ }
+ if (payload.apns.threadId) {
+ aps['thread-id'] = payload.apns.threadId
+ }
+ if (payload.apns.interruptionLevel) {
+ aps['interruption-level'] = payload.apns.interruptionLevel
+ }
+ if (payload.apns.relevanceScore !== undefined) {
+ aps['relevance-score'] = payload.apns.relevanceScore
+ }
+ if (payload.apns.contentAvailable) {
+ aps['content-available'] = 1
+ }
+ if (payload.apns.mutableContent || payload.image) {
+ aps['mutable-content'] = 1
+ }
+ if (payload.apns.targetContentId) {
+ aps['target-content-id'] = payload.apns.targetContentId
+ }
+ } else if (payload.image) {
+ aps['mutable-content'] = 1
+ }
+
+ // Spread user data first so the reserved `aps` and `image_url` keys always win — a custom data
+ // key named `aps` must not overwrite the notification payload.
+ const result: Record<string, unknown> = { ...(payload.data ?? {}), aps }
+
+ if (payload.image) {
+ result['image_url'] = payload.image
+ }
+
+ return result
+ }
+
+ // Remove a device token the provider reported as no longer registered. Emitted as a $unset person
+ // update (flushed with the invocation's captured events) so we stop retrying dead tokens and don't
+ // accumulate stale ones on the person.
+ private pruneDeviceToken(
+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
+ invocation: CyclotronJobInvocationHogFunction,
+ distinctId: string,
+ appIdentifier: string,
+ platform: 'fcm' | 'apns'
+ ): void {
+ result.capturedPostHogEvents.push({
+ team_id: invocation.teamId,
+ event: '$set',
+ distinct_id: distinctId,
+ timestamp: new Date().toISOString(),
+ properties: { $unset: [`$device_push_subscription_${appIdentifier}`] },
+ })
+ pushNotificationTokenPrunedCounter.labels({ platform }).inc()
+ }
+
+ private buildFcmMessage(token: string, payload: PushNotificationPayloadType): Record<string, unknown> {
+ const notification: Record<string, string> = { title: payload.title }
+ if (payload.body) {
+ notification.body = payload.body
+ }
+ if (payload.image) {
+ notification.image = payload.image
+ }
+
+ const message: Record<string, unknown> = {
+ token,
+ notification,
+ }
+
+ if (payload.data) {
+ message.data = payload.data
+ }
+
+ // Android-specific config
+ if (payload.android || payload.collapseKey || payload.ttlSeconds !== undefined) {
+ const android: Record<string, unknown> = {}
+ if (payload.collapseKey) {
+ android.collapse_key = payload.collapseKey
+ }
+ if (payload.ttlSeconds !== undefined) {
+ android.ttl = `${payload.ttlSeconds}s`
+ }
+ if (payload.android) {
+ if (payload.android.priority) {
+ android.priority = payload.android.priority.toUpperCase()
+ }
+ const androidNotification: Record<string, string> = {}
+ if (payload.android.channelId) {
+ androidNotification.channel_id = payload.android.channelId
+ }
+ if (payload.android.sound) {
+ androidNotification.sound = payload.android.sound
+ }
+ if (payload.android.tag) {
+ androidNotification.tag = payload.android.tag
+ }
+ if (payload.android.icon) {
+ androidNotification.icon = payload.android.icon
+ }
+ if (payload.android.color) {
+ androidNotification.color = payload.android.color
+ }
+ if (payload.android.clickAction) {
+ androidNotification.click_action = payload.android.clickAction
+ }
+ if (Object.keys(androidNotification).length > 0) {
+ android.notification = androidNotification
+ }
+ }
+ message.android = android
+ }
+
+ // APNS overrides (for iOS devices via FCM)
+ if (payload.apns) {
+ const aps: Record<string, unknown> = {}
+ if (payload.apns.sound) {
+ aps.sound = payload.apns.sound
+ }
+ if (payload.apns.badge !== undefined) {
+ aps.badge = payload.apns.badge
+ }
+ if (payload.apns.category) {
+ aps.category = payload.apns.category
+ }
+ if (payload.apns.threadId) {
+ aps['thread-id'] = payload.apns.threadId
+ }
+ if (payload.apns.interruptionLevel) {
+ aps['interruption-level'] = payload.apns.interruptionLevel
+ }
+ if (payload.apns.relevanceScore !== undefined) {
+ aps['relevance-score'] = payload.apns.relevanceScore
+ }
+ if (payload.apns.subtitle) {
+ // FCM's message.notification has no `subtitle`. For an iOS device delivered via FCM the
+ // subtitle must live in the APNS alert; include title/body so overriding the alert keeps them.
+ aps.alert = {
+ title: payload.title,
+ ...(payload.body ? { body: payload.body } : {}),
+ subtitle: payload.apns.subtitle,
+ }
+ }
+ if (payload.apns.mutableContent) {
+ aps['mutable-content'] = 1
+ }
+ if (payload.apns.targetContentId) {
+ aps['target-content-id'] = payload.apns.targetContentId
+ }
+
+ message.apns = {
+ payload: { aps },
+ }
+
+ // Set collapse ID via APNS header if collapseKey is set
+ if (payload.collapseKey) {
+ ;(message.apns as Record<string, unknown>).headers = {
+ 'apns-collapse-id': payload.collapseKey,
+ }
+ }
+ if (payload.ttlSeconds !== undefined) {
+ const headers = ((message.apns as Record<string, unknown>).headers as Record<string, string>) ?? {}
+ headers['apns-expiration'] = String(Math.floor(Date.now() / 1000) + payload.ttlSeconds)
+ ;(message.apns as Record<string, unknown>).headers = headers
+ }
+ }
+
+ return { message }
+ }
+}
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 d17a343aabbf..28b929577849 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
@@ -63,7 +63,7 @@ describe('RecipientPreferencesService', () => {
})
const createFunctionStepInvocation = (
- action: Extract<HogFlowAction, { type: 'function' | 'function_email' | 'function_sms' }>
+ action: Extract<HogFlowAction, { type: 'function' | 'function_email' | 'function_sms' | 'function_push' }>
): CyclotronJobInvocationHogFunction => {
const hogFlow = new FixtureHogFlowBuilder()
.withTeamId(team.id)
@@ -443,6 +443,87 @@ describe('RecipientPreferencesService', () => {
})
})
+ describe('for push actions', () => {
+ const createPushAction = (
+ categoryId: string,
+ categoryType?: 'marketing' | 'transactional'
+ ): Extract<HogFlowAction, { type: 'function_push' }> => ({
+ id: 'push',
+ name: 'Send push',
+ description: 'Send a push notification to the recipient',
+ type: 'function_push',
+ filters: null,
+ config: {
+ template_id: 'template-native-push',
+ message_category_id: categoryId,
+ message_category_type: categoryType,
+ inputs: {},
+ },
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ })
+
+ // Push is keyed by the recipient's distinct_id (from the triggering event), not an email/phone
+ // 'to' field — that is the identifier the device token was registered under.
+ it.each([
+ ['opted out', 'OPTED_OUT', true],
+ ['opted in', 'OPTED_IN', false],
+ ] as const)('marketing push to a recipient %s of the category → skip=%s', async (_label, status, skip) => {
+ const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')
+ const invocation = createFunctionStepInvocation(action)
+ const recipient = createRecipient('distinct_id', {
+ '123e4567-e89b-12d3-a456-426614174000': status,
+ })
+
+ mockRecipientsManagerGet.mockResolvedValue(recipient)
+ mockRecipientsManagerGetPreference.mockReturnValue(status)
+ mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')
+
+ const result = await service.shouldSkipAction(invocation, action)
+
+ expect(result).toBe(skip)
+ expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
+ teamId: team.id,
+ identifier: 'distinct_id',
+ })
+ })
+
+ it('should return false for a transactional push without checking preferences', async () => {
+ const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'transactional')
+ const invocation = createFunctionStepInvocation(action)
+
+ const result = await service.shouldSkipAction(invocation, action)
+
+ expect(result).toBe(false)
+ expect(mockRecipientsManagerGet).not.toHaveBeenCalled()
+ })
+
+ it('keys the opt-out on the delivered-to person, not the triggering event', async () => {
+ // Delivery reads the device token from globals.person, so the opt-out must check that same
+ // person even when the triggering event distinct_id differs (e.g. a configured inputs.distinctId).
+ const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')
+ const invocation = createFunctionStepInvocation(action)
+ invocation.state.globals.person!.distinct_id = 'delivered-person'
+ invocation.state.globals.event!.distinct_id = 'trigger-person'
+
+ mockRecipientsManagerGet.mockResolvedValue(
+ createRecipient('delivered-person', {
+ '123e4567-e89b-12d3-a456-426614174000': 'OPTED_OUT',
+ })
+ )
+ mockRecipientsManagerGetPreference.mockReturnValue('OPTED_OUT')
+ mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')
+
+ const result = await service.shouldSkipAction(invocation, action)
+
+ expect(result).toBe(true)
+ expect(mockRecipientsManagerGet).toHaveBeenCalledWith({
+ teamId: team.id,
+ identifier: 'delivered-person',
+ })
+ })
+ })
+
describe('for other action types', () => {
it('should return false for function actions', async () => {
const action: Extract<HogFlowAction, { type: 'function' }> = {
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
index dcdc2478fe9e..a0f07090d305 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
@@ -4,7 +4,7 @@ import { logger } from '~/common/utils/logger'
import { CyclotronJobInvocationHogFunction } from '../../types'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
-type MessageFunctionActionType = 'function_email' | 'function_sms'
+type MessageFunctionActionType = 'function_email' | 'function_sms' | 'function_push'
type MessageAction = Extract<HogFlowAction, { type: MessageFunctionActionType }>
@@ -29,7 +29,7 @@ export class RecipientPreferencesService {
}
private isSubjectToRecipientPreferences(action: HogFlowAction): action is MessageAction {
- return ['function_email', 'function_sms'].includes(action.type)
+ return ['function_email', 'function_sms', 'function_push'].includes(action.type)
}
private async isRecipientOptedOutOfAction(
@@ -42,6 +42,13 @@ export class RecipientPreferencesService {
identifier = invocation.state.globals.inputs?.to_number
} else if (action.type === 'function_email') {
identifier = invocation.state.globals.inputs?.email?.to?.email
+ } else if (action.type === 'function_push') {
+ // Push has no email/phone "to" field. Delivery reads the device token from the invocation's
+ // person (globals.person.properties), so key the opt-out on that same person's distinct_id —
+ // not the configurable inputs.distinctId or the triggering event — so the recipient we check
+ // is always the recipient we deliver to. Fall back to the event distinct_id when the person
+ // has no resolved one.
+ identifier = invocation.state.globals.person?.distinct_id ?? invocation.state.globals.event?.distinct_id
}
if (!identifier) {
diff --git a/nodejs/src/cdp/templates/_destinations/firebase_push/firebase_push.template.ts b/nodejs/src/cdp/templates/_destinations/firebase_push/firebase_push.template.ts
deleted file mode 100644
index 6e2b0f356c82..000000000000
--- a/nodejs/src/cdp/templates/_destinations/firebase_push/firebase_push.template.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { HogFunctionTemplate } from '~/cdp/types'
-
-export const template: HogFunctionTemplate = {
- free: false,
- status: 'hidden',
- type: 'destination',
- id: 'template-firebase-push',
- name: 'Firebase Push Notification',
- description: 'Send push notifications to mobile devices via Firebase Cloud Messaging (FCM)',
- icon_url: '/static/services/firebase.png',
- category: ['Communication'],
- code_language: 'hog',
- code: `
-let fcmToken := inputs.fcm_token
-let title := inputs.title
-let body := inputs.body
-let projectId := inputs.firebase_account.project_id
-
-if (not fcmToken) {
- throw Error('FCM token is required')
-}
-
-if (not title) {
- throw Error('Notification title is required')
-}
-
-let url := f'https://fcm.googleapis.com/v1/projects/{projectId}/messages:send'
-
-let message := {
- 'message': {
- 'token': fcmToken,
- 'notification': {
- 'title': title,
- 'body': body
- }
- }
-}
-
-if (inputs.data) {
- message.message.data := inputs.data
-}
-
-let payload := {
- 'method': 'POST',
- 'headers': {
- 'Authorization': f'Bearer {inputs.firebase_account.access_token}',
- 'Content-Type': 'application/json'
- },
- 'body': message
-}
-
-if (inputs.debug) {
- print('Sending push notification', url, payload)
-}
-
-let res := fetch(url, payload)
-
-if (res.status < 200 or res.status >= 300) {
- throw Error(f'Failed to send push notification via FCM: {res.status} {res.body}')
-}
-
-if (inputs.debug) {
- print('Push notification sent', res)
-}
-`,
- inputs_schema: [
- {
- key: 'firebase_account',
- type: 'integration',
- integration: 'firebase',
- label: 'Firebase project',
- requiredScopes: 'placeholder',
- secret: false,
- hidden: false,
- required: true,
- },
- {
- key: 'fcm_token',
- type: 'string',
- label: 'FCM device token',
- secret: true,
- required: true,
- description:
- 'The Firebase Cloud Messaging token for the target device. In a future version, this will be automatically looked up from registered devices.',
- default: '',
- templating: 'liquid',
- },
- {
- key: 'title',
- type: 'string',
- label: 'Notification title',
- secret: false,
- required: true,
- description: 'The title of the push notification',
- default: 'Notification from {{ event.event }}',
- templating: 'liquid',
- },
- {
- key: 'body',
- type: 'string',
- label: 'Notification body',
- secret: false,
- required: false,
- description: 'The body text of the push notification',
- default: '',
- templating: 'liquid',
- },
- {
- key: 'data',
- type: 'json',
- label: 'Custom data payload',
- secret: false,
- required: false,
- description: 'Optional custom key-value data to send with the notification (for app handling)',
- default: {},
- },
- {
- key: 'debug',
- type: 'boolean',
- label: 'Log responses',
- description: 'Logs the FCM responses for debugging.',
- secret: false,
- required: false,
- default: false,
- },
- ],
-}
diff --git a/nodejs/src/cdp/templates/_destinations/push/push.template.ts b/nodejs/src/cdp/templates/_destinations/push/push.template.ts
new file mode 100644
index 000000000000..86e19645d8c4
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/push/push.template.ts
@@ -0,0 +1,250 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+export const template: HogFunctionTemplate = {
+ free: false,
+ status: 'hidden',
+ type: 'destination',
+ id: 'template-native-push',
+ name: 'Push notification',
+ description: 'Send push notifications to mobile devices via FCM or APNS',
+ icon_url: '/static/posthog-icon.svg',
+ category: ['Communication'],
+ code_language: 'hog',
+ code: `
+let payload := {
+ 'title': inputs.title,
+ 'body': inputs.body
+}
+
+if (inputs.image) payload.image := inputs.image
+if (inputs.data) payload.data := inputs.data
+if (inputs.collapseKey) payload.collapseKey := inputs.collapseKey
+if (inputs.ttlSeconds) payload.ttlSeconds := inputs.ttlSeconds
+
+// Android-specific overrides
+let android := {}
+if (inputs.android_priority) android.priority := inputs.android_priority
+if (inputs.android_channelId) android.channelId := inputs.android_channelId
+if (inputs.android_sound) android.sound := inputs.android_sound
+if (inputs.android_tag) android.tag := inputs.android_tag
+if (inputs.android_icon) android.icon := inputs.android_icon
+if (inputs.android_color) android.color := inputs.android_color
+if (inputs.android_clickAction) android.clickAction := inputs.android_clickAction
+if (length(keys(android)) > 0) payload.android := android
+
+// iOS (APNS) overrides
+let apns := {}
+if (inputs.ios_sound) apns.sound := inputs.ios_sound
+if (inputs.ios_badge != null) apns.badge := inputs.ios_badge
+if (inputs.ios_category) apns.category := inputs.ios_category
+if (inputs.ios_threadId) apns.threadId := inputs.ios_threadId
+if (inputs.ios_interruptionLevel) apns.interruptionLevel := inputs.ios_interruptionLevel
+if (inputs.ios_subtitle) apns.subtitle := inputs.ios_subtitle
+if (inputs.ios_mutableContent) apns.mutableContent := inputs.ios_mutableContent
+if (length(keys(apns)) > 0) payload.apns := apns
+
+if (not inputs.channels or length(inputs.channels) == 0) {
+ throw Error('No push channel configured. Select at least one channel.')
+}
+
+// Fan out to every selected channel inside the async function: a hog function only runs one async
+// call per invocation, so pass all channel integration ids in a single call. The recipient only has a
+// device token for the platform they registered, so other channels record push_skipped.
+let res := sendPushNotification({
+ 'integrationIds': arrayMap(channel -> channel.$integration_id, inputs.channels),
+ 'distinctId': inputs.distinctId,
+ 'payload': payload
+})
+if (not res.success) {
+ throw Error(f'Failed to send push notification: {res.error}')
+}
+`,
+ inputs_schema: [
+ {
+ key: 'distinctId',
+ type: 'string',
+ label: 'Distinct ID',
+ secret: false,
+ required: true,
+ description: 'Distinct ID of the person to send the notification to.',
+ default: '{event.distinct_id}',
+ },
+ {
+ key: 'channels',
+ type: 'integration_multi',
+ integration: 'firebase,apns',
+ label: 'Push channels',
+ secret: false,
+ required: true,
+ description:
+ 'Which channels to send through. Each recipient gets the notification on the device they registered.',
+ },
+ {
+ key: 'title',
+ type: 'string',
+ label: 'Notification title',
+ secret: false,
+ required: true,
+ description: 'The title of the push notification.',
+ default: 'Notification from {event.event}',
+ },
+ {
+ key: 'body',
+ type: 'string',
+ label: 'Notification body',
+ secret: false,
+ required: false,
+ description: 'The body text of the push notification.',
+ default: '',
+ templating: 'liquid',
+ },
+ {
+ key: 'image',
+ type: 'string',
+ label: 'Image URL',
+ secret: false,
+ required: false,
+ description: 'URL of an image to display in the notification.',
+ },
+ {
+ key: 'data',
+ type: 'json',
+ label: 'Custom data payload',
+ secret: false,
+ required: false,
+ description: 'Custom key-value data delivered to the app (values must be strings for FCM).',
+ default: {},
+ },
+ {
+ key: 'collapseKey',
+ type: 'string',
+ label: 'Collapse key',
+ secret: false,
+ required: false,
+ description:
+ 'Identifier for grouping notifications. Only the latest notification with a given key is shown.',
+ },
+ {
+ key: 'ttlSeconds',
+ type: 'number',
+ label: 'TTL (seconds)',
+ secret: false,
+ required: false,
+ description: 'Time-to-live in seconds. How long FCM stores the message if the device is offline.',
+ },
+ // Android-specific options (used when delivering via Firebase)
+ {
+ key: 'android_priority',
+ type: 'choice',
+ label: 'Android priority',
+ choices: [
+ { value: 'normal', label: 'Normal' },
+ { value: 'high', label: 'High' },
+ ],
+ description: 'Message delivery priority. High priority wakes the device immediately.',
+ required: false,
+ },
+ {
+ key: 'android_channelId',
+ type: 'string',
+ label: 'Android channel ID',
+ description: 'Android notification channel ID (Android 8.0+).',
+ required: false,
+ },
+ {
+ key: 'android_sound',
+ type: 'string',
+ label: 'Android sound',
+ description: 'Sound to play on Android. Use "default" for the system default.',
+ required: false,
+ },
+ {
+ key: 'android_tag',
+ type: 'string',
+ label: 'Android tag',
+ description: 'Notification tag. Replaces an existing notification with the same tag.',
+ required: false,
+ },
+ {
+ key: 'android_icon',
+ type: 'string',
+ label: 'Android icon',
+ description: 'Notification icon resource name.',
+ required: false,
+ },
+ {
+ key: 'android_color',
+ type: 'string',
+ label: 'Android color',
+ description: 'Notification icon color in #RRGGBB format.',
+ required: false,
+ },
+ {
+ key: 'android_clickAction',
+ type: 'string',
+ label: 'Android click action',
+ description: 'Activity to launch when the notification is tapped.',
+ required: false,
+ },
+ // iOS-specific options (used when delivering via Apple Push, or to iOS devices via Firebase)
+ {
+ key: 'ios_sound',
+ type: 'string',
+ label: 'iOS sound',
+ description: 'Sound file name or "default" for the system default.',
+ required: false,
+ },
+ {
+ key: 'ios_badge',
+ type: 'number',
+ label: 'iOS badge count',
+ description: 'App icon badge number.',
+ required: false,
+ },
+ {
+ key: 'ios_subtitle',
+ type: 'string',
+ label: 'iOS subtitle',
+ description: 'Additional text below the title.',
+ required: false,
+ },
+ {
+ key: 'ios_category',
+ type: 'string',
+ label: 'iOS category',
+ description: 'Notification category for actionable notifications.',
+ required: false,
+ },
+ {
+ key: 'ios_threadId',
+ type: 'string',
+ label: 'iOS thread ID',
+ description: 'Identifier for grouping notifications in the notification center.',
+ required: false,
+ },
+ {
+ key: 'ios_interruptionLevel',
+ type: 'choice',
+ label: 'iOS interruption level',
+ choices: [
+ { value: 'passive', label: 'Passive' },
+ { value: 'active', label: 'Active' },
+ { value: 'time-sensitive', label: 'Time sensitive' },
+ { value: 'critical', label: 'Critical' },
+ ],
+ description: 'How prominently the notification is presented (iOS 15+).',
+ required: false,
+ },
+ {
+ key: 'ios_mutableContent',
+ type: 'boolean',
+ label: 'iOS mutable content',
+ description: 'Allow a notification service extension to modify the content before display.',
+ required: false,
+ default: false,
+ },
+ ],
+ // Providers are now top-level inputs (fcm_provider / apns_provider), so this step renders as a
+ // flat form like email — no mappings UI. Explicitly empty to clear any previously-synced mappings.
+ mapping_templates: [],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index 16b6925f4789..f8b59806d8f7 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -7,7 +7,6 @@ import { template as clickupTemplate } from './_destinations/clickup/clickup.tem
import { template as closeTemplate } from './_destinations/close/close.template'
import { allComingSoonTemplates } from './_destinations/coming-soon/coming-soon-destinations.template'
import { template as emailTemplate } from './_destinations/email/email.template'
-import { template as firebasePushTemplate } from './_destinations/firebase_push/firebase_push.template'
import { template as githubTemplate } from './_destinations/github/github.template'
import { template as gitlabTemplate } from './_destinations/gitlab/gitlab.template'
import { template as googleTagManagerTemplate } from './_destinations/google-tag-manager/google-tag-manager.template'
@@ -30,6 +29,7 @@ import { template as posthogUpdateAccountPropertyTemplate } from './_destination
import { template as posthogUpdateAccountRelationshipsTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account-relationships.template'
import { template as posthogUpdateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account.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'
import { template as snapchatAdsTemplate } from './_destinations/snapchat_ads/snapchat.template'
import { template as tiktokAdsTemplate } from './_destinations/tiktok_ads/tiktok.template'
@@ -71,7 +71,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
googleSheetsTemplate,
googleTagManagerTemplate,
emailTemplate,
- firebasePushTemplate,
+ pushTemplate,
clickupTemplate,
posthogCaptureTemplate,
posthogGroupIdentifyTemplate,
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index 4a443039969f..8b6e12ed4235 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -194,7 +194,8 @@ export class TemplateTester {
private createHogExecutor(): HogExecutorService {
const config = this.mockHub
- const hogInputsService = new HogInputsService(undefined as any, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
+ const hogInputsService = new HogInputsService(undefined as any, recipientTokensService, undefined as any)
const emailService = new EmailService(
{
sesAccessKeyId: config.SES_ACCESS_KEY_ID,
@@ -208,7 +209,6 @@ export class TemplateTester {
config.SITE_URL,
new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
)
- const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
return new HogExecutorService(
{
hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
@@ -220,7 +220,8 @@ export class TemplateTester {
{ teamManager: this.mockTeamManager as any, siteUrl: config.SITE_URL },
hogInputsService,
emailService,
- recipientTokensService
+ recipientTokensService,
+ undefined as any
)
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index a0821fe0ff43..a605b2fa5453 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -240,6 +240,9 @@ export type MinimalAppMetric = {
| 'email_blocked'
| 'email_spam'
| 'email_unsubscribed'
+ | 'push_sent'
+ | 'push_failed'
+ | 'push_skipped'
| 'quota_limited'
| 'conversion'
count: number
@@ -400,12 +403,14 @@ export type HogFunctionInputSchemaType = {
| 'choice'
| 'json'
| 'integration'
+ | 'integration_multi'
| 'integration_field'
| 'email'
| 'native_email'
| 'posthog_assignee'
| 'posthog_ticket_tags'
| 'posthog_business_hours'
+ | 'push_subscription'
| 'non_failure_status_codes'
| 'customer_analytics_account_properties'
| 'customer_analytics_account_relationships'
@@ -423,6 +428,7 @@ export type HogFunctionInputSchemaType = {
integration_key?: string
requires_field?: string
integration_field?: string
+ platform?: 'android' | 'ios'
requiredScopes?: string
/**
* templating: true indicates the field supports templating. Alternatively
@@ -511,7 +517,7 @@ export type DBHogFunctionTemplate = {
export type IntegrationType = {
id: number
team_id: number
- kind: 'slack' | 'email' | 'oauth'
+ kind: 'slack' | 'email' | 'oauth' | 'firebase' | 'apns'
config: Record<string, any>
sensitive_config: Record<string, any>
}
diff --git a/nodejs/src/cdp/utils/push-subscription-utils.test.ts b/nodejs/src/cdp/utils/push-subscription-utils.test.ts
new file mode 100644
index 000000000000..a1ef5321b870
--- /dev/null
+++ b/nodejs/src/cdp/utils/push-subscription-utils.test.ts
@@ -0,0 +1,47 @@
+import { EncryptedFields } from './encryption-utils'
+import { getDevicePushSubscriptionToken } from './push-subscription-utils'
+
+describe('getDevicePushSubscriptionToken', () => {
+ const encryptedFields = new EncryptedFields('01234567890123456789012345678901')
+
+ it('returns null when person properties are undefined', () => {
+ expect(getDevicePushSubscriptionToken(undefined, 'my-project', encryptedFields)).toBeNull()
+ })
+
+ it('returns null when the property is missing', () => {
+ expect(getDevicePushSubscriptionToken({}, 'my-project', encryptedFields)).toBeNull()
+ })
+
+ it('returns null when the property value is not a string', () => {
+ expect(
+ getDevicePushSubscriptionToken({ $device_push_subscription_my_project: 123 }, 'my_project', encryptedFields)
+ ).toBeNull()
+ })
+
+ it('decrypts and returns the token for the matching app identifier', () => {
+ const token = 'device-token-abc123'
+ const encrypted = encryptedFields.encrypt(token)
+ const properties = {
+ [`$device_push_subscription_my-project`]: encrypted,
+ }
+
+ expect(getDevicePushSubscriptionToken(properties, 'my-project', encryptedFields)).toBe(token)
+ })
+
+ it('returns null for a non-matching app identifier', () => {
+ const encrypted = encryptedFields.encrypt('device-token-abc123')
+ const properties = {
+ $device_push_subscription_other_project: encrypted,
+ }
+
+ expect(getDevicePushSubscriptionToken(properties, 'my-project', encryptedFields)).toBeNull()
+ })
+
+ it('returns null when the stored value fails to decrypt (a forged plaintext token is rejected)', () => {
+ const properties = {
+ [`$device_push_subscription_my-project`]: 'not-encrypted-value',
+ }
+
+ expect(getDevicePushSubscriptionToken(properties, 'my-project', encryptedFields)).toBeNull()
+ })
+})
diff --git a/nodejs/src/cdp/utils/push-subscription-utils.ts b/nodejs/src/cdp/utils/push-subscription-utils.ts
new file mode 100644
index 000000000000..40d0fda53eb2
--- /dev/null
+++ b/nodejs/src/cdp/utils/push-subscription-utils.ts
@@ -0,0 +1,27 @@
+import { EncryptedFields } from './encryption-utils'
+
+/**
+ * Extract the device token from the $device_push_subscription_<appIdentifier> person property.
+ *
+ * The property value is the encrypted device token.
+ * Returns the decrypted token, or null if the property is missing or fails to decrypt.
+ */
+export function getDevicePushSubscriptionToken(
+ personProperties: Record<string, any> | undefined,
+ appIdentifier: string,
+ encryptedFields: EncryptedFields
+): string | null {
+ const value = personProperties?.[`$device_push_subscription_${appIdentifier}`]
+ if (!value || typeof value !== 'string') {
+ return null
+ }
+
+ // Require successful decryption. The subscription endpoint always stores this token encrypted, so a
+ // value that fails to decrypt was forged directly onto the person property via a plain `$set` capture
+ // event (a raw token). Ignore it rather than delivering to an unverified device.
+ try {
+ return encryptedFields.decrypt(value) ?? null
+ } catch {
+ return null
+ }
+}
diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.ts
index 4105ac7099e7..f25ce5b5cec0 100644
--- a/nodejs/src/common/utils/request.ts
+++ b/nodejs/src/common/utils/request.ts
@@ -48,6 +48,7 @@ export type FetchOptions = {
headers?: HeadersInit
body?: string | Buffer
timeoutMs?: number
+ allowH2?: boolean
}
export type FetchResponse = {
@@ -278,6 +279,19 @@ function makeSecureDispatcher(): Dispatcher {
}
const sharedSecureAgent = makeSecureDispatcher()
+// Unlike `makeSecureDispatcher`, this agent deliberately skips the ProxyAgent branch: CDP workers don't
+// set the proxy env vars, and SSRF stays covered via `httpStaticLookup`. If CDP egress ever moves behind
+// the proxy (see #49170), swap this for a `ProxyAgent` — undici's `ProxyAgent` supports `allowH2` — so
+// H2 traffic (e.g. APNs) doesn't silently keep going direct.
+const sharedSecureH2Agent = new Agent({
+ keepAliveTimeout: Number(requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS),
+ connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
+ allowH2: true,
+ connect: {
+ lookup: httpStaticLookup,
+ timeout: requestConfig.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS,
+ },
+})
const sharedInsecureAgent = new InsecureAgent()
/**
@@ -371,7 +385,8 @@ export async function fetch(url: string, options: FetchOptions = {}): Promise<Fe
validateHostnameIPLiteral(parsed.hostname, !isProdEnv())
inflightExternalRequests.inc()
try {
- return await _fetch(url, options, sharedSecureAgent)
+ const dispatcher = options.allowH2 ? sharedSecureH2Agent : sharedSecureAgent
+ return await _fetch(url, options, dispatcher)
} finally {
inflightExternalRequests.dec()
}
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 0b22ac7629d2..f5ace2d8d0b0 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -50,6 +50,7 @@ from posthog.models.integration import (
GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,
SLACK_INTEGRATION_KINDS,
AnthropicIntegration,
+ ApplePushIntegration,
AwsS3Integration,
AwsS3RoleBasedIntegration,
AzureBlobIntegration,
@@ -432,10 +433,15 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
return instance
elif validated_data["kind"] == "firebase":
+ # Support both file upload and JSON config
key_file = request.FILES.get("key")
- if not key_file:
- raise ValidationError("Firebase service account key file not provided")
- key_info = json.loads(key_file.read().decode("utf-8"))
+ if key_file:
+ key_info = json.loads(key_file.read().decode("utf-8"))
+ else:
+ config = validated_data.get("config", {})
+ key_info = config.get("key_info")
+ if not key_info:
+ raise ValidationError("Firebase service account key must be provided")
instance = FirebaseIntegration.integration_from_key(key_info, team_id, request.user)
return instance
@@ -632,6 +638,25 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
raise ValidationError(str(e))
return instance
+ elif validated_data["kind"] == "apns":
+ config = validated_data.get("config", {})
+ signing_key = config.get("signing_key")
+ key_id = config.get("key_id")
+ team_id_apple = config.get("team_id_apple")
+ bundle_id = config.get("bundle_id")
+ environment = config.get("environment", "production")
+
+ instance = ApplePushIntegration.integration_from_key(
+ signing_key=signing_key,
+ key_id=key_id,
+ team_id_apple=team_id_apple,
+ bundle_id=bundle_id,
+ team_id=team_id,
+ created_by=request.user,
+ environment=environment,
+ )
+ return instance
+
elif validated_data["kind"] == "aws-s3":
config = validated_data.get("config", {})
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index 86163436b5d7..2cc79a8b3705 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -240,6 +240,7 @@ class InputsSchemaItemSerializer(serializers.Serializer):
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -336,6 +337,9 @@ class InputsItemSerializer(serializers.Serializer):
elif item_type == "integration":
if not isinstance(value, int):
raise serializers.ValidationError({"input": f"Value must be an Integration ID."})
+ elif item_type == "integration_multi":
+ if not isinstance(value, list) or not all(isinstance(v, int) and not isinstance(v, bool) for v in value):
+ raise serializers.ValidationError({"input": "Value must be a list of Integration IDs."})
elif item_type == "email" or item_type == "native_email":
if not isinstance(value, dict):
raise serializers.ValidationError({"input": f"Value must be an email object."})
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 0272ad140878..7362ec8df15b 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -1933,6 +1933,7 @@ class ApplePushIntegration:
- team_id: Apple Developer Team ID
- bundle_id: App bundle identifier (e.g. com.example.app)
- key_id: The Key ID for the .p8 signing key
+ - environment: "production" or "sandbox" (defaults to "production")
sensitive_config stores:
- signing_key: The .p8 signing key contents
@@ -1954,10 +1955,14 @@ class ApplePushIntegration:
bundle_id: str,
team_id: int,
created_by: User | None = None,
+ environment: str = "production",
) -> "Integration":
if not all([signing_key, key_id, team_id_apple, bundle_id]):
raise ValidationError("All APNS fields are required: signing_key, key_id, team_id_apple, bundle_id")
+ if environment not in ("production", "sandbox"):
+ raise ValidationError("APNS environment must be 'production' or 'sandbox'")
+
integration, created = Integration.objects.update_or_create(
team_id=team_id,
kind="apns",
@@ -1967,6 +1972,7 @@ class ApplePushIntegration:
"team_id": team_id_apple,
"bundle_id": bundle_id,
"key_id": key_id,
+ "environment": environment,
},
"sensitive_config": {
"signing_key": signing_key,
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index d49f4594b34d..915b13970206 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2339,6 +2339,7 @@ class IntegrationKind(StrEnum):
CUSTOMERIO_APP = "customerio-app"
CUSTOMERIO_WEBHOOK = "customerio-webhook"
CUSTOMERIO_TRACK = "customerio-track"
+ APNS = "apns"
POSTGRESQL = "postgresql"
AWS_S3 = "aws-s3"
S3_COMPATIBLE = "s3-compatible"
diff --git a/posthog/urls.py b/posthog/urls.py
index 323fff62d54e..4608bf010c8a 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -52,6 +52,7 @@ from products.demo.backend.facade.api import demo_route
from products.early_access_features.backend.api import early_access_features
from products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook
from products.messaging.backend.api.customerio_webhook import CustomerIOWebhookView
+from products.messaging.backend.api.push_subscriptions import push_subscriptions
from products.notebooks.backend.facade.sql_v2 import (
notebook_sql_v2_callback,
notebook_sql_v2_data_plane,
@@ -431,6 +432,7 @@ urlpatterns = [
opt_slash_path("api/user/redirect_to_website", user.redirect_to_website),
opt_slash_path("api/early_access_features", early_access_features),
opt_slash_path("api/web_experiments", web_experiments),
+ opt_slash_path("api/push_subscriptions", push_subscriptions),
opt_slash_path("api/product_tours", product_tours),
re_path(r"^external_surveys/(?P<survey_id>[^/]+)/?$", public_survey_page),
opt_slash_path("api/signup/precheck", signup.SignupEmailPrecheckViewset.as_view()),
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index c63f3fde1cc2..5ff63ef05ef7 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -262,6 +262,7 @@ export const HogFunctionTypeEnumApi = {
* * `choice` - choice
* * `json` - json
* * `integration` - integration
+ * * `integration_multi` - integration_multi
* * `integration_field` - integration_field
* * `email` - email
* * `native_email` - native_email
@@ -282,6 +283,7 @@ export const InputsSchemaItemTypeEnumApi = {
Choice: 'choice',
Json: 'json',
Integration: 'integration',
+ IntegrationMulti: 'integration_multi',
IntegrationField: 'integration_field',
Email: 'email',
NativeEmail: 'native_email',
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index da6f074aafc3..7f73f0eb3d47 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -69,6 +69,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -80,7 +81,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -168,6 +169,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -179,7 +181,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -317,6 +319,7 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -328,7 +331,7 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -416,6 +419,7 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -427,7 +431,7 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -565,6 +569,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -576,7 +581,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -664,6 +669,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -675,7 +681,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -817,6 +823,7 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -828,7 +835,7 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -916,6 +923,7 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -927,7 +935,7 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -1139,6 +1147,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -1150,7 +1159,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -1247,6 +1256,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -1258,7 +1268,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '\* `string` - string\n\* `number` - number\n\* `boolean` - boolean\n\* `dictionary` - dictionary\n\* `choice` - choice\n\* `json` - json\n\* `integration` - integration\n\* `integration_multi` - integration_multi\n\* `integration_field` - integration_field\n\* `email` - email\n\* `native_email` - native_email\n\* `posthog_assignee` - posthog_assignee\n\* `posthog_ticket_tags` - posthog_ticket_tags\n\* `posthog_business_hours` - posthog_business_hours\n\* `non_failure_status_codes` - non_failure_status_codes\n\* `customer_analytics_account_properties` - customer_analytics_account_properties\n\* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index e3d55372c193..8932efa76d4f 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -4506,6 +4506,7 @@ export const IntegrationKindApi = {
CustomerioApp: 'customerio-app',
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
+ Apns: 'apns',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
S3Compatible: 's3-compatible',
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.py
new file mode 100644
index 000000000000..7498a8f74368
--- /dev/null
+++ b/products/messaging/backend/api/push_subscriptions.py
@@ -0,0 +1,222 @@
+from datetime import UTC, datetime
+
+from django.db.models import Q
+from django.http import HttpResponse, JsonResponse
+from django.views.decorators.csrf import csrf_exempt
+
+from rest_framework import status
+from rest_framework.request import Request
+
+from posthog.api.capture import capture_internal
+from posthog.api.utils import get_token
+from posthog.exceptions import (
+ RequestParsingError,
+ UnspecifiedCompressionFallbackParsingError,
+ generate_exception_response,
+)
+from posthog.helpers.encrypted_fields import EncryptedFieldMixin
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
+from posthog.utils import load_data_from_request
+from posthog.utils_cors import cors_response
+
+VALID_PLATFORMS = ("android", "ios")
+
+# A device registration payload is a handful of short string fields (distinct_id, device_token,
+# platform, app_id, api_key) — well under 1 KiB. Cap the raw request body far above that but far below
+# Django's global limit, so a compressed body can't inflate into a memory-exhaustion payload when
+# load_data_from_request decompresses it.
+MAX_BODY_BYTES = 16 * 1024
+
+# Shared instance: deriving the encryption keys runs PBKDF2 (100k iterations per key) and is
+# cached on the instance, so a module-level singleton avoids re-deriving on every request.
+_encrypted_fields = EncryptedFieldMixin()
+
+
+# Resolve the integration from the app_id alone, not the device platform. An app_id is either a
+# Firebase project_id or an APNs bundle_id, so a device can register with either provider regardless
+# of its OS — e.g. an iOS device delivering through Firebase registers with the Firebase project_id.
+# (The client still sends its platform, but it's metadata, not what selects the provider.)
+def _find_integration(team_id: int, app_id: str) -> Integration | None:
+ return (
+ Integration.objects.filter(team_id=team_id)
+ .filter(Q(kind="firebase", config__project_id=app_id) | Q(kind="apns", config__bundle_id=app_id))
+ .only("id")
+ .first()
+ )
+
+
+@csrf_exempt
+def push_subscriptions(request: Request):
+ if request.method == "OPTIONS":
+ return cors_response(request, HttpResponse(""))
+
+ if request.method != "POST":
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Only POST requests are supported.",
+ type="validation_error",
+ code="method_not_allowed",
+ status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
+ ),
+ )
+
+ if len(request.body) > MAX_BODY_BYTES:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Request body too large.",
+ type="validation_error",
+ code="request_too_large",
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ ),
+ )
+
+ try:
+ data = load_data_from_request(request)
+ except (RequestParsingError, UnspecifiedCompressionFallbackParsingError):
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Invalid JSON body.",
+ type="validation_error",
+ code="invalid_json",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+
+ if not isinstance(data, dict):
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Invalid JSON body.",
+ type="validation_error",
+ code="invalid_json",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+
+ api_key = get_token(data, request)
+ if not api_key:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Project token not provided. You can find your project token in your PostHog project settings.",
+ type="authentication_error",
+ code="missing_api_key",
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ ),
+ )
+
+ team = Team.objects.get_team_from_cache_or_token(api_key)
+ if not team:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Invalid project token.",
+ type="authentication_error",
+ code="invalid_api_key",
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ ),
+ )
+
+ distinct_id = data.get("distinct_id")
+ device_token = data.get("device_token")
+ platform = data.get("platform")
+ app_id = data.get("app_id")
+
+ missing_fields = [
+ field_name
+ for field_name, value in [
+ ("distinct_id", distinct_id),
+ ("device_token", device_token),
+ ("platform", platform),
+ ("app_id", app_id),
+ ]
+ if not value or not isinstance(value, str)
+ ]
+ if missing_fields:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ f"Missing required fields: {', '.join(missing_fields)}.",
+ type="validation_error",
+ code="missing_fields",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+
+ assert isinstance(distinct_id, str)
+ assert isinstance(device_token, str)
+ assert isinstance(platform, str)
+ assert isinstance(app_id, str)
+
+ if platform not in VALID_PLATFORMS:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ f"Invalid platform. Must be one of: {', '.join(VALID_PLATFORMS)}.",
+ type="validation_error",
+ code="invalid_platform",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+
+ integration = _find_integration(team.id, app_id)
+ if not integration:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ f"No push integration found for app_id '{app_id}'. "
+ "Please configure the integration in your PostHog project settings.",
+ type="validation_error",
+ code="integration_not_found",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ ),
+ )
+
+ encrypted_token = _encrypted_fields.encrypt(device_token)
+ property_key = f"$device_push_subscription_{app_id}"
+
+ try:
+ capture_internal(
+ token=team.api_token,
+ event_name="$set",
+ event_source="push_subscriptions",
+ distinct_id=distinct_id,
+ timestamp=datetime.now(UTC),
+ properties={"$set": {property_key: encrypted_token}},
+ process_person_profile=True,
+ )
+ except Exception:
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ "Failed to store push subscription.",
+ type="server_error",
+ code="capture_failed",
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ ),
+ )
+
+ return cors_response(
+ request,
+ JsonResponse(
+ {
+ "distinct_id": distinct_id,
+ "platform": platform,
+ },
+ status=status.HTTP_200_OK,
+ ),
+ )
diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.py
new file mode 100644
index 000000000000..7908c3bad53c
--- /dev/null
+++ b/products/messaging/backend/api/test/test_push_subscriptions.py
@@ -0,0 +1,255 @@
+import gzip
+import json
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import Client
+
+from rest_framework import status
+
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
+
+
+class TestPushSubscriptionsAPI(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.client = Client()
+
+ self.firebase_integration = Integration.objects.create(
+ team=self.team,
+ kind="firebase",
+ integration_id="my-firebase-project",
+ config={"project_id": "my-firebase-project"},
+ sensitive_config={},
+ )
+ self.apns_integration = Integration.objects.create(
+ team=self.team,
+ kind="apns",
+ integration_id="TEAM123.com.example.app",
+ config={"bundle_id": "com.example.app", "team_id": "TEAM123", "key_id": "KEY123"},
+ sensitive_config={},
+ )
+
+ def _post(self, data: dict, api_key: str | None = None):
+ payload = {**data, "api_key": api_key or self.team.api_token}
+ return self.client.post(
+ "/api/push_subscriptions/",
+ data=json.dumps(payload),
+ content_type="application/json",
+ )
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_register_android_token(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "fcm-device-token-abc",
+ "platform": "android",
+ "app_id": "my-firebase-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["distinct_id"] == "user-1"
+ assert data["platform"] == "android"
+
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["token"] == self.team.api_token
+ assert call_kwargs["distinct_id"] == "user-1"
+ assert call_kwargs["event_name"] == "$set"
+ assert call_kwargs["process_person_profile"] is True
+ assert "$device_push_subscription_my-firebase-project" in call_kwargs["properties"]["$set"]
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_register_ios_token(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "apns-device-token-abc",
+ "platform": "ios",
+ "app_id": "com.example.app",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["distinct_id"] == "user-1"
+ assert data["platform"] == "ios"
+
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert "$device_push_subscription_com.example.app" in call_kwargs["properties"]["$set"]
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_ios_device_registers_a_firebase_token(self, mock_capture: MagicMock):
+ # An iOS app delivering via Firebase registers with the Firebase project_id even though its
+ # platform is "ios": the provider is resolved from the app_id, not the device platform.
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "fcm-token-from-ios",
+ "platform": "ios",
+ "app_id": "my-firebase-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ call_kwargs = mock_capture.call_args.kwargs
+ assert "$device_push_subscription_my-firebase-project" in call_kwargs["properties"]["$set"]
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_token_is_encrypted(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "fcm-device-token-abc",
+ "platform": "android",
+ "app_id": "my-firebase-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+
+ call_kwargs = mock_capture.call_args.kwargs
+ encrypted_value = call_kwargs["properties"]["$set"]["$device_push_subscription_my-firebase-project"]
+ # The encrypted value should not be the raw token
+ assert encrypted_value != "fcm-device-token-abc"
+ # It should be a non-empty string (Fernet token)
+ assert isinstance(encrypted_value, str)
+ assert len(encrypted_value) > 0
+
+ def test_missing_api_key_returns_401(self):
+ response = self.client.post(
+ "/api/push_subscriptions/",
+ data=json.dumps({"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_invalid_token_returns_401(self):
+ response = self._post(
+ {"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"},
+ api_key="phc_invalid_token",
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_missing_required_fields(self):
+ response = self._post({"distinct_id": "user-1"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "device_token" in response.json()["detail"]
+ assert "platform" in response.json()["detail"]
+ assert "app_id" in response.json()["detail"]
+
+ def test_invalid_platform(self):
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "device-token",
+ "platform": "windows_phone",
+ "app_id": "proj",
+ }
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Invalid platform" in response.json()["detail"]
+
+ def test_integration_not_found(self):
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "device-token",
+ "platform": "android",
+ "app_id": "nonexistent-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["detail"].lower()
+
+ def test_team_isolation(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ Integration.objects.create(
+ team=other_team,
+ kind="firebase",
+ integration_id="other-project",
+ config={"project_id": "other-project"},
+ sensitive_config={},
+ )
+
+ response = self._post(
+ {
+ "distinct_id": "user-1",
+ "device_token": "device-token",
+ "platform": "android",
+ "app_id": "other-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["detail"].lower()
+
+ def test_get_method_not_allowed(self):
+ response = self.client.get(
+ f"/api/push_subscriptions/?token={self.team.api_token}",
+ )
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+
+ def test_options_returns_200(self):
+ response = self.client.options("/api/push_subscriptions/")
+
+ assert response.status_code == status.HTTP_200_OK
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_gzip_compressed_body(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ payload = {
+ "api_key": self.team.api_token,
+ "distinct_id": "user-1",
+ "device_token": "fcm-device-token-abc",
+ "platform": "android",
+ "app_id": "my-firebase-project",
+ }
+ compressed = gzip.compress(json.dumps(payload).encode())
+
+ response = self.client.post(
+ "/api/push_subscriptions/",
+ data=compressed,
+ content_type="application/json",
+ HTTP_CONTENT_ENCODING="gzip",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["distinct_id"] == "user-1"
+ mock_capture.assert_called_once()
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_oversized_body_is_rejected_before_parsing(self, mock_capture: MagicMock):
+ # A body over the cap is rejected before load_data_from_request decompresses it, so a
+ # compressed body can't inflate into a memory-exhaustion payload.
+ oversized = json.dumps({"api_key": self.team.api_token, "padding": "x" * (16 * 1024 + 1)})
+
+ response = self.client.post(
+ "/api/push_subscriptions/",
+ data=oversized,
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
+ mock_capture.assert_not_called()
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 2601b6631a47..99817e3aff71 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3859,6 +3859,7 @@ export const IntegrationKindApi = {
CustomerioApp: 'customerio-app',
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
+ Apns: 'apns',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
S3Compatible: 's3-compatible',
diff --git a/products/workflows/frontend/Channels/APNSSetup/APNSSetupModal.tsx b/products/workflows/frontend/Channels/APNSSetup/APNSSetupModal.tsx
new file mode 100644
index 000000000000..c867068053ac
--- /dev/null
+++ b/products/workflows/frontend/Channels/APNSSetup/APNSSetupModal.tsx
@@ -0,0 +1,70 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonButton, LemonInput, LemonModal, LemonSegmentedButton, LemonTextArea, Link } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { APNSSetupModalLogicProps, apnsSetupModalLogic } from './apnsSetupModalLogic'
+
+export const APNSSetupModal = (props: APNSSetupModalLogicProps): JSX.Element => {
+ const { isApnsIntegrationSubmitting } = useValues(apnsSetupModalLogic(props))
+ const { submitApnsIntegration } = useActions(apnsSetupModalLogic(props))
+
+ return (
+ <LemonModal
+ title={
+ <div className="flex items-center gap-2">
+ <span>Configure Apple Push Notification Service</span>
+ </div>
+ }
+ onClose={props.onClose}
+ >
+ <Form logic={apnsSetupModalLogic} formKey="apnsIntegration">
+ <div className="gap-4 flex flex-col">
+ <p className="text-secondary">
+ You can find these values in your{' '}
+ <Link to="https://developer.apple.com/account/resources/authkeys/list" target="_blank">
+ Apple Developer account
+ </Link>{' '}
+ under Certificates, Identifiers & Profiles &gt; Keys.
+ </p>
+ <LemonField name="signingKey" label="Signing key (.p8)">
+ <LemonTextArea
+ placeholder="-----BEGIN PRIVATE KEY-----&#10;...&#10;-----END PRIVATE KEY-----"
+ minRows={4}
+ />
+ </LemonField>
+ <LemonField name="keyId" label="Key ID">
+ <LemonInput type="text" placeholder="ABC123DEFG" />
+ </LemonField>
+ <LemonField name="teamId" label="Apple team ID">
+ <LemonInput type="text" placeholder="ABCDE12345" />
+ </LemonField>
+ <LemonField name="bundleId" label="Bundle ID">
+ <LemonInput type="text" placeholder="com.example.app" />
+ </LemonField>
+ <LemonField name="environment" label="Environment">
+ <LemonSegmentedButton
+ options={[
+ { value: 'production', label: 'Production' },
+ { value: 'sandbox', label: 'Sandbox' },
+ ]}
+ fullWidth
+ />
+ </LemonField>
+ <div className="flex justify-end">
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isApnsIntegrationSubmitting}
+ onClick={submitApnsIntegration}
+ >
+ Connect
+ </LemonButton>
+ </div>
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts
new file mode 100644
index 000000000000..3c0e42ed3f9e
--- /dev/null
+++ b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts
@@ -0,0 +1,69 @@
+import { connect, kea, path, props } from 'kea'
+import { forms } from 'kea-forms'
+
+import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { IntegrationType } from '~/types'
+
+import type { apnsSetupModalLogicType } from './apnsSetupModalLogicType'
+
+export interface APNSSetupModalLogicProps {
+ integration?: IntegrationType | null
+ onComplete: (integrationId?: number) => void
+ onClose: () => void
+}
+
+export interface APNSFormType {
+ signingKey: string
+ keyId: string
+ teamId: string
+ bundleId: string
+ environment: 'production' | 'sandbox'
+}
+
+export const apnsSetupModalLogic = kea<apnsSetupModalLogicType>([
+ path(['products', 'workflows', 'frontend', 'APNSSetup', 'apnsSetupModalLogic']),
+ props({} as APNSSetupModalLogicProps),
+ connect(() => ({
+ actions: [integrationsLogic, ['loadIntegrations']],
+ })),
+ forms(({ props, actions, values }) => ({
+ apnsIntegration: {
+ defaults: {
+ signingKey: '',
+ keyId: '',
+ teamId: '',
+ bundleId: '',
+ environment: 'production' as const,
+ },
+ errors: ({ signingKey, keyId, teamId, bundleId }) => ({
+ signingKey: signingKey.trim() ? undefined : 'Signing key is required',
+ keyId: keyId.trim() ? undefined : 'Key ID is required',
+ teamId: teamId.trim() ? undefined : 'Team ID is required',
+ bundleId: bundleId.trim() ? undefined : 'Bundle ID is required',
+ }),
+ submit: async () => {
+ try {
+ const integration = await api.integrations.create({
+ kind: 'apns',
+ config: {
+ signing_key: values.apnsIntegration.signingKey,
+ key_id: values.apnsIntegration.keyId,
+ team_id_apple: values.apnsIntegration.teamId,
+ bundle_id: values.apnsIntegration.bundleId,
+ environment: values.apnsIntegration.environment,
+ },
+ })
+ actions.loadIntegrations()
+ lemonToast.success('APNS channel created successfully!')
+ props.onComplete(integration.id)
+ } catch (error: any) {
+ lemonToast.error(error.detail || 'Failed to create APNS channel')
+ throw error
+ }
+ },
+ },
+ })),
+])
diff --git a/products/workflows/frontend/Channels/ChannelSetupModal.tsx b/products/workflows/frontend/Channels/ChannelSetupModal.tsx
index 6734455aaf89..bd798ec99150 100644
--- a/products/workflows/frontend/Channels/ChannelSetupModal.tsx
+++ b/products/workflows/frontend/Channels/ChannelSetupModal.tsx
@@ -1,6 +1,8 @@
import { IntegrationType } from '~/types'
+import { APNSSetupModal } from './APNSSetup/APNSSetupModal'
import { EmailSetupModal } from './EmailSetup/EmailSetupModal'
+import { FCMSetupModal } from './FCMSetup/FCMSetupModal'
import { ChannelType } from './MessageChannels'
import { SlackSetupModal } from './SlackSetup/SlackSetupModal'
import { TwilioSetupModal } from './TwilioSetup/TwilioSetupModal'
@@ -37,6 +39,10 @@ export function ChannelSetupModal({
return <SlackSetupModal {...modalProps} />
case 'twilio':
return <TwilioSetupModal {...modalProps} />
+ case 'firebase':
+ return <FCMSetupModal {...modalProps} />
+ case 'apns':
+ return <APNSSetupModal {...modalProps} />
default:
return null
diff --git a/products/workflows/frontend/Channels/FCMSetup/FCMSetupModal.tsx b/products/workflows/frontend/Channels/FCMSetup/FCMSetupModal.tsx
new file mode 100644
index 000000000000..9d6ad9ed87ed
--- /dev/null
+++ b/products/workflows/frontend/Channels/FCMSetup/FCMSetupModal.tsx
@@ -0,0 +1,52 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonButton, LemonModal, LemonTextArea, Link } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { FCMSetupModalLogicProps, fcmSetupModalLogic } from './fcmSetupModalLogic'
+
+export const FCMSetupModal = (props: FCMSetupModalLogicProps): JSX.Element => {
+ const { isFcmIntegrationSubmitting } = useValues(fcmSetupModalLogic(props))
+ const { submitFcmIntegration } = useActions(fcmSetupModalLogic(props))
+
+ return (
+ <LemonModal
+ title={
+ <div className="flex items-center gap-2">
+ <span>Configure Firebase Cloud Messaging</span>
+ </div>
+ }
+ onClose={props.onClose}
+ >
+ <Form logic={fcmSetupModalLogic} formKey="fcmIntegration">
+ <div className="gap-4 flex flex-col">
+ <p className="text-secondary">
+ Paste the contents of your Firebase service account key JSON file. You can generate one from the{' '}
+ <Link
+ to="https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk"
+ target="_blank"
+ >
+ Firebase Console
+ </Link>{' '}
+ under Project Settings &gt; Service accounts &gt; Generate new private key.
+ </p>
+ <LemonField name="serviceAccountKey" label="Service account key JSON">
+ <LemonTextArea placeholder='{"type": "service_account", ...}' minRows={6} />
+ </LemonField>
+ <div className="flex justify-end">
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isFcmIntegrationSubmitting}
+ onClick={submitFcmIntegration}
+ >
+ Connect
+ </LemonButton>
+ </div>
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts
new file mode 100644
index 000000000000..44041cdd8e0f
--- /dev/null
+++ b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts
@@ -0,0 +1,62 @@
+import { connect, kea, path, props } from 'kea'
+import { forms } from 'kea-forms'
+
+import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { IntegrationType } from '~/types'
+
+import type { fcmSetupModalLogicType } from './fcmSetupModalLogicType'
+
+export interface FCMSetupModalLogicProps {
+ integration?: IntegrationType | null
+ onComplete: (integrationId?: number) => void
+ onClose: () => void
+}
+
+export interface FCMFormType {
+ serviceAccountKey: string
+}
+
+export const fcmSetupModalLogic = kea<fcmSetupModalLogicType>([
+ path(['products', 'workflows', 'frontend', 'FCMSetup', 'fcmSetupModalLogic']),
+ props({} as FCMSetupModalLogicProps),
+ connect(() => ({
+ actions: [integrationsLogic, ['loadIntegrations']],
+ })),
+ forms(({ props, actions, values }) => ({
+ fcmIntegration: {
+ defaults: {
+ serviceAccountKey: '',
+ },
+ errors: ({ serviceAccountKey }) => ({
+ serviceAccountKey: serviceAccountKey.trim() ? undefined : 'Service account key is required',
+ }),
+ submit: async () => {
+ let keyInfo: Record<string, unknown>
+ try {
+ keyInfo = JSON.parse(values.fcmIntegration.serviceAccountKey)
+ } catch {
+ lemonToast.error('Invalid JSON in service account key')
+ throw new Error('Invalid JSON')
+ }
+
+ try {
+ const integration = await api.integrations.create({
+ kind: 'firebase',
+ config: {
+ key_info: keyInfo,
+ },
+ })
+ actions.loadIntegrations()
+ lemonToast.success('Firebase Cloud Messaging channel created successfully!')
+ props.onComplete(integration.id)
+ } catch (error: any) {
+ lemonToast.error(error.detail || 'Failed to create Firebase channel')
+ throw error
+ }
+ },
+ },
+ })),
+])
diff --git a/products/workflows/frontend/Channels/MessageChannels.tsx b/products/workflows/frontend/Channels/MessageChannels.tsx
index 5270d1e3033e..7409c64e2cc7 100644
--- a/products/workflows/frontend/Channels/MessageChannels.tsx
+++ b/products/workflows/frontend/Channels/MessageChannels.tsx
@@ -14,7 +14,7 @@ import { ChannelSetupModal } from './ChannelSetupModal'
const HedgehogReporter = pngHoggie(reporterPng)
-const MESSAGING_CHANNEL_TYPES = ['email', 'slack', 'twilio'] as const
+const MESSAGING_CHANNEL_TYPES = ['email', 'slack', 'twilio', 'firebase', 'apns'] as const
export type ChannelType = (typeof MESSAGING_CHANNEL_TYPES)[number]
export function MessageChannels(): JSX.Element {
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index ac9a74666ce8..b36289ddbdfb 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -22,6 +22,7 @@ import { AppMetricsTotalsRequest, loadAppMetricsTotals } from 'lib/components/Ap
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { uuid } from 'lib/utils/dom'
import { objectsEqual, reconcileById } from 'lib/utils/objects'
+import { templateToConfiguration } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
import { urls } from 'scenes/urls'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
@@ -675,6 +676,18 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
config = { ...config, inputs: { ...config.inputs, ...dynamicInputs } }
}
}
+ // Seed the step's inputs with the template defaults at creation time. The input renderer
+ // snapshots its values on mount, so applying defaults after mount leaves the fields blank.
+ if ('template_id' in config && config.template_id) {
+ const template = values.hogFunctionTemplatesById[config.template_id]
+ if (template) {
+ const defaults = templateToConfiguration(template).inputs ?? {}
+ config = {
+ ...config,
+ inputs: { ...defaults, ...('inputs' in config ? config.inputs : {}) },
+ }
+ }
+ }
const newAction = {
id: isHogFlowActionNode
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
index 7a24812bb73e..2c449a7f4edd 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
@@ -14,6 +14,8 @@ import { CreateActionType, hogFlowEditorLogic } from '../hogFlowEditorLogic'
// Side-effect imports: register product-specific trigger and action nodes
import '../registry'
+import { FEATURE_FLAGS } from 'lib/constants'
+
import { PERSON_DEPENDENT_ACTION_TYPES, workflowLogic } from '../../workflowLogic'
import { getRegisteredActionNodeCategories } from '../registry/actions/actionNodeRegistry'
import { useHogFlowStep } from '../steps/HogFlowSteps'
@@ -53,6 +55,13 @@ export const ACTION_NODES_TO_SHOW: CreateActionType[] = [
},
]
+const PUSH_NOTIFICATION_ACTION_NODE: CreateActionType = {
+ type: 'function_push',
+ name: 'Push',
+ description: 'Send a push notification to the user.',
+ config: { template_id: 'template-native-push', inputs: {} },
+}
+
const DEFAULT_DELAY = '10m'
export const DELAY_NODES_TO_SHOW: CreateActionType[] = [
{
@@ -196,7 +205,7 @@ const customFilterFunction = (template: HogFunctionTemplateType): boolean => {
return false
}
- if (template.status === 'coming_soon') {
+ if (['hidden', 'coming_soon'].includes(template.status)) {
return false
}
@@ -297,6 +306,9 @@ export function HogFlowEditorPanelBuild(): JSX.Element {
{ACTION_NODES_TO_SHOW.map((node, index) => (
<HogFlowEditorToolbarNode key={`${node.type}-${index}`} action={node} />
))}
+ {featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS] && (
+ <HogFlowEditorToolbarNode key="push-notifications" action={PUSH_NOTIFICATION_ACTION_NODE} />
+ )}
<HogFunctionTemplatesChooser />
<span className="flex gap-2 text-sm font-semibold mt-2 items-center">
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
index ffe59c742593..e12f7ac26b10 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/HogFlowSteps.tsx
@@ -10,6 +10,7 @@ import {
IconHourglass,
IconLeave,
IconLetter,
+ IconNotification,
IconPercentage,
IconWebhooks,
} from '@posthog/icons'
@@ -107,6 +108,12 @@ const HogFlowStepConfigs: Partial<{
color: () => '#f22f46',
renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
},
+ function_push: {
+ type: 'function_push',
+ icon: () => <IconNotification />,
+ color: (_, isDarkModeOn) => (isDarkModeOn ? '#F8BE2A' : '#F44D01'),
+ renderConfiguration: (node) => <StepFunctionConfiguration key={node.id} node={node} />,
+ },
function: {
type: 'function',
icon: (action, hogFunctionTemplatesById) => {
@@ -118,6 +125,10 @@ const HogFlowStepConfigs: Partial<{
return <IconWebhooks />
}
+ if (action.config.template_id === 'template-native-push') {
+ return <IconNotification />
+ }
+
const template = hogFunctionTemplatesById[action.config.template_id]
return template?.icon_url ? (
<img className="LemonIcon rounded" src={template.icon_url} alt={template.name} />
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
index 140ba2da7c3d..9ef6513d6aef 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
@@ -18,6 +18,9 @@ export function StepFunctionConfiguration({ node }: { node: StepFunctionNode }):
<>
<StepSchemaErrors />
<HogFlowFunctionConfiguration
+ // Remount per node: the input renderer snapshots its values on mount, so switching to
+ // another step of the same template must remount to show the newly selected node's inputs.
+ key={node.id}
templateId={templateId}
inputs={inputs}
setInputs={(inputs) => partialSetWorkflowActionConfig(node.id, { inputs })}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
index f2ce594ed150..3ca824b5d99a 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import { useEffect } from 'react'
import { IconCheck } from '@posthog/icons'
-import { LemonBanner, LemonButton, Link, Spinner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCollapse, Link, Spinner } from '@posthog/lemon-ui'
import { CyclotronJobInputs } from 'lib/components/CyclotronJob/CyclotronJobInputs'
import { templateToConfiguration } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
@@ -112,6 +112,7 @@ export function HogFlowFunctionConfiguration({
const template = hogFunctionTemplatesById[templateId]
const isEmailStep = templateId === 'template-email'
+ const isPushStep = templateId === 'template-native-push'
const engagementEventsEnabled = !!currentTeam?.workflows_config?.capture_workflows_engagement_events
useEffect(() => {
// oxlint-disable-next-line exhaustive-deps
@@ -123,7 +124,9 @@ export function HogFlowFunctionConfiguration({
setInputs({ ...defaults, ...currentInputs })
}
}
- }, [templateId])
+ // Re-run once the template resolves: it loads asynchronously, so on first render it can still be
+ // undefined and the defaults would otherwise never be applied.
+ }, [templateId, !!template])
if (hogFunctionTemplatesByIdLoading) {
return (
@@ -140,19 +143,48 @@ export function HogFlowFunctionConfiguration({
const triggerType = workflow?.trigger?.type
const sampleGlobals = buildSampleGlobals(triggerType, workflow?.variables)
+ // Native push carries a long tail of optional Android/iOS override fields. Keep the core message
+ // fields inline and tuck the platform-specific ones into collapsed sections so the form stays flat.
+ const inputsSchema = template.inputs_schema ?? []
+ const isPlatformInput = (key: string): boolean => key.startsWith('android_') || key.startsWith('ios_')
+ const coreInputsSchema = isPushStep ? inputsSchema.filter((s) => !isPlatformInput(s.key)) : inputsSchema
+ const androidInputsSchema = isPushStep ? inputsSchema.filter((s) => s.key.startsWith('android_')) : []
+ const iosInputsSchema = isPushStep ? inputsSchema.filter((s) => s.key.startsWith('ios_')) : []
+
+ const renderInputs = (schema: typeof inputsSchema): JSX.Element => (
+ <CyclotronJobInputs
+ errors={errors}
+ warnings={warnings}
+ configuration={{ inputs: inputs as Record<string, CyclotronJobInputType>, inputs_schema: schema }}
+ showSource={false}
+ sampleGlobalsWithInputs={sampleGlobals}
+ onInputChange={(key, value) => setInputs({ ...inputs, [key]: value })}
+ />
+ )
+
return (
<>
- <CyclotronJobInputs
- errors={errors}
- warnings={warnings}
- configuration={{
- inputs: inputs as Record<string, CyclotronJobInputType>,
- inputs_schema: template?.inputs_schema ?? [],
- }}
- showSource={false}
- sampleGlobalsWithInputs={sampleGlobals}
- onInputChange={(key, value) => setInputs({ ...inputs, [key]: value })}
- />
+ {renderInputs(coreInputsSchema)}
+ {isPushStep && (androidInputsSchema.length > 0 || iosInputsSchema.length > 0) && (
+ <LemonCollapse
+ className="mt-2"
+ multiple
+ panels={[
+ ...(androidInputsSchema.length > 0
+ ? [
+ {
+ key: 'android',
+ header: 'Android options',
+ content: renderInputs(androidInputsSchema),
+ },
+ ]
+ : []),
+ ...(iosInputsSchema.length > 0
+ ? [{ key: 'ios', header: 'iOS options', content: renderInputs(iosInputsSchema) }]
+ : []),
+ ]}
+ />
+ )}
{isEmailStep ? (
engagementEventsEnabled ? (
<div className="flex items-center gap-1.5 mt-2 text-xs text-muted-alt">
@@ -211,7 +243,7 @@ export function HogFlowFunctionConfiguration({
)
) : null}
<HogFlowFunctionMappings
- useMapping={Array.isArray(mappings) || (template?.mapping_templates?.length ?? 0) > 0}
+ useMapping={!isPushStep && (Array.isArray(mappings) || (template?.mapping_templates?.length ?? 0) > 0)}
inputs={inputs}
inputs_schema={template?.inputs_schema ?? []}
mappings={mappings ?? []}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/hogFunctionStepLogic.tsx b/products/workflows/frontend/Workflows/hogflows/steps/hogFunctionStepLogic.tsx
index 4aaf750ad9cd..bdbb565360e1 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/hogFunctionStepLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/hogFunctionStepLogic.tsx
@@ -10,7 +10,10 @@ import { HogFlowAction } from '../types'
import type { hogFunctionStepLogicType } from './hogFunctionStepLogicType'
export type StepFunctionNode = Node<
- Extract<HogFlowAction, { type: 'function' } | { type: 'function_email' } | { type: 'function_sms' }>
+ Extract<
+ HogFlowAction,
+ { type: 'function' } | { type: 'function_email' } | { type: 'function_sms' } | { type: 'function_push' }
+ >
>
export interface HogFunctionStepLogicProps {
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
index a3c757df93a8..ec04a043db47 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
@@ -81,6 +81,7 @@ export const CyclotronJobInputSchemaTypeSchema = z.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -295,6 +296,17 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
inputs: z.record(z.string(), CyclotronInputSchema),
}),
}),
+ z.object({
+ ..._commonActionFields,
+ type: z.literal('function_push'),
+ config: z.object({
+ message_category_id: z.string().uuid().optional(),
+ message_category_type: z.enum(['marketing', 'transactional']).optional(),
+ template_uuid: z.string().uuid().optional(),
+ template_id: z.literal('template-native-push'),
+ inputs: z.record(z.string(), CyclotronInputSchema),
+ }),
+ }),
// Exit
z.object({
@@ -308,8 +320,8 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
export const isOptOutEligibleAction = (
action: HogFlowAction
-): action is Extract<HogFlowAction, { type: 'function_email' | 'function_sms' }> => {
- return ['function_email', 'function_sms'].includes(action.type)
+): action is Extract<HogFlowAction, { type: 'function_email' | 'function_sms' | 'function_push' }> => {
+ return ['function_email', 'function_sms', 'function_push'].includes(action.type)
}
export const isEmailAction = (action: HogFlowAction): action is Extract<HogFlowAction, { type: 'function_email' }> => {
@@ -318,8 +330,8 @@ export const isEmailAction = (action: HogFlowAction): action is Extract<HogFlowA
export const isFunctionAction = (
action: HogFlowAction
-): action is Extract<HogFlowAction, { type: 'function' | 'function_sms' | 'function_email' }> => {
- return ['function', 'function_sms', 'function_email'].includes(action.type)
+): action is Extract<HogFlowAction, { type: 'function' | 'function_sms' | 'function_email' | 'function_push' }> => {
+ return ['function', 'function_sms', 'function_email', 'function_push'].includes(action.type)
}
export const isTriggerFunction = (
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 7f9f5b18b9c9..722abd609cf7 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -569,6 +569,17 @@ export const workflowLogic = kea<workflowLogicType>([
email: combinedErrors,
}
}
+ } else if (isFunctionAction(action) && action.config.template_id === 'template-native-push') {
+ // Native push needs at least one delivery channel; without one the runtime
+ // throws "No push channel configured" at send time. Block publish instead.
+ const channels = action.config.inputs?.channels?.value
+ if (!Array.isArray(channels) || channels.length === 0) {
+ result.valid = false
+ result.errors = {
+ ...result.errors,
+ channels: 'Select at least one channel to send this notification',
+ }
+ }
}
if (
diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsx
index 42266842c29e..03a72faeeee5 100644
--- a/products/workflows/frontend/WorkflowsScene.tsx
+++ b/products/workflows/frontend/WorkflowsScene.tsx
@@ -1,16 +1,17 @@
import { actions, kea, path, props, reducers, selectors, useActions, useValues } from 'kea'
import { urlToAction } from 'kea-router'
-import { IconLetter, IconPlusSmall } from '@posthog/icons'
+import { IconApple, IconAndroid, IconLetter, IconPlusSmall } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'
import api from 'lib/api'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
-import { TeamMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IconSlack, IconTwilio } from 'lib/lemon-ui/icons'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { addProductIntent } from 'lib/utils/product-intents'
import { capitalizeFirstLetter } from 'lib/utils/strings'
@@ -99,6 +100,7 @@ export const scene: SceneExport<WorkflowsSceneProps> = {
export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
const { currentTab } = useValues(workflowsSceneLogic(props))
+ const { featureFlags } = useValues(featureFlagLogic)
const { openSetupModal } = useActions(integrationsLogic)
const { openNewCategoryModal } = useActions(optOutCategoriesLogic)
const { showNewWorkflowModal } = useActions(newWorkflowLogic)
@@ -137,6 +139,26 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
),
onClick: () => openSetupModal(undefined, 'twilio'),
},
+ ...(featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS]
+ ? [
+ {
+ label: (
+ <div className="flex gap-1 items-center">
+ <IconAndroid /> Firebase Cloud Messaging
+ </div>
+ ),
+ onClick: () => openSetupModal(undefined, 'firebase'),
+ },
+ {
+ label: (
+ <div className="flex gap-1 items-center">
+ <IconApple /> Apple Push Notifications
+ </div>
+ ),
+ onClick: () => openSetupModal(undefined, 'apns'),
+ },
+ ]
+ : []),
]
const tabs: LemonTab<WorkflowsSceneTab>[] = [
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a43a2d3ab890..24c834ae71b3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5490,6 +5490,7 @@ export namespace Schemas {
CustomerioApp: 'customerio-app',
CustomerioWebhook: 'customerio-webhook',
CustomerioTrack: 'customerio-track',
+ Apns: 'apns',
Postgresql: 'postgresql',
AwsS3: 'aws-s3',
S3Compatible: 's3-compatible',
@@ -28308,6 +28309,7 @@ export namespace Schemas {
* * `choice` - choice
* * `json` - json
* * `integration` - integration
+ * * `integration_multi` - integration_multi
* * `integration_field` - integration_field
* * `email` - email
* * `native_email` - native_email
@@ -28329,6 +28331,7 @@ export namespace Schemas {
Choice: 'choice',
Json: 'json',
Integration: 'integration',
+ IntegrationMulti: 'integration_multi',
IntegrationField: 'integration_field',
Email: 'email',
NativeEmail: 'native_email',
diff --git a/services/mcp/src/generated/cdp_functions/api.ts b/services/mcp/src/generated/cdp_functions/api.ts
index b7d2502cc53a..100cecb0110c 100644
--- a/services/mcp/src/generated/cdp_functions/api.ts
+++ b/services/mcp/src/generated/cdp_functions/api.ts
@@ -94,6 +94,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -105,7 +106,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -188,6 +189,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -199,7 +201,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -345,6 +347,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -356,7 +359,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -439,6 +442,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -450,7 +454,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -670,6 +674,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -681,7 +686,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -778,6 +783,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -789,7 +795,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
diff --git a/services/mcp/src/generated/error_tracking_alerts/api.ts b/services/mcp/src/generated/error_tracking_alerts/api.ts
index 445944584877..70d6ac3c41d1 100644
--- a/services/mcp/src/generated/error_tracking_alerts/api.ts
+++ b/services/mcp/src/generated/error_tracking_alerts/api.ts
@@ -94,6 +94,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -105,7 +106,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -188,6 +189,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -199,7 +201,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -336,6 +338,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -347,7 +350,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
@@ -430,6 +433,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'choice',
'json',
'integration',
+ 'integration_multi',
'integration_field',
'email',
'native_email',
@@ -441,7 +445,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
'customer_analytics_account_relationships',
])
.describe(
- '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
+ '* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships'
),
key: zod.string(),
label: zod.string().optional(),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-create.json
index e039b9bf76ba..0a9d4d70cb1b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-create.json
@@ -174,7 +174,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -183,6 +183,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -335,7 +336,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -344,6 +345,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
index 3042b99f7b81..8cb169d4f26a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
@@ -312,7 +312,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -321,6 +321,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -493,7 +494,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -502,6 +503,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
index 12fa68751a4b..01e620113d66 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
@@ -178,7 +178,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -187,6 +187,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -339,7 +340,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -348,6 +349,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-create.json
index 2ab4dc8fc255..10c155472b3f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-create.json
@@ -174,7 +174,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -183,6 +183,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -335,7 +336,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -344,6 +345,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
index 229d0479d8da..719d58d3d792 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
@@ -178,7 +178,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -187,6 +187,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",
@@ -339,7 +340,7 @@
]
},
"type": {
- "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
+ "description": "* `string` - string\n* `number` - number\n* `boolean` - boolean\n* `dictionary` - dictionary\n* `choice` - choice\n* `json` - json\n* `integration` - integration\n* `integration_multi` - integration_multi\n* `integration_field` - integration_field\n* `email` - email\n* `native_email` - native_email\n* `posthog_assignee` - posthog_assignee\n* `posthog_ticket_tags` - posthog_ticket_tags\n* `posthog_business_hours` - posthog_business_hours\n* `non_failure_status_codes` - non_failure_status_codes\n* `customer_analytics_account_properties` - customer_analytics_account_properties\n* `customer_analytics_account_relationships` - customer_analytics_account_relationships",
"enum": [
"string",
"number",
@@ -348,6 +349,7 @@
"choice",
"json",
"integration",
+ "integration_multi",
"integration_field",
"email",
"native_email",