: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): prototype the push registration endpoint in node (#101110)
Daniel Marchuk505e334684a0
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex 7ec6d4fa7a06..e84e6d7f2754 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -186,6 +186,8 @@ export function getPluginServerCapabilities(throw new Error(`Mode ${mode} is handled by IngestionGeneralServer, not PluginServer`)case PluginServerMode.ingestion_api:throw new Error(`Mode ${mode} is handled by IngestionApiServer, not PluginServer`)+ case PluginServerMode.push_api:+ throw new Error(`Mode ${mode} is handled by PushApiServer, not PluginServer`)case PluginServerMode.cdp_hogflow_scheduler:return {cdpHogflowScheduler: true,diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 5bc76615de93..36cadc47a980 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -68,6 +68,7 @@ export enum PluginServerMode {ingestion_traces = 'ingestion-traces',cdp_hogflow_scheduler = 'cdp-hogflow-scheduler',ingestion_api = 'ingestion-api',+ push_api = 'push-api',}export const stringToPluginServerMode = Object.fromEntries(diff --git a/nodejs/src/index.ts b/nodejs/src/index.tsindex b94778413d82..03d6ba6766cb 100644--- a/nodejs/src/index.ts+++ b/nodejs/src/index.ts@@ -20,6 +20,7 @@ import { IngestionSessionReplayMlMirrorServer } from '~/servers/ingestion-sessioimport { IngestionSessionReplayMlParquetSinkServer } from '~/servers/ingestion-session-replay-ml-parquet-sink-server'import { IngestionSessionReplayServer } from '~/servers/ingestion-session-replay-server'import { IngestionTracesServer } from '~/servers/ingestion-traces-server'+import { PushApiServer } from '~/servers/push-api-server'import { RecordingApiServer } from '~/servers/recording-api-server'function createServer(): NodeServer {@@ -71,6 +72,9 @@ function createServer(): NodeServer {case PluginServerMode.ingestion_traces:return new IngestionTracesServer()+ case PluginServerMode.push_api:+ return new PushApiServer()+default:// CDP modes, evaluation scheduler, local dev (null), local-cdpreturn new PluginServer()diff --git a/nodejs/src/messaging/push-subscriptions/identity-token.test.ts b/nodejs/src/messaging/push-subscriptions/identity-token.test.tsnew file mode 100644index 000000000000..1a0b836314a8--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/identity-token.test.ts@@ -0,0 +1,129 @@+import { generateKeyPairSync, randomBytes } from 'crypto'+import jwt from 'jsonwebtoken'++import { verifyPushIdentityToken } from './identity-token'++describe('verifyPushIdentityToken', () => {+ const AUDIENCE = 'posthog:push_identity'+ // Generated rather than written in: a literal here trips the hardcoded-credential scan.+ const secret = randomBytes(32).toString('hex')+ const distinctId = 'user-1'+ const appId = 'com.example.app'++ const { publicKey, privateKey } = generateKeyPairSync('ec', {+ namedCurve: 'P-256',+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ })++ const sign = (payload: Record<string, unknown>, key: string = privateKey): string =>+ jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE, ...payload }, key, {+ algorithm: 'ES256',+ expiresIn: 300,+ })++ const verify = (token: string, overrides: Partial<Parameters<typeof verifyPushIdentityToken>[0]> = {}): boolean =>+ verifyPushIdentityToken({ token, distinctId, appId, publicKeys: [publicKey], ...overrides })++ it('accepts a token signed with the registered public key', () => {+ expect(verify(sign({}))).toEqual(true)+ })++ it('refuses an HS256 token keyed with the public key', () => {+ // Guards against reintroducing an HMAC pass. The public key is published on the channel, so+ // verifying it as an HMAC secret would let anyone holding it mint a token for any user.+ const forged = jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE }, publicKey, {+ algorithm: 'HS256',+ expiresIn: 300,+ })++ expect(verify(forged)).toEqual(false)+ })++ it('refuses a token signed with the project secret, which is no longer accepted', () => {+ const hmac = jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE }, secret, {+ algorithm: 'HS256',+ expiresIn: 300,+ })++ expect(verify(hmac)).toEqual(false)+ })++ it('refuses an unsigned token', () => {+ // An alg=none token has no key by definition, and the empty key is what makes this the+ // attack the test covers.+ // nosemgrep: javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret+ const unsigned = jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE }, '', {+ algorithm: 'none',+ expiresIn: 300,+ } as jwt.SignOptions)++ expect(verify(unsigned)).toEqual(false)+ })++ it('refuses a token with no expiry', () => {+ // jsonwebtoken only checks expiry when the claim is present, so an external signer could+ // otherwise mint a token that never stops working.+ const forever = jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE }, privateKey, {+ algorithm: 'ES256',+ })++ expect(verify(forever)).toEqual(false)+ })++ it('refuses an expired token', () => {+ const expired = jwt.sign({ sub: distinctId, app_id: appId, aud: AUDIENCE }, privateKey, {+ algorithm: 'ES256',+ expiresIn: -10,+ })++ expect(verify(expired)).toEqual(false)+ })++ it.each([+ ['another user', { sub: 'someone-else' }],+ ['another app', { app_id: 'com.other.app' }],+ ['another audience', { aud: 'posthog:something_else' }],+ ])('refuses a token minted for %s', (_name, overrides) => {+ expect(verify(sign(overrides))).toEqual(false)+ })++ it.each([+ ['an empty string', ''],+ ['a value that is not a token', 'not-a-jwt'],+ [+ 'a token with a mangled signature',+ `${jwt.sign({ sub: distinctId }, privateKey, { algorithm: 'ES256' })}tampered`,+ ],+ ])('refuses %s without raising', (_name, token) => {+ expect(verify(token)).toEqual(false)+ })++ // Django verifies with PyJWT, whose claim rules differ from jsonwebtoken's. A string payload skips+ // jsonwebtoken's own claim validation when signing, so these shapes can be minted at all.+ const now = Math.floor(Date.now() / 1000)+ it.each([+ ['exp as a whole-number string', { exp: String(now + 300) }, true],+ ['nbf as a whole-number string in the past', { exp: now + 300, nbf: String(now - 10) }, true],+ ['exp as a fractional string', { exp: `${now + 300}.5` }, false],+ ['iat in the future', { exp: now + 300, iat: now + 600 }, false],+ ['iat that is not a number', { exp: now + 300, iat: 'yesterday' }, false],+ ['iat as null', { exp: now + 300, iat: null }, false],+ ['an audience list holding a non-string', { exp: now + 300, aud: [AUDIENCE, 5] }, false],+ ['a numeric jti', { exp: now + 300, jti: 7 }, false],+ ])('matches django for %s', (_name, claims, accepted) => {+ const token = jwt.sign(+ JSON.stringify({ sub: distinctId, app_id: appId, aud: AUDIENCE, ...claims }),+ privateKey,+ {+ algorithm: 'ES256',+ }+ )++ expect(verify(token)).toEqual(accepted)+ })++ it('refuses everything when the channel registered no key', () => {+ expect(verify(sign({}), { publicKeys: [] })).toEqual(false)+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/identity-token.ts b/nodejs/src/messaging/push-subscriptions/identity-token.tsnew file mode 100644index 000000000000..8da017560ccb--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/identity-token.ts@@ -0,0 +1,87 @@+import jwt from 'jsonwebtoken'++const AUDIENCE = 'posthog:push_identity'++/** ES256 only. The customer signs with an EC private key and registers the public half on the+ * channel, so PostHog never holds a key that can mint a token.+ *+ * Verification is deliberately single-algorithm. An HS256 pass alongside this one is the JWT+ * algorithm-confusion attack waiting to happen: the public key is published on the channel, so+ * anyone holding it could sign an HMAC token for any user.+ */+export function verifyPushIdentityToken(params: {+ token: string+ distinctId: string+ appId: string+ publicKeys: string[]+}): boolean {+ for (const publicKey of params.publicKeys) {+ if (decodeMatches(params.token, publicKey, params.distinctId, params.appId)) {+ return true+ }+ }+ return false+}++function decodeMatches(token: string, key: string, distinctId: string, appId: string): boolean {+ try {+ // Only the signature is checked here. The claims are checked below with PyJWT's rules, which+ // differ from jsonwebtoken's, so a token Django accepts is accepted here and nothing more.+ const payload = jwt.verify(token, key, {+ algorithms: ['ES256'],+ ignoreExpiration: true,+ ignoreNotBefore: true,+ })+ if (typeof payload !== 'object' || payload === null) {+ return false+ }+ const claims = payload as Record<string, unknown>+ return claimsValid(claims, Date.now() / 1000) && claims.sub === distinctId && claims.app_id === appId+ } catch {+ // Covers a bad signature and a key that cannot be used with ES256. Every such case fails+ // closed rather than raising.+ return false+ }+}++function claimsValid(claims: Record<string, unknown>, now: number): boolean {+ // An external signer can mint a token with no exp, so require it.+ if (claims.exp === undefined || claims.exp === null) {+ return false+ }+ for (const name of ['iat', 'nbf', 'exp']) {+ if (!(name in claims)) {+ continue+ }+ const value = pythonInt(claims[name])+ if (value === null) {+ return false+ }+ if (name === 'exp' ? value <= now : value > now) {+ return false+ }+ }+ if ('jti' in claims && typeof claims.jti !== 'string') {+ return false+ }+ const audiences = typeof claims.aud === 'string' ? [claims.aud] : claims.aud+ if (!Array.isArray(audiences) || audiences.some((audience) => typeof audience !== 'string')) {+ return false+ }+ return audiences.includes(AUDIENCE)+}++/** Python's `int()` over a JSON value, which is how PyJWT reads a time claim: a number truncates, a+ * boolean is 0 or 1, and a string must hold a whole number. Returns null where Python raises. */+function pythonInt(value: unknown): number | null {+ if (typeof value === 'boolean') {+ return value ? 1 : 0+ }+ if (typeof value === 'number') {+ return Number.isFinite(value) ? Math.trunc(value) : null+ }+ if (typeof value === 'string' && /^\s*[+-]?\d+(_\d+)*\s*$/.test(value)) {+ return Number(value.replace(/_/g, '').trim())+ }+ return null+}diff --git a/nodejs/src/messaging/push-subscriptions/project-token-lookup.test.ts b/nodejs/src/messaging/push-subscriptions/project-token-lookup.test.tsnew file mode 100644index 000000000000..1ec9385c69a7--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/project-token-lookup.test.ts@@ -0,0 +1,54 @@+import { ProjectTokenLookup } from './project-token-lookup'++describe('ProjectTokenLookup', () => {+ let tokens: Record<string, number>+ let postgres: any+ let lookup: ProjectTokenLookup++ beforeEach(() => {+ jest.useFakeTimers()+ tokens = { phc_live: 7 }+ postgres = {+ query: jest.fn((_use: unknown, _sql: string, [requested]: [string[]]) =>+ Promise.resolve({+ rows: requested+ .filter((token) => token in tokens)+ .map((token) => ({ id: tokens[token], api_token: token })),+ })+ ),+ }+ lookup = new ProjectTokenLookup(postgres)+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ const resolve = async (token: string): Promise<unknown> => {+ const pending = lookup.getTeamByToken(token)+ await jest.advanceTimersByTimeAsync(50)+ return await pending+ }++ it('resolves a project token to its team', async () => {+ expect(await resolve('phc_live')).toEqual({ id: 7, api_token: 'phc_live' })+ })++ it('does not resolve a team by its id', async () => {+ expect(await resolve('7')).toBeNull()+ })++ it('refuses a token too long to be a project token without querying or caching it', async () => {+ expect(await resolve('a'.repeat(201))).toBeNull()+ expect(postgres.query).not.toHaveBeenCalled()+ })++ it('stops resolving a reset token within seconds', async () => {+ expect(await resolve('phc_live')).not.toBeNull()+ delete tokens.phc_live++ await jest.advanceTimersByTimeAsync(6_500)++ expect(await resolve('phc_live')).toBeNull()+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/project-token-lookup.ts b/nodejs/src/messaging/push-subscriptions/project-token-lookup.tsnew file mode 100644index 000000000000..398287c0f9ce--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/project-token-lookup.ts@@ -0,0 +1,51 @@+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { LazyLoader } from '~/common/utils/lazy-loader'++export type ProjectTeam = { id: number; api_token: string }++/** The longest value `posthog_team.api_token` can hold. A longer token cannot match a project. */+export const MAX_PROJECT_TOKEN_LENGTH = 200++/** Resolves a project token to its team by exact match on `api_token` and nothing else.+ *+ * The shared TeamManager is not used here. It caches every looked-up key for minutes, and on a+ * public endpoint the key is whatever the caller sends. A short refresh makes a reset token stop+ * working within seconds, close to Django, which invalidates its cache on reset.+ */+export class ProjectTokenLookup {+ private loader: LazyLoader<ProjectTeam>++ constructor(postgres: PostgresRouter) {+ this.loader = new LazyLoader({+ name: 'PushProjectTokens',+ refreshAgeMs: 5_000,+ refreshJitterMs: 1_000,+ // Matches the service's own negative cache, which answers repeats before this is asked.+ refreshNullAgeMs: 60_000,+ maxSize: 50_000,+ loader: async (tokens: string[]) => {+ const { rows } = await postgres.query<ProjectTeam>(+ PostgresUse.COMMON_READ,+ 'SELECT id, api_token FROM posthog_team WHERE api_token = ANY($1)',+ [tokens],+ 'fetchPushProjectTokens'+ )+ const result: Record<string, ProjectTeam | null> = {}+ for (const token of tokens) {+ result[token] = null+ }+ for (const row of rows) {+ result[row.api_token] = { id: Number(row.id), api_token: row.api_token }+ }+ return result+ },+ })+ }++ public async getTeamByToken(token: string): Promise<ProjectTeam | null> {+ if (token.length > MAX_PROJECT_TOKEN_LENGTH) {+ return null+ }+ return await this.loader.get(token)+ }+}diff --git a/nodejs/src/messaging/push-subscriptions/push-capture.test.ts b/nodejs/src/messaging/push-subscriptions/push-capture.test.tsnew file mode 100644index 000000000000..f4c8200d2d2c--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-capture.test.ts@@ -0,0 +1,166 @@+import { IncomingMessage, Server, createServer } from 'http'+import { AddressInfo } from 'net'++import { parseJSON } from '~/common/utils/json-parse'++import { PushCaptureService } from './push-capture'++describe('PushCaptureService', () => {+ let server: Server+ let base: string+ let received: { url: string; headers: IncomingMessage['headers']; body: any }[]+ let status: number+ // Answers taken in order, one per request; `status` answers once they run out.+ let script: { status: number; result?: string; delayMs?: number }[]++ beforeEach(async () => {+ received = []+ status = 200+ script = []+ server = createServer((req, res) => {+ const chunks: Buffer[] = []+ req.on('data', (chunk) => chunks.push(chunk))+ req.on('end', () => {+ received.push({+ url: req.url ?? '',+ headers: req.headers,+ body: parseJSON(Buffer.concat(chunks).toString('utf8')),+ })+ const step = script.shift() ?? { status }+ const uuid = received[received.length - 1].body?.batch?.[0]?.uuid+ const body = step.result ? JSON.stringify({ results: { [uuid]: { result: step.result } } }) : '{}'+ const reply = (): void => {+ res.writeHead(step.status, { 'Content-Type': 'application/json' }).end(body)+ }+ if (step.delayMs) {+ setTimeout(reply, step.delayMs)+ } else {+ reply()+ }+ })+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ })++ afterEach(async () => {+ await new Promise((resolve) => server.close(resolve))+ })++ const send = (timeoutMs = 2000): Promise<void> =>+ new PushCaptureService(base, timeoutMs, () => Promise.resolve()).capture({+ token: 'phc_real',+ event: '$set',+ distinctId: 'user-1',+ properties: { $set: { $device_push_subscription_app: 'cipher' }, $process_person_profile: true },+ })++ it('posts the v1 internal batch envelope django posts', async () => {+ await send()++ expect(received).toHaveLength(1)+ expect(received[0].url).toEqual('/i/v1/analytics/events')+ expect(received[0].body).toMatchObject({+ capture_internal: true,+ historical_migration: false,+ batch: [+ {+ event: '$set',+ distinct_id: 'user-1',+ properties: { $set: { $device_push_subscription_app: 'cipher' } },+ options: { process_person_profile: true },+ },+ ],+ })+ })++ it("posts to the v1 path when configured with the plugin server's /capture url", async () => {+ await new PushCaptureService(`${base}/capture`, 2000, () => Promise.resolve()).capture({+ token: 'phc_real',+ event: '$set',+ distinctId: 'user-1',+ properties: {},+ })++ expect(received[0].url).toEqual('/i/v1/analytics/events')+ })++ it('authenticates with the project token, which the endpoint requires', async () => {+ await send()++ expect(received[0].headers.authorization).toEqual('Bearer phc_real')+ })++ it('lifts the legacy person-processing property out of properties', async () => {+ // Left in `properties` it is ingested as an ordinary event property and the option never+ // applies, so the person profile is not processed and the subscription is not stored.+ await send()++ expect(received[0].body.batch[0].properties.$process_person_profile).toBeUndefined()+ expect(received[0].body.batch[0].options.process_person_profile).toEqual(true)+ })++ it('gives every event its own uuid', async () => {+ await send()+ await send()++ expect(received[0].body.batch[0].uuid).not.toEqual(received[1].body.batch[0].uuid)+ })++ it.each([+ ['a client error', 400, 1],+ ['an auth error', 401, 1],+ ['a rate limit, which django does not retry either', 429, 1],+ ['a server error that persists', 500, 4],+ ['an unavailable capture that persists', 503, 4],+ ])('throws on %s so the SDK is not told it stored', async (_name, code, requests) => {+ status = code++ await expect(send()).rejects.toThrow(`capture returned ${code}`)+ expect(received).toHaveLength(requests)+ })++ it.each([+ ['a transient server error', [{ status: 503 }, { status: 200 }], 2],+ [+ 'an event capture asked to retry',+ [+ { status: 200, result: 'retry' },+ { status: 200, result: 'ok' },+ ],+ 2,+ ],+ ])('stores the registration after %s, as django does', async (_name, steps, requests) => {+ script = steps++ await send()++ expect(received).toHaveLength(requests)+ expect(new Set(received.map((request) => request.body.batch[0].uuid)).size).toEqual(1)+ })++ it('marks each resubmission of an event capture asked to retry', async () => {+ script = [+ { status: 200, result: 'retry' },+ { status: 200, result: 'ok' },+ ]++ await send()++ expect(received.map((request) => request.headers['posthog-attempt'])).toEqual(['1', '2'])+ })++ it('gives up when capture asks to retry on every attempt', async () => {+ script = Array.from({ length: 4 }, () => ({ status: 200, result: 'retry' }))++ await expect(send()).rejects.toThrow('capture asked to retry the event on every attempt')+ expect(received).toHaveLength(4)+ })++ it('does not retry a timeout, which would hold the SDK request for several timeouts', async () => {+ script = [{ status: 200, delayMs: 500 }]++ await expect(send(50)).rejects.toThrow()+ expect(received).toHaveLength(1)+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/push-capture.ts b/nodejs/src/messaging/push-subscriptions/push-capture.tsnew file mode 100644index 000000000000..2cae5ce6f10f--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-capture.ts@@ -0,0 +1,196 @@+import { randomUUID } from 'crypto'+import { Counter } from 'prom-client'++import { parseJSON } from '~/common/utils/json-parse'+import { logger } from '~/common/utils/logger'+import { FetchResponse, internalFetch } from '~/common/utils/request'++/** Submits the person update through the same capture path Django uses.+ *+ * The plugin server's shared `InternalCaptureService` posts a single flat event to the public+ * capture endpoint, with no Authorization header. Django posts a v1 batch envelope carrying+ * `capture_internal: true` to `/i/v1/analytics/events` with the project token as a bearer. Those are+ * different doors into ingestion: the internal one is how an event submitted on a customer's behalf+ * is marked as such, and quota and routing read that marking. Serving this endpoint from Node+ * through the public door would change how the same registration is ingested and counted, which is+ * not a change this move is supposed to make.+ */++const SDK_INFO = 'posthog-capture-v1-internal/1.0'+const CAPTURE_V1_INTERNAL_ENDPOINT = '/i/v1/analytics/events'++/** The v1 option fields whose legacy spelling has to be lifted out of `properties`, or capture-rs+ * reads them as ordinary event properties and the option goes unapplied. */+const OPTIONS_TO_LEGACY_PROPERTY: Record<string, string> = {+ cookieless_mode: '$cookieless_mode',+ disable_skew_correction: '$ignore_sent_at',+ product_tour_id: '$product_tour_id',+ process_person_profile: '$process_person_profile',+}+const EXTRA_LEGACY_ALIASES: Record<string, string> = {+ disable_skew_correction: 'disable_skew_adjustment',+}++const captureCounter = new Counter({+ name: 'push_subscription_capture_total',+ help: 'Person updates submitted for a device registration, by outcome.',+ labelNames: ['outcome'],+})++export type PushCaptureEvent = {+ token: string+ event: string+ distinctId: string+ properties: Record<string, any>+}++export class PushCaptureService {+ private origin: string++ constructor(+ captureUrl: string,+ private timeoutMs: number = 2000,+ private sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms))+ ) {+ // The plugin server's CAPTURE_INTERNAL_URL ends in the `/capture` path of the v0 endpoint, while+ // Django's is the bare origin. The v1 path goes on the origin, so either form works.+ this.origin = new URL(captureUrl).origin+ }++ /** Resolves only when capture accepted the event. The caller answers the SDK on that basis, and+ * an SDK that is told the registration was stored never sends it again. */+ public async capture(event: PushCaptureEvent): Promise<void> {+ const now = new Date().toISOString()+ const { options, properties } = splitOptions(event.properties)++ const entry: Record<string, any> = {+ event: event.event,+ uuid: randomUUID(),+ distinct_id: event.distinctId,+ timestamp: now,+ properties,+ }+ if (Object.keys(options).length > 0) {+ entry.options = options+ }+ const body = JSON.stringify({+ created_at: now,+ capture_internal: true,+ historical_migration: false,+ batch: [entry],+ })++ for (let attempt = 1; ; attempt++) {+ const response = await this.post(event.token, body, attempt)++ if (response.status < 200 || response.status >= 300) {+ captureCounter.inc({ outcome: 'rejected' })+ logger.warn('push_subscription_capture_rejected', { status: response.status })+ throw new Error(`capture returned ${response.status}`)+ }++ if (resultFor(await response.text(), entry.uuid) !== 'retry') {+ captureCounter.inc({ outcome: 'ok' })+ return+ }+ if (attempt >= MAX_ATTEMPTS) {+ captureCounter.inc({ outcome: 'rejected' })+ logger.warn('push_subscription_capture_rejected', { status: response.status, result: 'retry' })+ throw new Error('capture asked to retry the event on every attempt')+ }+ await this.sleep(retryAfterMs(response.headers['retry-after']))+ }+ }++ /** One application attempt, with the transport retries Django's session makes under it. A timeout+ * is not retried: each attempt already holds the SDK's request for the full timeout, and retrying+ * one is what stretches Django's answer to many seconds while capture is slow. */+ private async post(token: string, body: string, attempt: number): Promise<FetchResponse> {+ for (let retry = 0; ; retry++) {+ try {+ const response = await internalFetch(`${this.origin}${CAPTURE_V1_INTERNAL_ENDPOINT}`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ 'User-Agent': SDK_INFO,+ 'PostHog-Sdk-Info': SDK_INFO,+ 'PostHog-Attempt': String(attempt),+ 'PostHog-Request-Id': randomUUID(),+ 'PostHog-Request-Timestamp': new Date().toISOString(),+ },+ body,+ timeoutMs: this.timeoutMs,+ })+ if (!TRANSPORT_RETRY_STATUSES.has(response.status) || retry >= TRANSPORT_BACKOFF_MS.length) {+ return response+ }+ await response.text()+ } catch (error) {+ if ((error as Error).name === 'TimeoutError' || retry >= TRANSPORT_BACKOFF_MS.length) {+ throw error+ }+ }+ await this.sleep(TRANSPORT_BACKOFF_MS[retry])+ }+ }+}++/** Django's session retries these statuses and connection errors three times, backing off 0, 200 and+ * 400ms (urllib3 `Retry(total=3, backoff_factor=0.1)`). */+const TRANSPORT_RETRY_STATUSES = new Set([500, 502, 503, 504])+const TRANSPORT_BACKOFF_MS = [0, 200, 400]++/** Django's `CAPTURE_V1_INTERNAL_MAX_ATTEMPTS` and `CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS`. */+const MAX_ATTEMPTS = 4+const RETRY_AFTER_CAP_MS = 5000++function resultFor(text: string, uuid: string): string | undefined {+ try {+ const result = parseJSON(text)?.results?.[uuid]?.result+ return typeof result === 'string' ? result : undefined+ } catch {+ return undefined+ }+}++/** Seconds, capped, as Django's `_parse_retry_after` reads it: absent is 0, unparseable is 1. */+function retryAfterMs(header: string | undefined): number {+ if (!header) {+ return 0+ }+ const seconds = Number(header)+ if (!Number.isFinite(seconds)) {+ return 1000+ }+ return Math.min(Math.max(seconds * 1000, 0), RETRY_AFTER_CAP_MS)+}++function splitOptions(input: Record<string, any>): { options: Record<string, any>; properties: Record<string, any> } {+ const properties = { ...input }+ const options: Record<string, any> = {}++ for (const [optionKey, legacyProperty] of Object.entries(OPTIONS_TO_LEGACY_PROPERTY)) {+ let value = properties[legacyProperty]+ delete properties[legacyProperty]++ const alias = EXTRA_LEGACY_ALIASES[optionKey]+ if (alias) {+ const aliasValue = properties[alias]+ delete properties[alias]+ if (value === undefined || value === null) {+ value = aliasValue+ }+ }++ if (value !== undefined && value !== null) {+ options[optionKey] = value+ }+ }++ for (const field of ['$session_id', '$window_id']) {+ delete properties[field]+ }++ return { options, properties }+}diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.tsnew file mode 100644index 000000000000..8b7a361377c8--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.test.ts@@ -0,0 +1,209 @@+import { Server, createServer, request as httpRequest } from 'http'+import { AddressInfo } from 'net'+import { register } from 'prom-client'+import { gzipSync } from 'zlib'++import { FetchResponse, internalFetch } from '~/common/utils/request'++import { createPushSubscriptionsHandler } from './push-subscriptions-http'+import { PushHandlerResult, PushSubscriptionsService } from './push-subscriptions.service'++describe('push subscriptions http', () => {+ let server: Server+ let base: string+ let seen: { method: string; body: string; contentType?: string; compression?: string | null }[]+ let answer: PushHandlerResult+ let failure: Error | null++ beforeEach(async () => {+ seen = []+ answer = { status: 200, body: { distinct_id: 'user-1' } }+ failure = null+ const service = {+ handle: (request: any) => {+ seen.push({+ method: request.method,+ body: request.body.toString('utf8'),+ contentType: request.contentType,+ compression: request.query?.get('compression') ?? null,+ })+ return failure ? Promise.reject(failure) : Promise.resolve(answer)+ },+ } as unknown as PushSubscriptionsService++ const handler = createPushSubscriptionsHandler(service)+ server = createServer(+ (req, res) =>+ void handler(req, res).catch(() => {+ res.writeHead(500).end()+ })+ )+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ })++ afterEach(async () => {+ await new Promise((resolve) => server.close(resolve))+ })++ const post = (path: string, init: Record<string, any> = {}): Promise<FetchResponse> =>+ internalFetch(`${base}${path}`, { method: 'POST', ...init })++ it('delivers a DELETE body to the service', async () => {+ // The reason this endpoint is not on the plugin server's express framework: that one drops+ // the body on DELETE, and DELETE with a body is how every released SDK unregisters a device.+ const body = JSON.stringify({ api_key: 'phc_x', app_id: 'a' })++ const response = await internalFetch(`${base}/api/push_subscriptions/`, {+ method: 'DELETE',+ headers: { 'Content-Type': 'application/json' },+ body,+ })++ expect(response.status).toEqual(200)+ expect(seen).toEqual([{ method: 'DELETE', body, contentType: 'application/json', compression: null }])+ })++ it('passes the content type and query through untouched', async () => {+ await post('/api/push_subscriptions/?compression=gzip', {+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'data=x',+ })++ expect(seen[0]).toMatchObject({+ contentType: 'application/x-www-form-urlencoded',+ compression: 'gzip',+ })+ })++ it('hands the gzipped bytes over without decoding them itself', async () => {+ const gzipped = gzipSync(Buffer.from('{"a":1}'))++ await post('/api/push_subscriptions/', {+ headers: { 'Content-Encoding': 'gzip', 'Content-Type': 'application/json' },+ body: gzipped,+ })++ expect(Buffer.from(seen[0].body, 'utf8').length).toBeGreaterThan(0)+ })++ it.each([['/api/push_subscriptions'], ['/api/push_subscriptions/']])('serves %s', async (path) => {+ const response = await post(path, { body: '{}' })++ expect(response.status).toEqual(200)+ })++ it.each([['/api/push_subscriptions/extra'], ['//']])('does not serve %s', async (path) => {+ const response = await post(path, { body: '{}' })++ expect(response.status).toEqual(404)+ expect(seen).toEqual([])+ })++ it('answers a preflight without calling the service', async () => {+ const response = await internalFetch(`${base}/api/push_subscriptions/`, {+ method: 'OPTIONS',+ headers: { Origin: 'https://app.example.com' },+ })++ expect(response.status).toEqual(200)+ expect(response.headers['access-control-allow-origin']).toEqual('*')+ expect(seen).toEqual([])+ })++ it('advertises the verbs it serves, including the one django omits', async () => {+ // A browser preflight for the unregister call is refused when DELETE is missing here.+ const response = await internalFetch(`${base}/api/push_subscriptions/`, {+ method: 'OPTIONS',+ headers: { Origin: 'https://app.example.com' },+ })++ expect(response.headers['access-control-allow-methods']).toEqual('GET, POST, DELETE, OPTIONS')+ })++ it('never lets another site make a credentialed call', async () => {+ const response = await post('/api/push_subscriptions/', {+ headers: { Origin: 'https://evil.example' },+ body: '{}',+ })++ expect(response.headers['access-control-allow-origin']).toEqual('*')+ expect(response.headers['access-control-allow-credentials']).toBeUndefined()+ })++ it('stops reading once a body passes the limit, and still answers', async () => {+ answer = { status: 413, body: { type: 'validation_error', code: 'request_too_large', detail: 'x', attr: null } }+ const oversized = Buffer.alloc(64 * 1024, 'a')++ const response = await post('/api/push_subscriptions/', { body: oversized })++ expect(response.status).toEqual(413)+ // One byte past the limit is enough for the service to see it is over; nothing larger is held.+ expect(seen[0].body.length).toEqual(16 * 1024 + 1)+ })++ it('returns the rejection body the service produced', async () => {+ answer = {+ status: 401,+ body: {+ type: 'authentication_error',+ code: 'invalid_api_key',+ detail: 'Invalid project token.',+ attr: null,+ },+ rejection: { code: 'invalid_api_key', apiKeyFingerprint: 'abc123' },+ }++ const response = await post('/api/push_subscriptions/', { body: '{}' })++ expect(response.status).toEqual(401)+ expect(await response.json()).toEqual({+ type: 'authentication_error',+ code: 'invalid_api_key',+ detail: 'Invalid project token.',+ attr: null,+ })+ })++ it('counts a request the service throws on as a 500', async () => {+ const failedRequests = async (): Promise<number> => {+ const metric = await register.getSingleMetric('push_subscription_request_duration_seconds')!.get()+ return metric.values+ .filter(+ (v) => 'metricName' in v && String(v.metricName).endsWith('_count') && v.labels.status === '500'+ )+ .reduce((sum, v) => sum + v.value, 0)+ }+ const before = await failedRequests()+ failure = new Error('postgres is down')++ const response = await post('/api/push_subscriptions/', { body: '{}' })++ expect(response.status).toEqual(500)+ expect((await failedRequests()) - before).toEqual(1)+ })++ it('does not hang when the client disconnects mid-body', async () => {+ // Announce a body and then drop the socket. Without a close handler the read never settles+ // and the handler is retained for the life of the process.+ await new Promise<void>((resolve) => {+ const req = httpRequest(+ {+ host: '127.0.0.1',+ port: (server.address() as AddressInfo).port,+ path: '/api/push_subscriptions/',+ method: 'POST',+ },+ () => undefined+ )+ req.setHeader('Content-Length', '1000')+ req.on('error', () => resolve())+ req.write('x'.repeat(10))+ req.destroy()+ setTimeout(resolve, 100)+ })++ const response = await post('/api/push_subscriptions/', { body: '{}' })+ expect(response.status).toEqual(200)+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.tsnew file mode 100644index 000000000000..4a1592d6d096--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions-http.ts@@ -0,0 +1,217 @@+import { IncomingMessage, ServerResponse } from 'http'+import { Counter, Histogram } from 'prom-client'++import { logger } from '~/common/utils/logger'++import { MAX_BODY_BYTES, PushSubscriptionsService } from './push-subscriptions.service'++/** Names match what Django exposes, so its dashboards and alerts survive a cutover. prometheus_client+ * appends `_total` in the exposition format and prom-client does not, hence the explicit suffix. */+const rejectionCounter = new Counter({+ name: 'push_subscription_rejection_total',+ help: 'Device registration requests rejected, by reason and HTTP method.',+ labelNames: ['code', 'method'],+})++const discardCounter = new Counter({+ name: 'push_subscription_discarded_total',+ help: 'Device registrations acknowledged but not stored, by reason.',+ labelNames: ['reason'],+})++const identityVerificationCounter = new Counter({+ name: 'push_subscription_identity_verification_total',+ help: 'Outcome of push subscription identity token verification.',+ labelNames: ['mode', 'operation', 'outcome'],+})++const requestDuration = new Histogram({+ name: 'push_subscription_request_duration_seconds',+ help: 'Time to answer a device registration request, by method and status.',+ labelNames: ['method', 'status'],+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],+})++const PATHS = new Set(['/api/push_subscriptions/', '/api/push_subscriptions'])++const DISCARD_LOG_WINDOW_MS = 60_000+let discardLogWindow = 0+let discardedTeamsThisWindow = new Set<number>()++/** Handles `/api/push_subscriptions/` on a plain node http server.+ *+ * Deliberately not built on the plugin server's `ultimate-express`: that framework discards the+ * request body on DELETE, and DELETE with a JSON body is how every released SDK unregisters a+ * device. Verified against ultimate-express 2.0.9 — content-length arrives, the stream never emits,+ * and POST, PUT and PATCH are all unaffected, so it is specific to the verb this endpoint needs.+ */+export function createPushSubscriptionsHandler(service: PushSubscriptionsService) {+ return async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const rawUrl = req.url ?? '/'+ const queryStart = rawUrl.indexOf('?')+ // Matched on the raw path, so dot segments and other spellings that URL parsing would+ // normalize onto this path are not served.+ const path = queryStart === -1 ? rawUrl : rawUrl.slice(0, queryStart)+ if (!PATHS.has(path)) {+ res.writeHead(404).end()+ return+ }+ let query: URLSearchParams+ try {+ query = new URLSearchParams(queryStart === -1 ? '' : rawUrl.slice(queryStart + 1))+ } catch {+ query = new URLSearchParams()+ }++ applyCors(req, res)++ if (req.method === 'OPTIONS') {+ // Django answers the preflight with an empty HttpResponse, which carries its default+ // content type. Matching it keeps the preflight byte-identical to today's.+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end('')+ return+ }++ const startedAt = process.hrtime.bigint()+ const methodLabel = req.method === 'POST' || req.method === 'DELETE' ? req.method : 'other'+ const body = await readBody(req)+ let result: Awaited<ReturnType<PushSubscriptionsService['handle']>>+ try {+ result = await service.handle({+ method: req.method ?? 'GET',+ body,+ contentType: header(req, 'content-type'),+ contentEncoding: header(req, 'content-encoding'),+ query,+ })+ } catch (error) {+ // The server answers a throw with a 500, and the error-rate alert reads this histogram.+ requestDuration.observe(+ { method: methodLabel, status: '500' },+ Number(process.hrtime.bigint() - startedAt) / 1e9+ )+ throw error+ }++ if (result.rejection) {+ rejectionCounter.inc({ code: result.rejection.code, method: methodLabel })+ const sdk = parseUserAgentSdk(header(req, 'user-agent'))+ logger.warn('push_subscription_rejected', {+ code: result.rejection.code,+ status_code: result.status,+ method: req.method,+ team_id: result.rejection.teamId ?? null,+ // Client-supplied, so bounded to keep a hostile value from bloating the log line.+ app_id: typeof result.rejection.appId === 'string' ? result.rejection.appId.slice(0, 128) : null,+ detail: result.rejection.detail ?? null,+ sdk_name: sdk.name,+ sdk_version: sdk.version,+ api_key_fingerprint: result.rejection.apiKeyFingerprint ?? null,+ // Django attaches the traceback for the paths that swallow an exception, so a 500 is+ // diagnosable from this one event rather than only from the counter.+ error: result.rejection.error ? String(result.rejection.error) : null,+ })+ }++ if (result.identityVerification) {+ identityVerificationCounter.inc(result.identityVerification)+ }++ if (result.discarded) {+ discardCounter.inc({ reason: result.discarded.reason })+ if (isFirstDiscardInWindow(result.discarded.teamId)) {+ logger.info('push_subscription_discarded', {+ reason: result.discarded.reason,+ team_id: result.discarded.teamId,+ app_id: result.discarded.appId,+ })+ }+ }++ requestDuration.observe(+ { method: methodLabel, status: String(result.status) },+ Number(process.hrtime.bigint() - startedAt) / 1e9+ )++ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ }+}++function header(req: IncomingMessage, name: string): string | undefined {+ const value = req.headers[name]+ return Array.isArray(value) ? value[0] : value+}++/** Reads one byte past the limit, which is what lets the service answer 413 without holding a+ * larger body in memory. */+function readBody(req: IncomingMessage): Promise<Buffer> {+ return new Promise((resolve) => {+ const chunks: Buffer[] = []+ let size = 0+ let settled = false+ const finish = (): void => {+ if (settled) {+ return+ }+ settled = true+ resolve(Buffer.concat(chunks).subarray(0, MAX_BODY_BYTES + 1))+ }+ req.on('data', (chunk: Buffer) => {+ if (size <= MAX_BODY_BYTES) {+ chunks.push(chunk)+ size += chunk.length+ }+ })+ req.on('end', finish)+ req.on('error', finish)+ // A client that disconnects mid-body emits neither, leaking the handler without this.+ req.on('aborted', finish)+ req.on('close', finish)+ })+}++function applyCors(req: IncomingMessage, res: ServerResponse): void {+ if (!header(req, 'origin')) {+ return+ }+ // A wildcard, as Django answers, and no credentials: nothing here reads a cookie, and a+ // reflected origin with credentials would let any site make credentialed calls.+ res.setHeader('Access-Control-Allow-Origin', '*')+ // Django advertises only GET, POST and OPTIONS here while accepting DELETE, so a browser+ // preflight for the unregister call is refused. Native SDKs never preflight, which is why that+ // has gone unnoticed; this deliberately advertises the verb the endpoint actually serves.+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS')+ res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')+ res.setHeader('Vary', 'Origin')+}++function isFirstDiscardInWindow(teamId: number): boolean {+ const window = Math.floor(Date.now() / DISCARD_LOG_WINDOW_MS)+ // Replaced rather than added to, so the set holds one window instead of every team seen.+ if (window !== discardLogWindow) {+ discardLogWindow = window+ discardedTeamsThisWindow = new Set()+ }+ if (discardedTeamsThisWindow.has(teamId)) {+ return false+ }+ discardedTeamsThisWindow.add(teamId)+ return true+}++function parseUserAgentSdk(userAgent?: string): { name: string | null; version: string | null } {+ // PostHog SDKs identify as "posthog-<name>/<version>". Each part is bounded, others ignored.+ if (!userAgent || !userAgent.startsWith('posthog-')) {+ return { name: null, version: null }+ }+ const separator = userAgent.indexOf('/')+ if (separator === -1) {+ return { name: null, version: null }+ }+ const version = userAgent.slice(separator + 1).split(/\s/)[0]+ if (!version) {+ return { name: null, version: null }+ }+ return { name: userAgent.slice(0, separator).slice(0, 64), version: version.slice(0, 32) }+}diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.tsnew file mode 100644index 000000000000..a4d29b58d8af--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.test.ts@@ -0,0 +1,422 @@+import { gzipSync } from 'zlib'++import { PushSubscriptionsService } from './push-subscriptions.service'++describe('PushSubscriptionsService', () => {+ const team = { id: 7, api_token: 'phc_real', secret_api_token: null }++ let teamManager: any+ let postgres: any+ let capture: any+ let integrationRows: { kind: string; config: Record<string, any> }[]+ let appIdQueries: number+ let integrationQueries: number+ let service: PushSubscriptionsService++ const request = (body: unknown, method = 'POST', extra: Record<string, any> = {}): any => ({+ method,+ body: Buffer.isBuffer(body) ? body : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body)),+ ...extra,+ })++ const valid = {+ api_key: 'phc_real',+ distinct_id: 'user-1',+ device_token: 'device-1',+ app_id: 'my-firebase-project',+ }++ beforeEach(() => {+ integrationRows = [{ kind: 'firebase', config: { project_id: 'my-firebase-project' } }]+ appIdQueries = 0+ integrationQueries = 0+ teamManager = {+ getTeamByToken: jest.fn((token: string) => Promise.resolve(token === 'phc_real' ? team : null)),+ }+ postgres = {+ query: jest.fn((_use: unknown, query: string) => {+ if (query.includes('kind = ANY')) {+ appIdQueries += 1+ return Promise.resolve({ rows: integrationRows })+ }+ integrationQueries += 1+ return Promise.resolve({ rows: integrationRows })+ }),+ }+ capture = { capture: jest.fn(() => Promise.resolve()) }+ service = new PushSubscriptionsService(+ teamManager,+ postgres,+ { encrypt: (value: string) => `enc:${value}` } as any,+ capture,+ 'secret'+ )+ })++ const capturedProperties = (): any => capture.capture.mock.calls[0][0].properties++ it('stores the encrypted device token under a key for the device, the key django writes', async () => {+ const result = await service.handle(request(valid))++ expect(result.status).toEqual(200)+ expect(result.body).toEqual({ distinct_id: 'user-1' })+ expect(capturedProperties().$set).toEqual({+ '$device_push_subscription_my-firebase-project:03204de92e11fc8c': 'enc:device-1',+ })+ })++ it('reports a rejected capture rather than telling the SDK the token was stored', async () => {+ // The SDK marks a registration delivered on a 2xx and stops re-sending it, so a capture that+ // did not happen has to surface as an error or the device is never registered.+ capture.capture.mockRejectedValue(new Error('capture returned 503'))++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(500)+ expect(result.body).toMatchObject({ code: 'capture_failed' })+ })++ it('reports a capture that threw', async () => {+ capture.capture.mockRejectedValue(new Error('connection refused'))++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(500)+ expect(result.rejection?.error).not.toBeUndefined()+ })++ it('tells a project with no channel why nothing was stored', async () => {+ // SDKs register on every app open, so a 4xx here would turn every such project into an+ // error firehose that never stops. The body carries what the status code cannot.+ integrationRows = []++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(200)+ expect(result.body).toEqual({+ distinct_id: 'user-1',+ stored: false,+ push_enabled: false,+ reason: 'no_push_channel_for_app_id',+ detail: expect.stringContaining("no push channel for app_id 'my-firebase-project'"),+ })+ expect(capture.capture).not.toHaveBeenCalled()+ })++ it('unsets the device and the app-wide key on DELETE even when the channel is gone', async () => {+ integrationRows = []++ const result = await service.handle(request(valid, 'DELETE'))++ expect(result.status).toEqual(200)+ expect(capturedProperties().$unset).toEqual([+ '$device_push_subscription_my-firebase-project:03204de92e11fc8c',+ '$device_push_subscription_my-firebase-project',+ ])+ })++ const inflatesPastLimit = gzipSync(Buffer.from(JSON.stringify({ ...valid, pad: 'a'.repeat(64 * 1024) })))+ it.each([+ ['a raw body over the size limit', Buffer.alloc(16 * 1024 + 1, 'a'), undefined],+ ['a small gzip body that inflates past the limit', inflatesPastLimit, 'gzip'],+ ['the same body sent without declaring gzip', inflatesPastLimit, undefined],+ ])('rejects %s as too large', async (_name, body, contentEncoding) => {+ const result = await service.handle({ method: 'POST', body, contentEncoding })++ expect(result.status).toEqual(413)+ expect(result.body).toMatchObject({ code: 'request_too_large' })+ expect(capture.capture).not.toHaveBeenCalled()+ })++ it('accepts a body exactly at the size limit', async () => {+ const padding = 'a'.repeat(16 * 1024 - JSON.stringify({ ...valid, pad: '' }).length)+ const body = Buffer.from(JSON.stringify({ ...valid, pad: padding }))+ expect(body.length).toEqual(16 * 1024)++ const result = await service.handle({ method: 'POST', body })++ expect(result.status).toEqual(200)+ })++ it('names each missing field and how it was missing', async () => {+ const result = await service.handle(request({ api_key: 'phc_real', device_token: '', app_id: 12 }))++ expect(result.status).toEqual(400)+ expect(result.rejection?.detail).toEqual('distinct_id:absent,device_token:empty,app_id:invalid')+ })++ it.each([+ ['api_key', { api_key: 'phc_real' }],+ ['token', { token: 'phc_real' }],+ ['$token', { $token: 'phc_real' }],+ ['properties.token', { properties: { token: 'phc_real' } }],+ ])('accepts the project token under %s', async (_name, carrier) => {+ const result = await service.handle(request({ ...valid, api_key: undefined, ...carrier }))++ expect(result.status).toEqual(200)+ })++ it.each([+ ['a string', 'not-an-object'],+ ['an array', ['token']],+ ['a number', 7],+ ])('treats a non-object `properties` of %s as carrying no token', async (_name, properties) => {+ // Django calls .get on it and answers 500. A request that named no token should be told so.+ const result = await service.handle(request({ ...valid, api_key: undefined, properties }))++ expect(result.status).toEqual(401)+ expect(result.body).toMatchObject({ code: 'missing_api_key' })+ })++ it('refuses a token that resolves to a team without being its project token', async () => {+ teamManager.getTeamByToken.mockImplementation((token: string) =>+ Promise.resolve(token === 'phc_real' || token === 'phc_alias' ? team : null)+ )++ const result = await service.handle(request({ ...valid, api_key: 'phc_alias' }))++ expect(result.status).toEqual(401)+ expect(result.body).toMatchObject({ code: 'invalid_api_key' })+ expect(capture.capture).not.toHaveBeenCalled()+ })++ it('stops asking the database for a token that resolved to nothing', async () => {+ const first = await service.handle(request({ ...valid, api_key: 'phc_unknown' }))+ const second = await service.handle(request({ ...valid, api_key: 'phc_unknown' }))++ expect(first.status).toEqual(401)+ expect(second.status).toEqual(401)+ expect(teamManager.getTeamByToken).toHaveBeenCalledTimes(1)+ })++ it('reads the channel per request so a policy change applies immediately', async () => {+ // The row carries the identity verification mode. A cached copy would keep answering+ // `disabled` after an admin turns verification on, and store registrations unverified.+ await service.handle(request(valid))+ integrationRows = [+ {+ kind: 'firebase',+ config: { project_id: 'my-firebase-project', push_identity_verification: 'required' },+ },+ ]++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(401)+ expect(result.body).toMatchObject({ code: 'identity_verification_failed' })+ })++ describe('the configured app_id cache', () => {+ it('skips the channel lookup for an app_id the team has never configured', async () => {+ const first = await service.handle(request({ ...valid, app_id: 'never-configured' }))+ const queriesAfterFirst = integrationQueries+ const second = await service.handle(request({ ...valid, app_id: 'never-configured' }))++ expect(first.body).toMatchObject({ reason: 'no_push_channel_for_app_id' })+ expect(second.body).toMatchObject({ reason: 'no_push_channel_for_app_id' })+ expect(appIdQueries).toEqual(1)+ // The second request answered from the cached list rather than querying again.+ expect(integrationQueries).toEqual(queriesAfterFirst)+ })++ it('still looks the channel up for an app_id the team has configured', async () => {+ await service.handle(request(valid))+ await service.handle(request(valid))++ expect(integrationQueries).toEqual(2)+ })++ it('falls through to the real lookup when the cached list cannot be read', async () => {+ // "Don't know" must not discard a registration the team is entitled to.+ postgres.query.mockImplementation((_use: unknown, query: string) => {+ if (query.includes('kind = ANY')) {+ return Promise.reject(new Error('read replica down'))+ }+ return Promise.resolve({ rows: integrationRows })+ })++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(200)+ expect(result.body).toEqual({ distinct_id: 'user-1' })+ })+ })++ describe('request decoding', () => {+ it('accepts a gzipped body', async () => {+ const result = await service.handle(+ request(gzipSync(Buffer.from(JSON.stringify(valid))), 'POST', { contentEncoding: 'gzip' })+ )++ expect(result.status).toEqual(200)+ })++ it('accepts a gzipped body that did not declare itself', async () => {+ const result = await service.handle(request(gzipSync(Buffer.from(JSON.stringify(valid)))))++ expect(result.status).toEqual(200)+ })++ it('accepts the compression named in the query string', async () => {+ const result = await service.handle(+ request(gzipSync(Buffer.from(JSON.stringify(valid))), 'POST', {+ query: new URLSearchParams('compression=gzip-js'),+ })+ )++ expect(result.status).toEqual(200)+ })++ it('accepts a base64 body', async () => {+ const encoded = Buffer.from(JSON.stringify(valid)).toString('base64')++ const result = await service.handle(request(Buffer.from(encoded)))++ expect(result.status).toEqual(200)+ })++ it('accepts a form-encoded body carrying the token as a field', async () => {+ const form = new URLSearchParams({+ api_key: 'phc_real',+ data: JSON.stringify({ distinct_id: 'user-1', device_token: 'device-1', app_id: valid.app_id }),+ })++ const result = await service.handle(+ request(Buffer.from(form.toString()), 'POST', {+ contentType: 'application/x-www-form-urlencoded',+ })+ )++ expect(result.status).toEqual(200)+ })++ it.each([+ ['malformed JSON', '{"api_key":'],+ ['an array body', '[]'],+ ['a bare string', '"a string"'],+ ['an empty body', ''],+ ['a truncated gzip stream', gzipSync(Buffer.from('{"a":1}')).subarray(0, 8).toString('latin1')],+ ])('rejects %s as an invalid body', async (_name, body) => {+ const result = await service.handle(request(Buffer.from(body, 'latin1')))++ expect(result.status).toEqual(400)+ expect(result.body).toMatchObject({ code: 'invalid_json' })+ })++ it('reads a body carrying the constants python accepts and javascript does not', async () => {+ const body = `{"api_key":"phc_real","distinct_id":"user-1","device_token":"device-1","app_id":"${valid.app_id}","retries":NaN}`++ const result = await service.handle(request(Buffer.from(body)))++ expect(result.status).toEqual(200)+ })++ it('does not rewrite a string whose contents look like those constants', async () => {+ const result = await service.handle(request({ ...valid, distinct_id: 'NaN' }))++ expect(result.status).toEqual(200)+ expect(capturedProperties().$set).not.toBeUndefined()+ expect(capture.capture.mock.calls[0][0].distinctId).toEqual('NaN')+ })+ })++ describe('hostile and unusual values', () => {+ it('keys the property on a unicode app id', async () => {+ const appId = 'com.example.🚀café'+ integrationRows = [{ kind: 'firebase', config: { project_id: appId } }]++ const result = await service.handle(request({ ...valid, app_id: appId }))++ expect(result.status).toEqual(200)+ expect(capturedProperties().$set).toEqual({+ [`$device_push_subscription_${appId}:03204de92e11fc8c`]: 'enc:device-1',+ })+ })++ it('does not let a body define fields through the prototype', async () => {+ const body = '{"__proto__":{"api_key":"phc_real"},"distinct_id":"user-1"}'++ const result = await service.handle(request(Buffer.from(body)))++ expect(result.status).toEqual(401)+ expect(result.body).toMatchObject({ code: 'missing_api_key' })+ expect(({} as any).api_key).toBeUndefined()+ })++ it('does not read a required field off the prototype chain', async () => {+ const body = '{"api_key":"phc_real","distinct_id":"user-1","device_token":"device-1"}'++ const result = await service.handle(request(Buffer.from(body)))++ expect(result.rejection?.detail).toEqual('app_id:absent')+ })++ it('takes the last value when a field is repeated', async () => {+ const body = `{"api_key":"phc_real","distinct_id":"first","distinct_id":"second","device_token":"device-1","app_id":"${valid.app_id}"}`++ const result = await service.handle(request(Buffer.from(body)))++ expect(result.body).toEqual({ distinct_id: 'second' })+ })++ it.each([+ ['GET', 405],+ ['PUT', 405],+ ['PATCH', 405],+ ['TRACE', 405],+ ])('refuses %s', async (method, status) => {+ const result = await service.handle(request(valid, method))++ expect(result.status).toEqual(status)+ expect(result.body).toMatchObject({ code: 'method_not_allowed' })+ })+ })++ describe('identity verification', () => {+ beforeEach(() => {+ integrationRows = [+ {+ kind: 'firebase',+ config: { project_id: 'my-firebase-project', push_identity_verification: 'optional' },+ },+ ]+ })++ it('stores an unverified registration in optional mode and records the outcome', async () => {+ const result = await service.handle(request(valid))++ expect(result.status).toEqual(200)+ expect(result.identityVerification).toEqual({+ mode: 'optional',+ operation: 'register',+ outcome: 'unverified',+ })+ })++ it('records the outcome for an unregister too', async () => {+ const result = await service.handle(request(valid, 'DELETE'))++ expect(result.identityVerification).toMatchObject({ operation: 'unregister' })+ })++ it('takes the strictest mode when two channels share an app_id', async () => {+ // Nothing constrains two integrations to one app_id, so a lax duplicate must not be able+ // to downgrade a sibling's required policy.+ integrationRows = [+ {+ kind: 'firebase',+ config: { project_id: 'my-firebase-project', push_identity_verification: 'disabled' },+ },+ {+ kind: 'apns',+ config: { bundle_id: 'my-firebase-project', push_identity_verification: 'required' },+ },+ ]++ const result = await service.handle(request(valid))++ expect(result.status).toEqual(401)+ expect(result.body).toMatchObject({ code: 'identity_verification_failed' })+ })+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.tsnew file mode 100644index 000000000000..073b131981d8--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts@@ -0,0 +1,378 @@+import { createHmac } from 'crypto'+import { LRUCache } from 'lru-cache'++import { EncryptedFields } from '~/cdp/utils/encryption-utils'+import { DEVICE_SUBSCRIPTION_PREFIX, deviceSubscriptionKey } from '~/cdp/utils/push-subscription-utils'+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'++import { verifyPushIdentityToken } from './identity-token'+import { ProjectTokenLookup } from './project-token-lookup'+import { PushCaptureService } from './push-capture'+import { InflatedBodyTooLargeError, RawRequest, decodeRequest } from './request-decoding'++export type PushRejectionCode =+ | 'method_not_allowed'+ | 'request_too_large'+ | 'invalid_json'+ | 'missing_api_key'+ | 'invalid_api_key'+ | 'missing_fields'+ | 'identity_verification_failed'+ | 'capture_failed'++export type PushErrorType = 'validation_error' | 'authentication_error' | 'server_error'++/** The body shape Django's `generate_exception_response` produces, which SDKs already parse. */+export type PushErrorBody = {+ type: PushErrorType+ code: PushRejectionCode+ detail: string+ attr: null+}++export type PushSuccessBody = {+ distinct_id: string+ stored?: false+ push_enabled?: false+ reason?: string+ detail?: string+}++export type PushHandlerResult = {+ status: number+ body: PushErrorBody | PushSuccessBody+ /** Set on a rejection so the caller can log and count it with the same fields Django uses. */+ rejection?: {+ code: PushRejectionCode+ teamId?: number+ appId?: string | null+ detail?: string+ apiKeyFingerprint?: string+ error?: unknown+ }+ discarded?: { teamId: number; appId: string; reason: 'no_integration' }+ identityVerification?: {+ mode: 'optional' | 'required'+ operation: 'register' | 'unregister'+ outcome: 'verified' | 'unverified'+ }+}++export const MAX_BODY_BYTES = 16 * 1024++const VERIFICATION_MODE_PRECEDENCE: Record<string, number> = { disabled: 0, optional: 1, required: 2 }++type PushIntegration = { config: Record<string, any> }++/** In-process rather than Redis: the token is request-controlled and the endpoint is public, so a+ * shared key per submitted value would let anyone evict real entries. */+const INVALID_TOKEN_CACHE_TTL_MS = 60_000+const INVALID_TOKEN_CACHE_SIZE = 2048++/** Keyed on the team alone: keying on the request's app_id would let one public project token mint+ * unbounded entries. */+const CONFIGURED_APP_IDS_CACHE_TTL_MS = 60_000+const CONFIGURED_APP_IDS_CACHE_SIZE = 10_000++const PUSH_INTEGRATION_KINDS = ['firebase', 'apns']++export class PushSubscriptionsService {+ private invalidTokens: LRUCache<string, true>+ private configuredAppIdsCache: LRUCache<number, string[]>++ constructor(+ private projectTokens: Pick<ProjectTokenLookup, 'getTeamByToken'>,+ private postgres: PostgresRouter,+ private encryptedFields: EncryptedFields,+ private capture: PushCaptureService,+ private secretKey: string+ ) {+ this.invalidTokens = new LRUCache({ max: INVALID_TOKEN_CACHE_SIZE, ttl: INVALID_TOKEN_CACHE_TTL_MS })+ this.configuredAppIdsCache = new LRUCache({+ max: CONFIGURED_APP_IDS_CACHE_SIZE,+ ttl: CONFIGURED_APP_IDS_CACHE_TTL_MS,+ })+ }++ private apiKeyFingerprint(apiKey: string): string {+ // Keyed with the server secret so a fingerprint cannot be precomputed for a guessed token.+ return createHmac('sha256', this.secretKey).update(apiKey).digest('hex').slice(0, 16)+ }++ public async handle(request: RawRequest): Promise<PushHandlerResult> {+ if (request.method !== 'POST' && request.method !== 'DELETE') {+ return reject('method_not_allowed', 405, 'validation_error', 'Only POST and DELETE requests are supported.')+ }++ if (request.body.length > MAX_BODY_BYTES) {+ return reject('request_too_large', 413, 'validation_error', 'Request body too large.')+ }++ let data: Record<string, any>+ let form: URLSearchParams | undefined+ try {+ const decoded = decodeRequest(request)+ form = decoded.form+ if (typeof decoded.data !== 'object' || decoded.data === null || Array.isArray(decoded.data)) {+ return reject('invalid_json', 400, 'validation_error', 'Invalid JSON body.')+ }+ data = decoded.data as Record<string, any>+ } catch (error) {+ if (error instanceof InflatedBodyTooLargeError) {+ return reject('request_too_large', 413, 'validation_error', 'Request body too large.')+ }+ return reject('invalid_json', 400, 'validation_error', 'Invalid JSON body.')+ }++ const apiKey = getToken(data, form)+ if (!apiKey) {+ return reject(+ 'missing_api_key',+ 401,+ 'authentication_error',+ 'Project token not provided. You can find your project token in your PostHog project settings.'+ )+ }++ const fingerprint = this.apiKeyFingerprint(apiKey)+ const appIdField = typeof data.app_id === 'string' ? data.app_id : null++ if (this.invalidTokens.has(fingerprint)) {+ return reject('invalid_api_key', 401, 'authentication_error', 'Invalid project token.', {+ appId: appIdField,+ apiKeyFingerprint: fingerprint,+ })+ }++ const team = await this.projectTokens.getTeamByToken(apiKey)+ if (!team || team.api_token !== apiKey) {+ this.invalidTokens.set(fingerprint, true)+ return reject('invalid_api_key', 401, 'authentication_error', 'Invalid project token.', {+ appId: appIdField,+ apiKeyFingerprint: fingerprint,+ })+ }++ const missingFields = (['distinct_id', 'device_token', 'app_id'] as const).filter(+ (field) => !data[field] || typeof data[field] !== 'string'+ )+ if (missingFields.length > 0) {+ // absent vs empty vs invalid separates contract drift from a client passing a bad value.+ const detail = missingFields+ .map((field) => {+ const state = !hasOwn(data, field) ? 'absent' : data[field] === '' ? 'empty' : 'invalid'+ return `${field}:${state}`+ })+ .join(',')+ return reject(+ 'missing_fields',+ 400,+ 'validation_error',+ `Missing required fields: ${missingFields.join(', ')}.`,+ { teamId: team.id, detail }+ )+ }++ const distinctId = data.distinct_id as string+ const deviceToken = data.device_token as string+ const appId = data.app_id as string++ const integrations = await this.findIntegrations(team.id, appId)++ // SDKs auto-register on every app open, so a 4xx here turns the whole fleet into an error+ // firehose. DELETE falls through: logout must clear a subscription stored earlier.+ if (integrations.length === 0 && request.method === 'POST') {+ return {+ status: 200,+ body: {+ distinct_id: distinctId,+ stored: false,+ push_enabled: false,+ // Without this a developer whose token goes nowhere cannot tell the difference+ // from a working registration.+ reason: 'no_push_channel_for_app_id',+ detail:+ `This project has no push channel for app_id '${appId}'. The device token was ` ++ 'not stored. Add a push channel whose Firebase project id or APNs bundle id ' ++ 'matches this app_id, and check the project the SDK is sending to.',+ },+ discarded: { teamId: team.id, appId, reason: 'no_integration' },+ }+ }++ const operation = request.method === 'POST' ? 'register' : 'unregister'+ const verificationMode = strictestVerificationMode(integrations)+ let identityVerification: PushHandlerResult['identityVerification']+ if (verificationMode === 'optional' || verificationMode === 'required') {+ const identityToken = data.identity_token+ const publicKeys = integrations.flatMap(+ (integration) => (integration.config.push_identity_public_keys as string[] | undefined) ?? []+ )+ const verified =+ typeof identityToken === 'string' &&+ verifyPushIdentityToken({+ token: identityToken,+ distinctId,+ appId,+ publicKeys,+ })+ identityVerification = {+ mode: verificationMode,+ operation,+ outcome: verified ? 'verified' : 'unverified',+ }+ if (!verified && verificationMode === 'required') {+ return {+ ...reject(+ 'identity_verification_failed',+ 401,+ 'authentication_error',+ 'A valid identity token is required for this device. Your backend must sign a ' ++ 'short-lived token for the signed-in user with the key configured for this ' ++ "channel's identity verification.",+ { teamId: team.id, appId }+ ),+ identityVerification,+ }+ }+ }++ const propertyKey = deviceSubscriptionKey(appId, deviceToken)+ // $unset of an absent property is a no-op, so DELETE is idempotent. Logout also clears the+ // app-wide key: a device cannot tell whether that key holds its own token, and leaving it+ // would keep a logged-out device receiving notifications.+ const properties =+ request.method === 'POST'+ ? { $set: { [propertyKey]: this.encryptedFields.encrypt(deviceToken) } }+ : { $unset: [propertyKey, `${DEVICE_SUBSCRIPTION_PREFIX}${appId}`] }++ try {+ // An SDK told the registration was stored stops re-sending it, so a capture that did+ // not happen has to surface here.+ await this.capture.capture({+ token: team.api_token,+ event: '$set',+ distinctId,+ properties: { ...properties, $process_person_profile: true },+ })+ } catch (error) {+ return {+ ...reject(+ 'capture_failed',+ 500,+ 'server_error',+ request.method === 'POST'+ ? 'Failed to store push subscription.'+ : 'Failed to remove push subscription.',+ { teamId: team.id, appId, error }+ ),+ identityVerification,+ }+ }++ return { status: 200, body: { distinct_id: distinctId }, identityVerification }+ }++ private async findIntegrations(teamId: number, appId: string): Promise<PushIntegration[]> {+ // null means "don't know", so a failed lookup falls through to the real query rather than+ // discarding a registration the team is entitled to.+ const configured = await this.configuredAppIds(teamId)+ if (configured !== null && !configured.includes(appId)) {+ return []+ }+ return await this.fetchIntegrations(teamId, appId)+ }++ private async configuredAppIds(teamId: number): Promise<string[] | null> {+ const cached = this.configuredAppIdsCache.get(teamId)+ if (cached) {+ return cached+ }+ try {+ const { rows } = await this.postgres.query<{ kind: string; config: Record<string, any> }>(+ PostgresUse.COMMON_READ,+ `SELECT kind, config FROM posthog_integration WHERE team_id = $1 AND kind = ANY($2)`,+ [teamId, PUSH_INTEGRATION_KINDS],+ 'fetchConfiguredPushAppIds'+ )+ const appIds = rows+ .map((row) => (row.kind === 'firebase' ? row.config?.project_id : row.config?.bundle_id))+ .filter((appId): appId is string => typeof appId === 'string')+ this.configuredAppIdsCache.set(teamId, appIds)+ return appIds+ } catch {+ return null+ }+ }++ // Resolved from the app_id alone, not the device platform, so a device can register with either+ // provider. Read per request: the row carries the verification policy, and a cached copy would+ // keep answering `disabled` after an admin turns verification on.+ private async fetchIntegrations(teamId: number, appId: string): Promise<PushIntegration[]> {+ const { rows } = await this.postgres.query<{ config: Record<string, any> }>(+ PostgresUse.COMMON_READ,+ `SELECT config FROM posthog_integration+ WHERE team_id = $1+ AND ((kind = 'firebase' AND config->>'project_id' = $2)+ OR (kind = 'apns' AND config->>'bundle_id' = $2))`,+ [teamId, appId],+ 'fetchPushIntegrations'+ )+ return rows.map((row) => ({ config: row.config ?? {} }))+ }+}++function hasOwn(data: Record<string, any>, field: string): boolean {+ return Object.prototype.hasOwnProperty.call(data, field)+}++function strictestVerificationMode(integrations: PushIntegration[]): string {+ let mode = 'disabled'+ for (const integration of integrations) {+ const candidate = (integration.config.push_identity_verification as string | undefined) ?? 'disabled'+ if ((VERIFICATION_MODE_PRECEDENCE[candidate] ?? 0) > (VERIFICATION_MODE_PRECEDENCE[mode] ?? 0)) {+ mode = candidate+ }+ }+ return mode+}++/** The order Django's `get_token` uses for a body-carrying request. Query parameters are not read:+ * Django only looks at those for GET, and this endpoint takes POST and DELETE. */+function getToken(data: Record<string, any>, form?: URLSearchParams): string | null {+ for (const value of [form?.get('api_key'), form?.get('token')]) {+ if (value) {+ return value+ }+ }+ // Django reads `properties.token` with `.get`, which raises when properties is not a mapping and+ // answers the request with a 500. Treating it as absent answers 401 instead, which is what the+ // client should have been told.+ const properties = typeof data.properties === 'object' && data.properties !== null ? data.properties : {}+ for (const value of [data.$token, data.token, data.api_key, properties.token]) {+ if (typeof value === 'string' && value) {+ return value+ }+ }+ return null+}++function reject(+ code: PushRejectionCode,+ status: number,+ type: PushErrorType,+ detail: string,+ extra: {+ teamId?: number+ appId?: string | null+ detail?: string+ apiKeyFingerprint?: string+ error?: unknown+ } = {}+): PushHandlerResult {+ return {+ status,+ body: { type, code, detail, attr: null },+ rejection: { code, ...extra },+ }+}diff --git a/nodejs/src/messaging/push-subscriptions/request-decoding.test.ts b/nodejs/src/messaging/push-subscriptions/request-decoding.test.tsnew file mode 100644index 000000000000..302e86fb3a17--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/request-decoding.test.ts@@ -0,0 +1,138 @@+import { gzipSync } from 'zlib'++import {+ RequestParsingError,+ UnspecifiedCompressionFallbackParsingError,+ decodeRequest,+ decompress,+} from './request-decoding'++describe('request decoding', () => {+ const json = '{"api_key":"phc_x","app_id":"a"}'+ const parsed = { api_key: 'phc_x', app_id: 'a' }++ describe('decompress', () => {+ it.each([+ ['a plain body', Buffer.from(json), ''],+ ['a gzipped body', gzipSync(Buffer.from(json)), 'gzip'],+ ['a body gzipped by posthog-js', gzipSync(Buffer.from(json)), 'gzip-js'],+ ['a gzipped body that did not say so', gzipSync(Buffer.from(json)), ''],+ ['a base64 body', Buffer.from(Buffer.from(json).toString('base64')), ''],+ ['a base64 body in the data= form', Buffer.from(`data=${Buffer.from(json).toString('base64')}`), ''],+ ])('reads %s', (_name, body, compression) => {+ expect(decompress(body, compression)).toEqual(parsed)+ })++ it.each([+ ['an empty body', Buffer.alloc(0), ''],+ ['a zero-length string', '', ''],+ ])('returns null for %s', (_name, body, compression) => {+ expect(decompress(body, compression)).toBeNull()+ })++ it('rejects the literal string undefined, which a broken client sends as a gzip body', () => {+ expect(() => decompress(Buffer.from('undefined'), 'gzip')).toThrow(RequestParsingError)+ })++ it('rejects a truncated gzip stream', () => {+ expect(() => decompress(gzipSync(Buffer.from(json)).subarray(0, 10), 'gzip')).toThrow(RequestParsingError)+ })++ it('reports an undeclared body that is neither JSON nor gzip separately', () => {+ // Django distinguishes this case, so the two error types are kept apart here even though+ // the endpoint answers both the same way.+ expect(() => decompress(Buffer.from('not json at all'), '')).toThrow(+ UnspecifiedCompressionFallbackParsingError+ )+ })++ it('rejects lz64, which nothing that registers a device sends', () => {+ expect(() => decompress(Buffer.from('anything'), 'lz64')).toThrow(RequestParsingError)+ })++ it('rejects bytes that are not valid UTF-8 rather than substituting characters', () => {+ expect(() => decompress(Buffer.from([0x7b, 0xff, 0xfe, 0x7d]), '')).toThrow(+ UnspecifiedCompressionFallbackParsingError+ )+ })++ it.each([+ ['NaN', '{"value": NaN}', { value: null }],+ ['Infinity', '{"value": Infinity}', { value: null }],+ ['-Infinity', '{"value": -Infinity}', { value: null }],+ ['several at once', '{"a":NaN,"bb":[Infinity,-Infinity]}', { a: null, bb: [null, null] }],+ ])('maps the bare constant %s to null, as python does', (_name, body, expected) => {+ expect(decompress(Buffer.from(body), '')).toEqual(expected)+ })++ it('destroys a short body whose base64 attempt happens to succeed, as django does', () => {+ // `{"a":NaN}` holds four base64-alphabet characters, so Django's unconditional base64+ // attempt decodes it to noise and never reaches the JSON parse. Verified against the+ // Django implementation, which raises on this body too. Matching it matters more than+ // improving on it: the two have to answer the same request the same way.+ expect(() => decompress(Buffer.from('{"a":NaN}'), '')).toThrow(UnspecifiedCompressionFallbackParsingError)+ })++ it('leaves those words alone inside a string', () => {+ expect(decompress(Buffer.from('{"a":"NaN and Infinity"}'), '')).toEqual({ a: 'NaN and Infinity' })+ })++ it('leaves an escaped quote in a string from breaking the constant scan', () => {+ expect(decompress(Buffer.from('{"a":"quote \\" NaN","b":NaN}'), '')).toEqual({+ a: 'quote " NaN',+ b: null,+ })+ })+ })++ describe('decodeRequest', () => {+ it('reads the compression named in the query string for POST', () => {+ const result = decodeRequest({+ method: 'POST',+ body: gzipSync(Buffer.from(json)),+ query: new URLSearchParams('compression=gzip'),+ })++ expect(result.data).toEqual(parsed)+ })++ it('reads a urlencoded form body', () => {+ const form = new URLSearchParams({ api_key: 'phc_form', data: json })++ const result = decodeRequest({+ method: 'POST',+ body: Buffer.from(form.toString()),+ contentType: 'application/x-www-form-urlencoded',+ })++ expect(result.data).toEqual(parsed)+ expect(result.form?.get('api_key')).toEqual('phc_form')+ })++ it('ignores the charset parameter on the content type', () => {+ const result = decodeRequest({+ method: 'POST',+ body: Buffer.from(json),+ contentType: 'application/json; charset=utf-8',+ })++ expect(result.data).toEqual(parsed)+ })++ it('reads the body of a DELETE, which is how every SDK unregisters a device', () => {+ const result = decodeRequest({ method: 'DELETE', body: Buffer.from(json) })++ expect(result.data).toEqual(parsed)+ })++ it('reads a gzipped DELETE body from the content-encoding header', () => {+ const result = decodeRequest({+ method: 'DELETE',+ body: gzipSync(Buffer.from(json)),+ contentEncoding: 'gzip',+ })++ expect(result.data).toEqual(parsed)+ })+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/request-decoding.ts b/nodejs/src/messaging/push-subscriptions/request-decoding.tsnew file mode 100644index 000000000000..8d5f69853e23--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/request-decoding.ts@@ -0,0 +1,318 @@+import { gunzipSync } from 'zlib'++/** Mirrors Django's `decompress` / `load_data_from_request`. A body Django accepts and this rejects+ * is a device that never registers, and the SDK re-posts it on every app open for the life of the+ * install, so the decoding has to match rather than be merely reasonable. */++export class RequestParsingError extends Error {}++/** Raised when a body with no declared compression parsed as neither JSON nor gzip. Django+ * distinguishes it from RequestParsingError; the view answers both the same way. */+export class UnspecifiedCompressionFallbackParsingError extends Error {}++export class InflatedBodyTooLargeError extends Error {}++/** Django inflates without a bound. Here decoding runs on the one event loop that serves every+ * request and its cost grows with the inflated size, so a 16 KiB body that inflates to 16 MiB would+ * stall every other request on the process. A registration is under 1 KiB, so no SDK request comes+ * near this. */+export const MAX_INFLATED_BYTES = 64 * 1024++const GZIP_COMPRESSIONS = new Set(['gzip', 'gzip-js'])+const BODY_CONTENT_TYPES = new Set(['', 'text/plain', 'application/json'])++export type RawRequest = {+ method: string+ body: Buffer+ contentType?: string+ contentEncoding?: string+ /** Parsed from the URL. Django reads `compression` from the query string for POST. */+ query?: URLSearchParams+}++/** The decoded body, plus the form fields Django's `get_token` reads directly off `request.POST`. */+export type DecodedRequest = {+ data: unknown+ form?: URLSearchParams+}++export function decodeRequest(request: RawRequest): DecodedRequest {+ const contentType = (request.contentType ?? '').split(';')[0].trim().toLowerCase()+ const isForm = request.method === 'POST' && !BODY_CONTENT_TYPES.has(contentType)+ const form = isForm ? parseForm(request.body, contentType) : undefined++ // DELETE never reads form fields: Django's `load_data_from_request` only inspects the body for+ // POST, so the view decompresses `request.body` directly for every other method.+ const compression =+ request.method === 'POST'+ ? (+ request.query?.get('compression') ||+ form?.get('compression') ||+ request.contentEncoding ||+ ''+ ).toLowerCase()+ : (request.contentEncoding ?? '').toLowerCase()++ const payload: Buffer | string | null = isForm ? (form?.get('data') ?? null) : request.body++ return { data: decompress(payload, compression), form }+}++export function decompress(data: Buffer | string | null, compression: string): unknown {+ if (data === null || data.length === 0) {+ return null+ }++ let current: Buffer | string = data++ if (GZIP_COMPRESSIONS.has(compression)) {+ if (Buffer.isBuffer(current) ? current.equals(Buffer.from('undefined')) : current === 'undefined') {+ throw new RequestParsingError(+ 'data being loaded from the request body for decompression is the literal string "undefined"'+ )+ }+ try {+ current = gunzipSync(Buffer.isBuffer(current) ? current : Buffer.from(current), {+ maxOutputLength: MAX_INFLATED_BYTES,+ })+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE') {+ throw new InflatedBodyTooLargeError('Inflated body too large.')+ }+ throw new RequestParsingError(`Failed to decompress data. ${String(error)}`)+ }+ }++ if (compression === 'lz64') {+ // A posthog-js path. No mobile SDK sends it and web clients do not register devices, so+ // this rejects it rather than carry a decompressor for traffic that does not exist.+ throw new RequestParsingError('lz64 compression is not supported.')+ }++ const base64Decoded = tryBase64Decode(current)+ if (base64Decoded !== null) {+ current = base64Decoded+ }++ // `json.loads` on bytes decodes UTF-8 strictly, and the view treats that failure the same way+ // as invalid JSON, so invalid bytes have to fail here rather than become replacement characters.+ const text = Buffer.isBuffer(current) ? decodeUtf8Strict(current) : current+ try {+ if (text === null) {+ throw new SyntaxError('body is not valid UTF-8')+ }+ return parseJsonLikePython(text)+ } catch (error) {+ if (compression !== '') {+ throw new RequestParsingError(`Invalid JSON: ${String(error)}`)+ }+ // Django retries as gzip before giving up, so a body it accepts this way must not fail here.+ try {+ return decompress(current, 'gzip')+ } catch (fallbackError) {+ if (fallbackError instanceof InflatedBodyTooLargeError) {+ throw fallbackError+ }+ throw new UnspecifiedCompressionFallbackParsingError(`Invalid JSON: ${String(error)}`)+ }+ }+}++/** Python's `json.loads` reads the bare tokens `NaN`, `Infinity` and `-Infinity` and this endpoint+ * maps them to null, where `JSON.parse` rejects them outright. Only reached once strict parsing has+ * failed, so a string whose contents are "NaN" is already parsed and never rewritten. */+function parseJsonLikePython(text: string): unknown {+ try {+ // oxlint-disable-next-line eslint-js/no-restricted-syntax+ return JSON.parse(text)+ } catch (error) {+ const rewritten = replaceBareConstants(text)+ if (rewritten === null) {+ throw error+ }+ // oxlint-disable-next-line eslint-js/no-restricted-syntax+ return JSON.parse(rewritten)+ }+}++const BARE_CONSTANT = /NaN|-?Infinity/y++/** Replaces the non-JSON numeric constants outside string literals, or null when there are none. */+function replaceBareConstants(text: string): string | null {+ let result = ''+ let index = 0+ let inString = false+ let replaced = false++ while (index < text.length) {+ const character = text[index]+ if (inString) {+ if (character === '\\') {+ result += text.slice(index, index + 2)+ index += 2+ continue+ }+ if (character === '"') {+ inString = false+ }+ result += character+ index += 1+ continue+ }+ if (character === '"') {+ inString = true+ result += character+ index += 1+ continue+ }+ BARE_CONSTANT.lastIndex = index+ const match = BARE_CONSTANT.exec(text)+ if (match) {+ result += 'null'+ index += match[0].length+ replaced = true+ continue+ }+ result += character+ index += 1+ }++ return replaced ? result : null+}++const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'+const BASE64_VALUES = new Map([...BASE64_ALPHABET].map((character, index) => [character, index]))++/** Django tries base64 on every body before parsing it. Mirrors `posthog.utils.base64_decode`, where+ * each step can reject a body, and a body Python rejects here is one it goes on to parse unchanged,+ * so the failures matter as much as the successes. */+function tryBase64Decode(data: Buffer | string): string | null {+ const raw = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8')+ // Python encodes to ASCII first, so anything outside it raises and the attempt is abandoned.+ if (raw.some((byte) => byte > 0x7f)) {+ return null+ }++ let text = raw.toString('latin1')+ const unquoted = percentDecodeToAscii(text)+ if (unquoted === null) {+ return null+ }+ if (raw.subarray(0, 5).toString('latin1') === 'data=') {+ const separator = unquoted.indexOf('=')+ text = separator === -1 ? '' : unquoted.slice(separator + 1)+ } else {+ text = unquoted+ }++ text = text.replace(/ /g, '')+ const padding = text.length % 4+ if (padding) {+ text += '='.repeat(4 - padding)+ }++ const decoded = pythonB64Decode(text)+ if (decoded === null) {+ return null+ }+ return decodeUtf8Strict(decoded)+}++/** `urllib.parse.unquote` then `.encode("ascii")`: a non-ASCII byte or a malformed escape both leave+ * a character the ASCII encode rejects, so either abandons the attempt. */+function percentDecodeToAscii(text: string): string | null {+ let result = ''+ let index = 0+ while (index < text.length) {+ if (text[index] === '%' && index + 2 < text.length) {+ const hex = text.slice(index + 1, index + 3)+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {+ const byte = parseInt(hex, 16)+ if (byte > 0x7f) {+ return null+ }+ result += String.fromCharCode(byte)+ index += 3+ continue+ }+ // Python leaves a malformed escape as the literal characters it found.+ }+ result += text[index]+ index += 1+ }+ return result+}++/** CPython's lenient `binascii.a2b_base64`: non-alphabet characters and `=` are skipped inline, and+ * only trailing padding can close a partial quad. Node's decoder accepts bodies Python rejects, and+ * Python leaving a body untouched is what lets a plain JSON body parse as itself. */+function pythonB64Decode(text: string): Buffer | null {+ const out: number[] = []+ let quadPosition = 0+ let trailingPads = 0+ let carry = 0++ for (const character of text) {+ if (character === '=') {+ trailingPads += 1+ continue+ }+ const value = BASE64_VALUES.get(character)+ if (value === undefined) {+ continue+ }+ trailingPads = 0+ switch (quadPosition) {+ case 0:+ carry = value+ quadPosition = 1+ break+ case 1:+ out.push(((carry << 2) | (value >> 4)) & 0xff)+ carry = value & 0x0f+ quadPosition = 2+ break+ case 2:+ out.push(((carry << 4) | (value >> 2)) & 0xff)+ carry = value & 0x03+ quadPosition = 3+ break+ default:+ out.push(((carry << 6) | value) & 0xff)+ quadPosition = 0+ break+ }+ }++ if (quadPosition === 0) {+ return Buffer.from(out)+ }+ // One data character past a quad can never be a byte, and a partial quad needs padding behind it.+ if (quadPosition === 1 || quadPosition + trailingPads < 4) {+ return null+ }+ return Buffer.from(out)+}++/** Python raises on bytes that are not valid UTF-8, and that exception is what makes the caller keep+ * the original body. Node's default decoder would substitute U+FFFD and mangle it instead. */+function decodeUtf8Strict(buffer: Buffer): string | null {+ try {+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer)+ } catch {+ return null+ }+}++function parseForm(body: Buffer, contentType: string): URLSearchParams | undefined {+ // Django also parses multipart here, but no client registers a device that way and a half-built+ // parser would answer differently rather than not at all.+ if (contentType !== 'application/x-www-form-urlencoded') {+ return undefined+ }+ try {+ return new URLSearchParams(body.toString('utf8'))+ } catch {+ return undefined+ }+}diff --git a/nodejs/src/servers/push-api-server.ts b/nodejs/src/servers/push-api-server.tsnew file mode 100644index 000000000000..a52e853324db--- /dev/null+++ b/nodejs/src/servers/push-api-server.ts@@ -0,0 +1,167 @@+import { Server, createServer } from 'http'++import { EncryptedFields } from '~/cdp/utils/encryption-utils'+import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'+import { PostgresRouter, PostgresRouterConfig } from '~/common/utils/db/postgres'+import { isProdEnv, isTestEnv } from '~/common/utils/env-utils'+import { logger } from '~/common/utils/logger'+import { ProjectTokenLookup } from '~/messaging/push-subscriptions/project-token-lookup'+import { PushCaptureService } from '~/messaging/push-subscriptions/push-capture'+import { createPushSubscriptionsHandler } from '~/messaging/push-subscriptions/push-subscriptions-http'+import { PushSubscriptionsService } from '~/messaging/push-subscriptions/push-subscriptions.service'++import { CommonConfig } from '../common/config'+import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService } from '../types'+import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from './base-server'++export type PushApiConfig = {+ PUSH_API_PORT: number+ PUSH_API_HOST: string+ /** Keys the fingerprint in the rejection log. Matching Django's value keeps a client's+ * fingerprint the same in both services' logs while both serve the endpoint. The key also stops a+ * secret API key submitted in the wrong field from being confirmable out of the log. */+ SECRET_KEY: string+}++export function getDefaultPushApiConfig(): PushApiConfig {+ return {+ PUSH_API_PORT: 6750,+ PUSH_API_HOST: '0.0.0.0',+ SECRET_KEY: '',+ }+}++export type PushApiServerConfig = BaseServerConfig &+ PostgresRouterConfig &+ PushApiConfig &+ Pick<CommonConfig, 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'ENCRYPTION_SALT_KEYS' | 'CAPTURE_INTERNAL_URL'>++/** Serves `/api/push_subscriptions/`, the endpoint every mobile SDK calls on app open.+ *+ * The registration endpoint listens on its own `node:http` port rather than on the shared express+ * app. `ultimate-express` discards the request body on DELETE, and DELETE with a JSON body is how+ * every released SDK unregisters a device, so serving it there would answer `invalid_json` to every+ * logout. The lifecycle's express app still serves health and metrics on HTTP_SERVER_PORT.+ */+export class PushApiServer implements NodeServer {+ readonly lifecycle: ServerLifecycle+ private config: PushApiServerConfig++ private postgres?: PostgresRouter+ private pushServer?: Server+ private listenError?: Error++ constructor(config: Partial<PushApiServerConfig> = {}) {+ this.config = {+ ...defaultConfig,+ ...overrideConfigWithEnv(getDefaultPushApiConfig()),+ ...config,+ }+ this.lifecycle = new ServerLifecycle(this.config)+ }++ async start(): Promise<void> {+ return this.lifecycle.start(+ () => this.startServices(),+ () => this.getCleanupResources()+ )+ }++ async stop(error?: Error): Promise<void> {+ return this.lifecycle.stop(() => this.getCleanupResources(), error)+ }++ private async startServices(): Promise<void> {+ if (!this.config.SECRET_KEY && isProdEnv()) {+ // Unkeyed, the fingerprint of a secret key submitted in the wrong field becomes confirmable by+ // anyone who can read the rejection log and holds a candidate value.+ throw new Error('SECRET_KEY is required to serve push subscriptions')+ }++ if (!this.config.ENCRYPTION_SALT_KEYS && isProdEnv()) {+ // Every stored registration would fail to encrypt while the health check stays green.+ throw new Error('ENCRYPTION_SALT_KEYS is required to serve push subscriptions')+ }++ this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)+ logger.info('👍', 'Postgres Router ready')++ const service = new PushSubscriptionsService(+ new ProjectTokenLookup(this.postgres),+ this.postgres,+ new EncryptedFields(this.config.ENCRYPTION_SALT_KEYS),+ new PushCaptureService(this.config.CAPTURE_INTERNAL_URL),+ this.config.SECRET_KEY+ )++ if (!isTestEnv()) {+ this.pushServer = await this.listen(createPushSubscriptionsHandler(service))+ }++ const pluginService: PluginServerService = {+ id: 'push-api',+ onShutdown: async () => {+ await new Promise<void>((resolve) => {+ if (!this.pushServer) {+ resolve()+ return+ }+ this.pushServer.close(() => resolve())+ })+ },+ healthcheck: () => this.isHealthy(),+ }+ this.lifecycle.services.push(pluginService)+ }++ private listen(handler: (req: any, res: any) => Promise<void>): Promise<Server> {+ // Node checks the header and request timeouts only this often, 30 seconds by default, which+ // lets a slow client hold a socket well past them.+ const server = createServer({ connectionsCheckingInterval: 1_000 }, (req, res) => {+ void handler(req, res).catch((error) => {+ // A throw here would otherwise reach the process-level handler and take the pod down+ // over one request, so the connection is answered and the error is left to the logs.+ logger.error('push subscription request failed', { error })+ if (!res.headersSent) {+ res.writeHead(500, { 'Content-Type': 'application/json' })+ }+ res.end('{"type":"server_error","code":"internal","detail":"Internal error.","attr":null}')+ })+ })++ // A registration is a handful of short fields. Without these a client that opens a connection+ // and sends nothing holds a socket until node's default timeout, which is how a public+ // endpoint is starved of connections rather than of CPU.+ server.headersTimeout = 10_000+ server.requestTimeout = 15_000+ server.keepAliveTimeout = 30_000++ return new Promise((resolve, reject) => {+ server.once('error', (error) => {+ this.listenError = error as Error+ reject(error)+ })+ server.listen(this.config.PUSH_API_PORT, this.config.PUSH_API_HOST, () => {+ logger.info(+ '🚀',+ `push subscriptions listening on ${this.config.PUSH_API_HOST}:${this.config.PUSH_API_PORT}`+ )+ resolve(server)+ })+ })+ }++ private isHealthy(): HealthCheckResult {+ if (this.listenError) {+ return new HealthCheckResultError('Push API failed to listen', { error: this.listenError.message })+ }+ if (!isTestEnv() && !this.pushServer?.listening) {+ return new HealthCheckResultError('Push API is not listening', {})+ }+ return new HealthCheckResultOk()+ }++ private getCleanupResources(): CleanupResources {+ return { kafkaProducers: [], redisPools: [], postgres: this.postgres }+ }+}