Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp): detect self-referential event-forwarding loops in destination fetches (#61512)

Daniel Marchuk1cd98e2b1efd
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index b039131eb42d..e606fd2f15d6 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -141,6 +141,7 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_FETCH_RETRIES'
| 'CDP_FETCH_BACKOFF_BASE_MS'
| 'CDP_FETCH_BACKOFF_MAX_MS'
+ | 'CDP_SELF_LOOP_GUARD_MODE'
| 'CDP_EMAIL_QUEUE_ROUTING'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC'
| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'
@@ -396,6 +397,7 @@ export function createCdpCoreServices(
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: config.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 74f9d49cbdd3..8f7897281f38 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -17,6 +17,7 @@ import {
WARPSTREAM_CYCLOTRON_PRODUCER,
WARPSTREAM_INGESTION_PRODUCER,
} from './outputs/producers'
+import { SelfLoopGuardMode } from './services/self-loop-guard'
import { CyclotronJobQueueKind, CyclotronJobQueueSource } from './types'
// CdpConfig intersects ClickhouseConfig so any consumer reading
@@ -90,6 +91,7 @@ export type CdpConfig = ClickhouseConfig & {
CDP_FETCH_RETRIES: number
CDP_FETCH_BACKOFF_BASE_MS: number
CDP_FETCH_BACKOFF_MAX_MS: number
+ CDP_SELF_LOOP_GUARD_MODE: SelfLoopGuardMode
CDP_OVERFLOW_QUEUE_ENABLED: boolean
HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC: string
HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER: CdpProducerName
@@ -199,6 +201,10 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_FETCH_RETRIES: 3,
CDP_FETCH_BACKOFF_BASE_MS: 1000,
CDP_FETCH_BACKOFF_MAX_MS: 30000,
+ // Observe-only by default: detect self-loops and emit metrics without blocking.
+ // Valid values: 'disabled' | 'warn'. A blocking 'enforce' mode will be added in a
+ // follow-up PR once cdp_self_loop_guard_total production data is in.
+ CDP_SELF_LOOP_GUARD_MODE: 'warn',
CDP_OVERFLOW_QUEUE_ENABLED: false,
HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,
HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index ba3252724c8d..24935ff1e5ca 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -489,6 +489,7 @@ export function createHogTransformerService(
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: config.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: deps.teamManager, siteUrl: config.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index ce4f354d9b2f..e28683e15a4d 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -19,6 +19,7 @@ import { compileHog } from '../templates/compiler'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
import { EXTEND_OBJECT_KEY, isConnectionLevelError } from './hog-executor.service'
+import { selfLoopGuardCounter } from './self-loop-guard'
// Mock before importing fetch
jest.mock('~/utils/request', () => {
@@ -71,6 +72,7 @@ describe('Hog Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
@@ -1664,6 +1666,95 @@ describe('Hog Executor', () => {
expect(result.error.message).toContain('status code 400')
})
})
+
+ describe('self-loop guard', () => {
+ const OWN_TOKEN = 'phc_synthetic_own_0000000000000000'
+ const INGEST_URL = 'https://us.i.posthog.com/capture/'
+
+ const mockOwnTeam = (): void => {
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ id: 1,
+ api_token: OWN_TOKEN,
+ secret_api_token: null,
+ } as any)
+ }
+
+ const setMode = (mode: 'disabled' | 'warn'): void => {
+ ;(executor as any).config.selfLoopGuardMode = mode
+ }
+
+ const ownTokenCaptureBody = (): string =>
+ JSON.stringify({ api_key: OWN_TOKEN, event: 'replicated', distinct_id: 'u1', properties: {} })
+
+ // The detected count is the production signal that drives the enforce decision,
+ // so assert it actually moves - not just the human-facing log.
+ const readDetectedCount = async (): Promise<number> => {
+ const metric = await selfLoopGuardCounter.get()
+ return metric.values.find((v) => v.labels.mode === 'warn' && v.labels.action === 'detected')?.value ?? 0
+ }
+
+ it('detects a self-referential ingest fetch and logs + meters it without blocking (warn)', async () => {
+ setMode('warn')
+ mockOwnTeam()
+ const invocation = await createFetchInvocation({
+ url: INGEST_URL,
+ method: 'POST',
+ body: ownTokenCaptureBody(),
+ })
+ ;(fetch as jest.Mock).mockImplementationOnce(() =>
+ Promise.resolve({ status: 200, headers: {}, text: () => Promise.resolve('ok') })
+ )
+ const detectedBefore = await readDetectedCount()
+
+ const result = await executor.executeFetch(invocation)
+
+ // Observe-only: the fetch still happens and nothing errors.
+ expect(result.error).toBeUndefined()
+ expect(cleanLogs(result.logs.map((l) => l.message))).toEqual(
+ expect.arrayContaining([expect.stringContaining('can form an event-forwarding loop')])
+ )
+ expect(await readDetectedCount()).toBe(detectedBefore + 1)
+ })
+
+ it('does not flag a normal external fetch even with the project token in the body', async () => {
+ setMode('warn')
+ mockOwnTeam()
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/test`,
+ method: 'POST',
+ body: ownTokenCaptureBody(),
+ })
+ mockRequest.mockClear()
+ const detectedBefore = await readDetectedCount()
+
+ const result = await executor.executeFetch(invocation)
+
+ expect(result.error).toBeUndefined()
+ expect(mockRequest).toHaveBeenCalled()
+ expect(cleanLogs(result.logs.map((l) => l.message))).not.toEqual(
+ expect.arrayContaining([expect.stringContaining('event-forwarding loop')])
+ )
+ expect(await readDetectedCount()).toBe(detectedBefore)
+ })
+
+ it('fails open: a team lookup error never breaks the fetch', async () => {
+ setMode('warn')
+ jest.spyOn(hub.teamManager, 'getTeam').mockRejectedValue(new Error('db unavailable'))
+ const invocation = await createFetchInvocation({
+ url: INGEST_URL,
+ method: 'POST',
+ body: ownTokenCaptureBody(),
+ })
+ ;(fetch as jest.Mock).mockImplementationOnce(() =>
+ Promise.resolve({ status: 200, headers: {}, text: () => Promise.resolve('ok') })
+ )
+
+ const result = await executor.executeFetch(invocation)
+
+ // Detection failing must not surface as a destination error.
+ expect(result.error).toBeUndefined()
+ })
+ })
})
describe('isConnectionLevelError', () => {
@@ -1782,6 +1873,7 @@ describe('Hog Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting,
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index aae8e324d373..08b6a7d3ee8a 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -35,6 +35,12 @@ import { isNonFailureStatus } from '../utils/non-failure-status-codes'
import { HogInputsService } from './hog-inputs.service'
import { EmailService } from './messaging/email.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
+import {
+ SelfLoopGuardMode,
+ isPostHogIngestUrl,
+ isSelfReferentialIngestFetch,
+ selfLoopGuardCounter,
+} from './self-loop-guard'
/** Narrowed config type for CDP fetch retry settings, used by native/segment destination executors */
export type CdpFetchConfig = Pick<
@@ -48,6 +54,7 @@ export interface HogExecutorConfig {
fetchRetries: number
fetchBackoffBaseMs: number
fetchBackoffMaxMs: number
+ selfLoopGuardMode: SelfLoopGuardMode
emailQueueRouting: string
}
@@ -757,6 +764,30 @@ export class HogExecutorService {
}
}
+ // Observe-only detection of event-forwarding loops: a fetch back into this
+ // project's own ingestion endpoint re-enters the pipeline and can re-trigger this
+ // same function. We only measure for now (a follow-up will design enforcement from
+ // this signal). The ingest-URL check gates the team lookup so external fetches (the
+ // common case) pay nothing, and the whole block fails open - detection must never
+ // break a destination it was only meant to watch.
+ if (this.config.selfLoopGuardMode !== 'disabled' && isPostHogIngestUrl(params.url)) {
+ try {
+ const team = await this.asyncContext.teamManager.getTeam(invocation.teamId)
+ if (team && isSelfReferentialIngestFetch({ url: params.url, body: params.body, team })) {
+ selfLoopGuardCounter.inc({ mode: this.config.selfLoopGuardMode, action: 'detected' })
+ addLog(
+ 'warn',
+ `This fetch targets a PostHog ingestion endpoint using this project's own API key, which can form an event-forwarding loop. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`
+ )
+ }
+ } catch (err) {
+ logger.warn('🦔', '[HogExecutor] Self-loop guard detection skipped due to an internal error', {
+ error: err,
+ teamId: invocation.teamId,
+ })
+ }
+ }
+
const fetchParams: FetchOptions = { method, headers }
if (!['GET', 'HEAD'].includes(method) && params.body) {
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 4f8d2e34b468..18e51a755f21 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -61,6 +61,7 @@ describe('HogFunctionHandler', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
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 49ad8801c433..a0eb0d65d959 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -81,6 +81,7 @@ describe('Hogflow Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: hub.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
hogInputsService,
@@ -1864,6 +1865,7 @@ describe('Hogflow Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: '*',
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
@@ -2061,6 +2063,7 @@ describe('Hogflow Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: '*',
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
@@ -2094,6 +2097,7 @@ describe('Hogflow Executor', () => {
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: '',
+ selfLoopGuardMode: hub.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
new HogInputsService(hub.integrationManager, hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
diff --git a/nodejs/src/cdp/services/self-loop-guard.test.ts b/nodejs/src/cdp/services/self-loop-guard.test.ts
new file mode 100644
index 000000000000..31d8ecaec54a
--- /dev/null
+++ b/nodejs/src/cdp/services/self-loop-guard.test.ts
@@ -0,0 +1,155 @@
+import { Team } from '../../types'
+import { extractRequestApiKey, isPostHogIngestUrl, isSelfReferentialIngestFetch } from './self-loop-guard'
+
+// Synthetic, non-production values. OWN_TOKEN is the project the destination runs in;
+// OTHER_TOKEN is a different project (legitimate cross-project replication).
+const OWN_TOKEN = 'phc_synthetic_own_0000000000000000'
+const OWN_SECRET_TOKEN = 'phsx_synthetic_own_secret_00000000'
+const OTHER_TOKEN = 'phc_synthetic_other_111111111111111'
+
+const TEAM: Pick<Team, 'api_token' | 'secret_api_token'> = {
+ api_token: OWN_TOKEN,
+ secret_api_token: OWN_SECRET_TOKEN,
+}
+
+const INGEST_URL = 'https://us.i.posthog.com/capture/'
+const BATCH_URL = 'https://eu.i.posthog.com/batch/'
+const LOGS_URL = 'https://us.i.posthog.com/i/v1/logs'
+const API_URL = 'https://us.posthog.com/api/projects/100/insights/'
+const EXTERNAL_URL = 'https://external.example.com/webhook'
+
+const captureBody = (event: string, properties: Record<string, unknown> = {}, apiKey = OWN_TOKEN): string =>
+ JSON.stringify({ api_key: apiKey, event, distinct_id: 'synthetic_user_1', properties })
+
+// The shape a replicator posts to /batch/ - the primary real self-loop case.
+const batchBody = (events: string[], apiKey = OWN_TOKEN): string =>
+ JSON.stringify({
+ api_key: apiKey,
+ historical_migration: false,
+ batch: events.map((event) => ({ event, distinct_id: 'synthetic_user_1', properties: {} })),
+ })
+
+const detect = (overrides: { url?: string; body?: string | null }): boolean =>
+ isSelfReferentialIngestFetch({
+ url: overrides.url ?? INGEST_URL,
+ body: overrides.body === undefined ? captureBody('replicated_event') : overrides.body,
+ team: TEAM,
+ })
+
+describe('self-loop-guard', () => {
+ describe('isPostHogIngestUrl', () => {
+ it.each([
+ ['https://us.i.posthog.com/capture/', true],
+ ['https://us.i.posthog.com/capture', true],
+ ['https://eu.i.posthog.com/batch/', true],
+ ['https://us.i.posthog.com/e/', true],
+ ['https://us.i.posthog.com/track/', true],
+ ['https://us.i.posthog.com/i/v0/e/', true],
+ ['https://us.i.posthog.com/capture/?api_key=abc', true],
+ ['https://posthog.com/capture', true],
+ // observability + REST endpoints are NOT ingestion - cannot form a loop
+ ['https://us.i.posthog.com/i/v1/logs', false],
+ ['https://us.posthog.com/api/projects/100/insights/', false],
+ ['https://us.i.posthog.com/decide', false],
+ // non-posthog hosts
+ ['https://external.example.com/capture', false],
+ ['https://posthog.com.evil.com/capture', false],
+ ['https://notposthog.com/capture', false],
+ ['not a url', false],
+ ])('classifies %s as ingest=%s', (url, expected) => {
+ expect(isPostHogIngestUrl(url)).toBe(expected)
+ })
+ })
+
+ describe('extractRequestApiKey', () => {
+ it('reads the top-level api_key field', () => {
+ expect(extractRequestApiKey(captureBody('e'), INGEST_URL)).toBe(OWN_TOKEN)
+ })
+
+ it.each(['token', 'api_token'])('reads the top-level %s field', (field) => {
+ expect(extractRequestApiKey(JSON.stringify({ [field]: OWN_TOKEN }), INGEST_URL)).toBe(OWN_TOKEN)
+ })
+
+ it('reads the api_key query parameter when body has none', () => {
+ expect(extractRequestApiKey('', `${INGEST_URL}?api_key=${OWN_TOKEN}`)).toBe(OWN_TOKEN)
+ })
+
+ it('reads the top-level api_key from a batch body (the replicator shape)', () => {
+ expect(extractRequestApiKey(batchBody(['e1', 'e2']), INGEST_URL)).toBe(OWN_TOKEN)
+ })
+
+ it('does NOT treat $lib_token in event properties as the request credential', () => {
+ // The SDK auto-attaches the team token as $lib_token on event properties. That
+ // is metadata, not an intent to ingest as the project - it must not be matched.
+ const body = JSON.stringify({ event: 'ticket_updated', properties: { $lib_token: OWN_TOKEN } })
+ expect(extractRequestApiKey(body, API_URL)).toBeNull()
+ })
+
+ it('returns null for an unparseable body and no query token', () => {
+ expect(extractRequestApiKey('not-json{{', INGEST_URL)).toBeNull()
+ })
+ })
+
+ describe('isSelfReferentialIngestFetch', () => {
+ // The `false` rows double as the incident regression matrix: cross-project tokens,
+ // $lib_token SDK metadata, REST/observability endpoints, and substring matches must
+ // never be flagged.
+ it.each([
+ { case: 'capture to ingest endpoint with the project own token', args: {}, expected: true },
+ {
+ case: 'batch replicator posting to /batch/ with the project own token',
+ args: { url: BATCH_URL, body: batchBody(['e1', 'e2']) },
+ expected: true,
+ },
+ {
+ case: 'project own token on the URL query string',
+ args: { url: `${INGEST_URL}?api_key=${OWN_TOKEN}`, body: '' },
+ expected: true,
+ },
+ {
+ case: 'project secret token on the URL query string',
+ args: { url: `${INGEST_URL}?api_key=${OWN_SECRET_TOKEN}`, body: '' },
+ expected: true,
+ },
+ {
+ case: 'capture authenticated with the project secret token',
+ args: { body: captureBody('e', {}, OWN_SECRET_TOKEN) },
+ expected: true,
+ },
+ {
+ case: 'batch posting to /batch/ with a different project token',
+ args: { url: BATCH_URL, body: batchBody(['e1', 'e2'], OTHER_TOKEN) },
+ expected: false,
+ },
+ { case: 'external (non-PostHog) fetch', args: { url: EXTERNAL_URL }, expected: false },
+ { case: 'observability logs endpoint (not ingestion)', args: { url: LOGS_URL }, expected: false },
+ {
+ case: 'workflow step posting to a PostHog REST API endpoint (with $lib_token in body)',
+ args: { url: API_URL, body: JSON.stringify({ status: 'open', properties: { $lib_token: OWN_TOKEN } }) },
+ expected: false,
+ },
+ {
+ case: 'cross-project replication (different project token)',
+ args: { body: captureBody('any_event', {}, OTHER_TOKEN) },
+ expected: false,
+ },
+ {
+ case: 'team token only as $lib_token, not the api_key',
+ args: { body: JSON.stringify({ event: 'alpha', properties: { $lib_token: OWN_TOKEN } }) },
+ expected: false,
+ },
+ {
+ case: 'team token a substring of an unrelated field',
+ args: { body: JSON.stringify({ event: 'alpha', properties: { ref: `${OWN_TOKEN}_extra` } }) },
+ expected: false,
+ },
+ {
+ case: 'ingest fetch carrying no credential at all',
+ args: { body: JSON.stringify({ event: 'alpha' }) },
+ expected: false,
+ },
+ ])('returns $expected for: $case', ({ args, expected }) => {
+ expect(detect(args)).toBe(expected)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/services/self-loop-guard.ts b/nodejs/src/cdp/services/self-loop-guard.ts
new file mode 100644
index 000000000000..da3c1b05ecd0
--- /dev/null
+++ b/nodejs/src/cdp/services/self-loop-guard.ts
@@ -0,0 +1,90 @@
+import { Counter } from 'prom-client'
+
+import { Team } from '../../types'
+import { parseJSON } from '../../utils/json-parse'
+
+// A destination that fetches one of PostHog's own ingestion endpoints, authenticating
+// as its own project, re-enters the event pipeline. If that re-ingested event then
+// re-triggers the same destination, the chain forms an event-forwarding loop that
+// doubles traffic on every hop.
+//
+// This is the observe-only stage: it detects the shape and emits a metric so we can
+// measure real production traffic before designing enforcement. Modes are kept separate
+// so a follow-up can add an enforcing mode without changing the detection surface.
+export type SelfLoopGuardMode = 'disabled' | 'warn'
+
+// Only these paths re-enter the event pipeline. Observability (`/i/v1/logs`) and the
+// REST API (`/api/...`, `/decide`) do NOT re-trigger event processing, so a fetch to
+// them - even with the project's own token - cannot form an event-forwarding loop.
+const INGEST_PATHS = new Set(['/capture', '/batch', '/e', '/track', '/i/v0/e'])
+
+// Top-level body fields that carry the credential a capture request authenticates with.
+const API_KEY_FIELDS = ['api_key', 'token', 'api_token'] as const
+
+export const selfLoopGuardCounter = new Counter({
+ name: 'cdp_self_loop_guard_total',
+ help: 'Count of fetches the self-loop guard detected as self-referential, by mode',
+ labelNames: ['mode', 'action'],
+})
+
+export const isPostHogIngestUrl = (urlString: string): boolean => {
+ try {
+ const url = new URL(urlString)
+ const host = url.hostname.toLowerCase()
+ if (host !== 'posthog.com' && !host.endsWith('.posthog.com')) {
+ return false
+ }
+ const path = url.pathname.replace(/\/+$/, '') || '/'
+ return INGEST_PATHS.has(path)
+ } catch {
+ return false
+ }
+}
+
+// The credential a capture request authenticates with - either a top-level body field
+// or an `api_key`/`token` query parameter. Deliberately does NOT look at `$lib_token`
+// (SDK metadata auto-attached to event properties) or `Authorization` headers, both of
+// which carry a token without expressing intent to ingest as that project.
+export const extractRequestApiKey = (body: string | null | undefined, urlString: string): string | null => {
+ if (body) {
+ try {
+ const parsed = parseJSON(body)
+ if (parsed && typeof parsed === 'object') {
+ const obj = parsed as Record<string, unknown>
+ for (const field of API_KEY_FIELDS) {
+ if (typeof obj[field] === 'string') {
+ return obj[field] as string
+ }
+ }
+ }
+ } catch {
+ // Not JSON - fall through to the query string.
+ }
+ }
+ try {
+ const params = new URL(urlString).searchParams
+ return params.get('api_key') ?? params.get('token')
+ } catch {
+ return null
+ }
+}
+
+const ownsToken = (team: Pick<Team, 'api_token' | 'secret_api_token'>, token: string): boolean => {
+ return token === team.api_token || (team.secret_api_token !== null && token === team.secret_api_token)
+}
+
+// True when a fetch targets a PostHog ingestion endpoint authenticating with the
+// invocation's own project token - i.e. the shape that can form an event-forwarding
+// loop. Returns false for cross-project replication (a different project's token),
+// non-ingest endpoints, and requests carrying no project credential.
+export const isSelfReferentialIngestFetch = (input: {
+ url: string
+ body: string | null | undefined
+ team: Pick<Team, 'api_token' | 'secret_api_token'>
+}): boolean => {
+ if (!isPostHogIngestUrl(input.url)) {
+ return false
+ }
+ const requestToken = extractRequestApiKey(input.body, input.url)
+ return requestToken !== null && ownsToken(input.team, requestToken)
+}
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index c29cbbcf9bba..a8b0bb1febc8 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -209,6 +209,7 @@ export class TemplateTester {
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
emailQueueRouting: config.CDP_EMAIL_QUEUE_ROUTING,
+ selfLoopGuardMode: config.CDP_SELF_LOOP_GUARD_MODE,
},
{ teamManager: undefined as any, siteUrl: config.SITE_URL },
hogInputsService,