: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(cdp): add Standard Webhooks signing to the webhook destination (#90307)
Georges-Antoine Assif18ba88fa303
diff --git a/nodejs/src/cdp/async-functions/fetch-handler.test.ts b/nodejs/src/cdp/async-functions/fetch-handler.test.tsnew file mode 100644index 000000000000..1dba207e46a2--- /dev/null+++ b/nodejs/src/cdp/async-functions/fetch-handler.test.ts@@ -0,0 +1,27 @@+import { CyclotronInvocationQueueParametersFetchType } from '~/cdp/schema/cyclotron'++import { getAsyncFunctionHandler } from '../async-function-registry'+import { CyclotronJobInvocationResult } from '../types'+import './fetch-handler'++describe('fetch handler', () => {+ const callFetch = async (+ fetchOptions: Record<string, any>+ ): Promise<CyclotronInvocationQueueParametersFetchType> => {+ const result = { invocation: {} } as CyclotronJobInvocationResult<any>+ await getAsyncFunctionHandler('fetch')!.execute(['https://example.com', fetchOptions], {} as any, result)+ return result.invocation.queueParameters as CyclotronInvocationQueueParametersFetchType+ }++ // Receivers dedupe on webhook-id, so two deliveries must never share one. A+ // single invocation can call fetch repeatedly, which anything derived from the+ // invocation would collapse into one id.+ it('gives every signed fetch call its own webhook id', async () => {+ const first = await callFetch({ standard_webhooks: { secret_input: 'signing_secret' } })+ const second = await callFetch({ standard_webhooks: { secret_input: 'signing_secret' } })++ expect(first.standard_webhooks?.secret_input).toBe('signing_secret')+ expect(first.standard_webhooks?.webhook_id).toBeTruthy()+ expect(second.standard_webhooks?.webhook_id).not.toBe(first.standard_webhooks?.webhook_id)+ })+})diff --git a/nodejs/src/cdp/async-functions/fetch-handler.ts b/nodejs/src/cdp/async-functions/fetch-handler.tsindex f8679b5d0cb9..13ab9a4ede00 100644--- a/nodejs/src/cdp/async-functions/fetch-handler.ts+++ b/nodejs/src/cdp/async-functions/fetch-handler.ts@@ -1,5 +1,6 @@import { pickBy } from 'lodash'import { DateTime } from 'luxon'+import { randomUUID } from 'node:crypto'import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'@@ -34,6 +35,18 @@ registerAsyncFunction('fetch', {body,headers: pickBy(headers, (v) => typeof v == 'string'),...(fetchOptions?.aws_sigv4 ? { aws_sigv4: fetchOptions.aws_sigv4 } : {}),+ // Mint the webhook id here, once per fetch call, rather than in the+ // executor: it has to survive every retry of this call (the receiver+ // dedupes on it) and it must not be shared with another fetch from the+ // same invocation, which anything derived from the invocation would be.+ ...(fetchOptions?.standard_webhooks+ ? {+ standard_webhooks: {+ ...fetchOptions.standard_webhooks,+ webhook_id: randomUUID(),+ },+ }+ : {}),})result.invocation.queueParameters = fetchQueueParametersdiff --git a/nodejs/src/cdp/cdp-e2e.serial.test.ts b/nodejs/src/cdp/cdp-e2e.serial.test.tsindex 3528e87885c7..372f87c832b2 100644--- a/nodejs/src/cdp/cdp-e2e.serial.test.ts+++ b/nodejs/src/cdp/cdp-e2e.serial.test.ts@@ -3,6 +3,8 @@ import { mockFetch } from '~/tests/helpers/mocks/request.mock'import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'+import { createHmac } from 'node:crypto'+import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { closeHub, createHub } from '~/common/utils/db/hub'@@ -27,6 +29,7 @@ import {import { CdpEventsConsumer } from './consumers/cdp-events.consumer'import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'+import { template as webhookTemplate } from './templates/_destinations/webhook/webhook.template'import { compileHog } from './templates/compiler'const ActualKafkaProducerWrapper = jest.requireActual('~/common/kafka/producer').KafkaProducerWrapper@@ -530,6 +533,72 @@ describe('CDP Consumer loop', () => {expect(sigv4Authorizations[0]).not.toEqual(sigv4Authorizations[1])})+ // E2E coverage for Standard Webhooks signing, driven by the shipped webhook+ // template rather than hand-written Hog. Three things only reachable here:+ // `signing_secret` is a secret input, so in production it exists solely in+ // Fernet-encrypted `encrypted_inputs`; the signing payload now carries+ // `webhook_id`, so it has to survive the cyclotron serialization round-trip;+ // and the signature has to cover the exact body bytes the Node Hog VM emits.+ // The unit tests build `queueParameters` in memory and never see any of it.+ it('should sign webhook template fetches so a receiver can verify them', async () => {+ // Secret from the Standard Webhooks spec's reference example.+ const SIGNING_SECRET = 'whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw'+ const SIGNED_URL = 'https://signed.example.com/hooks'++ const fixedTime = new Date('2024-04-16T12:34:51Z').getTime()+ const dateSpy = jest.spyOn(Date, 'now').mockReturnValue(fixedTime)++ try {+ await insertHogFunction({+ type: 'destination',+ hog: webhookTemplate.code,+ bytecode: await compileHog(webhookTemplate.code),+ inputs_schema: webhookTemplate.inputs_schema,+ inputs: {+ url: { value: SIGNED_URL },+ method: { value: 'POST' },+ body: { value: { event: '{event.event}' } },+ headers: { value: { 'Content-Type': 'application/json' } },+ },+ // Mirror what Django's `move_secret_inputs` produces on save: a+ // `secret: true` input is absent from `inputs` entirely, so the+ // executor can only find it by decrypting `encrypted_inputs`.+ encrypted_inputs: hub.encryptedFields.encrypt(+ JSON.stringify({ signing_secret: { value: SIGNING_SECRET } })+ ),+ ...HOG_FILTERS_EXAMPLES.no_filters,+ } as any)++ // The default `fnFetchNoFilters` from beforeEach also matches this+ // event, so select the signed call by URL.+ const signedCalls = (): any[][] => mockFetch.mock.calls.filter((c: any[]) => c[0] === SIGNED_URL)++ await eventsConsumer.processBatch([globals])++ await waitForExpect(() => {+ expect(signedCalls()).toHaveLength(1)+ }, 5000)++ const [, opts] = signedCalls()[0] as [string, any]+ const headers = opts.headers as Record<string, string>++ expect(headers['webhook-id']).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)+ expect(headers['webhook-timestamp']).toBe('1713270891')+ expect(headers['Content-Type']).toBe('application/json')++ // Verify exactly the way a receiver's library does: recompute the HMAC+ // over the body bytes that arrived, keyed with the decoded secret. A+ // signature over anything but the sent bytes fails here.+ const key = Buffer.from(SIGNING_SECRET.replace('whsec_', ''), 'base64')+ const digest = createHmac('sha256', key)+ .update(`${headers['webhook-id']}.${headers['webhook-timestamp']}.${opts.body as string}`)+ .digest('base64')+ expect(headers['webhook-signature']).toBe(`v1,${digest}`)+ } finally {+ dateSpy.mockRestore()+ }+ })+it('should handle fetch failures with retries', async () => {mockFetch.mockImplementation(() => {return Promise.resolve({diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.tsindex f5e6cbb37e75..77b57f885744 100644--- a/nodejs/src/cdp/schema/cyclotron.ts+++ b/nodejs/src/cdp/schema/cyclotron.ts@@ -115,6 +115,19 @@ export const CyclotronInvocationQueueParametersFetchAwsSigV4Schema = z.object({session_token_input: z.string().optional(),})+// When `standard_webhooks` is present on a fetch queue payload, the cyclotron+// fetch executor signs the request per the Standard Webhooks spec immediately+// before each attempt. Like `aws_sigv4` above, `secret_input` is an input-key+// reference resolved at fetch time, because the queue payload is plaintext JSON.+// `webhook_id` is minted per fetch call by the fetch async function and lives in+// the payload so retries of that call reuse it: the spec makes it the receiver's+// idempotency key, so it must stay constant across attempts of one delivery and+// differ between two deliveries, including two in the same invocation.+export const CyclotronInvocationQueueParametersFetchStandardWebhooksSchema = z.object({+ secret_input: z.string(),+ webhook_id: z.string(),+})+export const CyclotronInvocationQueueParametersFetchSchema = z.object({type: z.literal('fetch'),url: z.string(),@@ -123,6 +136,7 @@ export const CyclotronInvocationQueueParametersFetchSchema = z.object({max_tries: z.number().optional(),headers: z.record(z.string(), z.string()).optional(),aws_sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Schema.optional(),+ standard_webhooks: CyclotronInvocationQueueParametersFetchStandardWebhooksSchema.optional(),})export const MAX_WORKFLOW_EMAIL_SENDERS = 10@@ -164,6 +178,9 @@ export type PushNotificationPayloadType = z.infer<typeof PushNotificationPayloadexport type CyclotronInvocationQueueParametersFetchAwsSigV4Type = z.infer<typeof CyclotronInvocationQueueParametersFetchAwsSigV4Schema>+export type CyclotronInvocationQueueParametersFetchStandardWebhooksType = z.infer<+ typeof CyclotronInvocationQueueParametersFetchStandardWebhooksSchema+>export type CyclotronInvocationQueueParametersFetchType = z.infer<typeof CyclotronInvocationQueueParametersFetchSchema>export type CyclotronInvocationQueueParametersEmailType = z.infer<typeof CyclotronInvocationQueueParametersEmailSchema>export type CyclotronInvocationQueueParametersSendPushNotificationType = z.infer<diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.tsindex 25b8da07bde3..c6930cdcbc2d 100644--- a/nodejs/src/cdp/services/hog-executor-async.service.ts+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts@@ -22,6 +22,7 @@ import { cdpTrackedFetch, fetchErrorDetail, isFetchResponseRetriable } from '../import { createInvocationResult } from '../utils/invocation-utils'import { isNonFailureStatus } from '../utils/non-failure-status-codes'import { ScopedServiceJwt } from '../utils/scoped-service-jwt'+import { resolveStandardWebhooksKey, signStandardWebhooksRequest } from '../utils/standard-webhooks'import { HogExecutorExecuteOptions, HogExecutorPreviousResult, HogExecutorService } from './hog-executor.service'import { HogInputsService } from './hog-inputs.service'import { EMAIL_QUEUE_PRIORITY, getEmailQueuePriorityClass } from './messaging/email-priority'@@ -445,14 +446,18 @@ export class HogExecutorAsyncService {// regenerated here and never persisted back to queueParameters. Credential// resolution + missing-input handling live in `aws-sigv4.ts` — see// `resolveAwsSigV4Credentials` for the encrypted_inputs/inputs lookup order.+ const failSigning = (error: string): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> => {+ addLog('error', error)+ result.error = new Error(error)+ result.finished = true+ return result+ }+let signedHeaders = headersif (params.aws_sigv4) {const resolved = resolveAwsSigV4Credentials(params.aws_sigv4, invocation.hogFunction)if (!resolved.ok) {- addLog('error', resolved.error)- result.error = new Error(resolved.error)- result.finished = true- return result+ return failSigning(resolved.error)}signedHeaders = signAwsRequest({method,@@ -463,6 +468,25 @@ export class HogExecutorAsyncService {})}+ // Standard Webhooks signatures embed a timestamp the receiver checks+ // against a tolerance window (5 minutes in the reference libraries), so+ // like AWS SigV4 above they are computed immediately before each attempt+ // and never persisted back to queueParameters. The `webhook-id` the+ // receiver dedupes on is the exception: it comes from the queue payload,+ // which the retry path preserves, so it stays constant across attempts.+ if (params.standard_webhooks) {+ const resolved = resolveStandardWebhooksKey(params.standard_webhooks, invocation.hogFunction)+ if (!resolved.ok) {+ return failSigning(resolved.error)+ }+ signedHeaders = signStandardWebhooksRequest({+ webhookId: params.standard_webhooks.webhook_id,+ body: params.body ?? '',+ headers: signedHeaders,+ key: resolved.key,+ })+ }+const fetchParams: FetchOptions = { method, headers: signedHeaders }if (!['GET', 'HEAD'].includes(method) && params.body) {diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex a18e1d2c9c02..80b6452661b9 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -2,6 +2,7 @@import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { FetchOptions } from '~/common/utils/request'+import { createHmac } from 'node:crypto'import { createServer } from 'http'import { DateTime } from 'luxon'import { AddressInfo } from 'net'@@ -1668,6 +1669,130 @@ describe('Hog Executor', () => {})})+ describe('standard_webhooks', () => {+ // Secret from the Standard Webhooks spec's reference example. The tests+ // recompute the expected signature with the base64-decoded key, exactly+ // as a receiver's verification library would.+ const KEY = Buffer.from('MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw', 'base64')+ const BODY = '{"test": 2432232314}'+ // Shaped like what the fetch async function puts on the queue payload.+ const SIGNING_REFS = {+ secret_input: 'signing_secret',+ webhook_id: '4f6c9f2a-5b1e-4f5b-9d3c-2a7e8c1d0b64',+ }++ const seedSigningSecretInput = (invocation: CyclotronJobInvocationHogFunction) => {+ invocation.hogFunction.encrypted_inputs = {+ ...(invocation.hogFunction.encrypted_inputs ?? {}),+ signing_secret: { value: 'whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw' },+ } as any+ }++ const expectedSignature = (webhookId: string, timestamp: string): string =>+ `v1,${createHmac('sha256', KEY).update(`${webhookId}.${timestamp}.${BODY}`).digest('base64')}`++ it('signs the request so the reference verification succeeds upstream', async () => {+ let receivedId: string | undefined+ let receivedTimestamp: string | undefined+ let receivedSignature: string | undefined+ mockRequest.mockImplementation((req: any, res: any) => {+ receivedId = req.headers['webhook-id']+ receivedTimestamp = req.headers['webhook-timestamp']+ receivedSignature = req.headers['webhook-signature']+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('ok')+ })++ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: BODY,+ headers: { 'Content-Type': 'application/json' },+ standard_webhooks: SIGNING_REFS,+ })+ seedSigningSecretInput(invocation)++ const result = await executor.executeFetch(invocation)++ expect(result.error).toBeUndefined()+ expect(receivedId).toBe(SIGNING_REFS.webhook_id)+ // Date.now is mocked to 2025-01-01T00:00:00Z in beforeEach+ expect(receivedTimestamp).toBe('1735689600')+ expect(receivedSignature).toBe(expectedSignature(receivedId!, receivedTimestamp!))+ })++ // The spec wants webhook-id constant across retries (the receiver's+ // idempotency key) while the timestamp must be fresh so the retry+ // stays within the receiver's tolerance window.+ it('keeps webhook-id constant across retries while refreshing the timestamp and signature', async () => {+ const receivedIds: string[] = []+ const receivedTimestamps: string[] = []+ const receivedSignatures: string[] = []+ let callCount = 0+ mockRequest.mockImplementation((req: any, res: any) => {+ receivedIds.push(req.headers['webhook-id'])+ receivedTimestamps.push(req.headers['webhook-timestamp'])+ receivedSignatures.push(req.headers['webhook-signature'])+ callCount+++ if (callCount === 1) {+ res.writeHead(500, { 'Content-Type': 'text/plain' })+ res.end('first attempt fails')+ } else {+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('second attempt ok')+ }+ })++ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: BODY,+ headers: { 'Content-Type': 'application/json' },+ standard_webhooks: SIGNING_REFS,+ })+ seedSigningSecretInput(invocation)++ let result = await executor.executeFetch(invocation)+ expect(result.invocation.state.attempts).toBe(1)++ const retryTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' }).plus({+ minutes: 6,+ })+ jest.spyOn(Date, 'now').mockReturnValue(retryTime.toMillis())++ result = await executor.executeFetch(result.invocation)++ expect(result.error).toBeUndefined()+ expect(receivedIds[0]).toBe(receivedIds[1])+ expect(receivedTimestamps).toEqual(['1735689600', '1735689960'])+ expect(receivedSignatures[0]).not.toBe(receivedSignatures[1])+ expect(receivedSignatures[1]).toBe(expectedSignature(receivedIds[1], receivedTimestamps[1]))+ })++ it('errors loudly instead of sending an unsigned request when the secret input is missing', async () => {+ mockRequest.mockImplementation((req: any, res: any) => {+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('ok')+ })++ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: BODY,+ headers: { 'Content-Type': 'application/json' },+ standard_webhooks: SIGNING_REFS,+ })+ // Intentionally do NOT seed inputs.++ const result = await executor.executeFetch(invocation)++ expect(mockRequest).not.toHaveBeenCalled()+ expect(result.error).toBeInstanceOf(Error)+ expect(result.error.message).toContain('Standard Webhooks signing failed')+ expect(result.error.message).toContain('signing_secret')+ })+ })+it('respects maxFetchRetries option to disable retries', async () => {mockRequest.mockImplementation((req: any, res: any) => {res.writeHead(500, { 'Content-Type': 'text/plain' })diff --git a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.tsindex 1b032c7f68b8..f53f960eb9c6 100644--- a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts@@ -50,6 +50,24 @@ describe('webhook template', () => {expect(fetchResponse.error).toBeUndefined()})+ // The queue payload is stored as plaintext JSON, so the template must pass+ // an input-key reference for the executor to resolve at fetch time, never+ // the secret itself.+ it('passes a signing secret reference, not the secret, to the fetch queue', async () => {+ const response = await tester.invoke({+ url: 'https://example.com',+ signing_secret: 'whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw',+ })++ expect(response.error).toBeUndefined()+ const params = response.invocation.queueParameters as any+ expect(params.standard_webhooks).toEqual({+ secret_input: 'signing_secret',+ webhook_id: expect.any(String),+ })+ expect(JSON.stringify(params)).not.toContain('MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw')+ })+it('should log details of given', async () => {let response = await tester.invoke({url: 'https://example.com?v={event.properties.$lib_version}',diff --git a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.tsindex 49bf923fc0e2..13e80e94dac3 100644--- a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts+++ b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts@@ -17,6 +17,12 @@ let payload := {'method': inputs.method}+if (not empty(inputs.signing_secret)) {+ payload['standard_webhooks'] := {+ 'secret_input': 'signing_secret'+ }+}+if (inputs.debug) {print('Request', inputs.url, payload)}@@ -89,6 +95,14 @@ if (inputs.debug) {default: { 'Content-Type': 'application/json' },description: 'HTTP headers to send in the request.',},+ {+ key: 'signing_secret',+ type: 'string',+ label: 'Signing secret',+ secret: true,+ required: false,+ description: 'Signs each request following the [Standard Webhooks](https://www.standardwebhooks.com) spec.',+ },{key: 'debug',type: 'boolean',diff --git a/nodejs/src/cdp/utils/aws-sigv4.ts b/nodejs/src/cdp/utils/aws-sigv4.tsindex a493d3e2f8d8..3e0535376812 100644--- a/nodejs/src/cdp/utils/aws-sigv4.ts+++ b/nodejs/src/cdp/utils/aws-sigv4.ts@@ -3,6 +3,7 @@ import { createHash, createHmac } from 'node:crypto'import { CyclotronInvocationQueueParametersFetchAwsSigV4Type } from '~/cdp/schema/cyclotron'import { HogFunctionType } from '../types'+import { resolveHogFunctionInputValue } from './hog-function-inputs'export type AwsSigV4Credentials = {service: string@@ -192,8 +193,7 @@ export function resolveAwsSigV4Credentials(sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Type,hogFunction: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>): ResolvedAwsSigV4Credentials {- const lookup = (key: string): unknown =>- hogFunction.encrypted_inputs?.[key]?.value ?? hogFunction.inputs?.[key]?.value+ const lookup = (key: string): unknown => resolveHogFunctionInputValue(hogFunction, key)const accessKeyId = lookup(sigv4.access_key_id_input)const secretAccessKey = lookup(sigv4.secret_access_key_input)diff --git a/nodejs/src/cdp/utils/hog-function-inputs.ts b/nodejs/src/cdp/utils/hog-function-inputs.tsnew file mode 100644index 000000000000..5d73ca98e5fe--- /dev/null+++ b/nodejs/src/cdp/utils/hog-function-inputs.ts@@ -0,0 +1,12 @@+import { HogFunctionType } from '../types'++// Secret inputs land in `encrypted_inputs` after Django's `move_secret_inputs`+// runs on save; non-secret inputs stay on `inputs`. Request signers resolve+// input-key references at fetch time with the encrypted value first, so a+// secret always wins over a stale plaintext copy.+export function resolveHogFunctionInputValue(+ hogFunction: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>,+ key: string+): unknown {+ return hogFunction.encrypted_inputs?.[key]?.value ?? hogFunction.inputs?.[key]?.value+}diff --git a/nodejs/src/cdp/utils/standard-webhooks.test.ts b/nodejs/src/cdp/utils/standard-webhooks.test.tsnew file mode 100644index 000000000000..e1e1b70a28c2--- /dev/null+++ b/nodejs/src/cdp/utils/standard-webhooks.test.ts@@ -0,0 +1,94 @@+import { resolveStandardWebhooksKey, signStandardWebhooksRequest } from './standard-webhooks'++describe('standard-webhooks', () => {+ const BASE64_SECRET = 'MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw'+ // The id, timestamp, body, and signature come from the Standard Webhooks+ // spec's reference example, so a passing test proves interoperability with+ // receivers that verify using the reference libraries.+ const WEBHOOK_ID = 'msg_p5jXN8AQM9LWM0D4loKWxJek'+ const NOW = new Date(1614265330 * 1000)+ const BODY = '{"test": 2432232314}'+ const EXPECTED_SIGNATURE = 'v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE='++ const hogFunctionWith = (value: unknown, field: 'inputs' | 'encrypted_inputs' = 'encrypted_inputs'): any => ({+ [field]: { signing_secret: { value } },+ })++ describe('resolveStandardWebhooksKey', () => {+ it.each([+ ['a whsec_ prefixed secret', `whsec_${BASE64_SECRET}`],+ ['a plain base64 secret', BASE64_SECRET],+ ])('decodes %s to the raw key bytes', (_name, secret) => {+ const resolved = resolveStandardWebhooksKey({ secret_input: 'signing_secret' }, hogFunctionWith(secret))++ expect(resolved).toEqual({ ok: true, key: Buffer.from(BASE64_SECRET, 'base64') })+ })++ it('falls back to plaintext inputs when encrypted_inputs does not carry the secret', () => {+ const resolved = resolveStandardWebhooksKey(+ { secret_input: 'signing_secret' },+ hogFunctionWith(BASE64_SECRET, 'inputs')+ )++ expect(resolved).toEqual({ ok: true, key: Buffer.from(BASE64_SECRET, 'base64') })+ })++ it.each([+ ['missing', {}],+ ['not a string', hogFunctionWith(12345)],+ ['an empty string', hogFunctionWith('')],+ ['not valid base64', hogFunctionWith('whsec_not!!valid@@base64')],+ // Lenient base64 decoding turns a truncated paste into a short or+ // even empty HMAC key, which anyone could reproduce.+ ['truncated to a single base64 character', hogFunctionWith('whsec_A')],+ ['shorter than the 24 bytes the spec requires', hogFunctionWith(`whsec_${BASE64_SECRET.slice(0, 16)}`)],+ ])('refuses to produce a key when the secret is %s', (_name, hogFunction) => {+ const resolved = resolveStandardWebhooksKey({ secret_input: 'signing_secret' }, hogFunction as any)++ expect(resolved.ok).toBe(false)+ })+ })++ describe('signStandardWebhooksRequest', () => {+ const key = Buffer.from(BASE64_SECRET, 'base64')++ it('produces the signature from the Standard Webhooks reference example', () => {+ const headers = signStandardWebhooksRequest({+ webhookId: WEBHOOK_ID,+ body: BODY,+ headers: { 'Content-Type': 'application/json' },+ key,+ now: NOW,+ })++ expect(headers).toEqual({+ 'Content-Type': 'application/json',+ 'webhook-id': WEBHOOK_ID,+ 'webhook-timestamp': '1614265330',+ 'webhook-signature': EXPECTED_SIGNATURE,+ })+ })++ it('replaces stale signing headers from a previous attempt instead of keeping them', () => {+ const headers = signStandardWebhooksRequest({+ webhookId: WEBHOOK_ID,+ body: BODY,+ headers: {+ 'Webhook-Id': 'stale-id',+ 'Webhook-Timestamp': '0',+ 'Webhook-Signature': 'v1,stale',+ 'X-Custom': 'kept',+ },+ key,+ now: NOW,+ })++ expect(headers).toEqual({+ 'X-Custom': 'kept',+ 'webhook-id': WEBHOOK_ID,+ 'webhook-timestamp': '1614265330',+ 'webhook-signature': EXPECTED_SIGNATURE,+ })+ })+ })+})diff --git a/nodejs/src/cdp/utils/standard-webhooks.ts b/nodejs/src/cdp/utils/standard-webhooks.tsnew file mode 100644index 000000000000..1a738fc09734--- /dev/null+++ b/nodejs/src/cdp/utils/standard-webhooks.ts@@ -0,0 +1,108 @@+import { createHmac } from 'node:crypto'++import { CyclotronInvocationQueueParametersFetchStandardWebhooksType } from '~/cdp/schema/cyclotron'++import { HogFunctionType } from '../types'+import { resolveHogFunctionInputValue } from './hog-function-inputs'++// Headers that are signing artifacts. They must always be rebuilt, never+// inherited from a previous attempt's queue payload.+const SIGNING_HEADERS = new Set(['webhook-id', 'webhook-timestamp', 'webhook-signature'])++// Standard Webhooks secrets are base64, optionally prefixed with "whsec_".+// See https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md+const BASE64_SECRET_REGEX = /^[A-Za-z0-9+/]+={0,2}$/++// The spec puts symmetric signing secrets at 24 bytes or more. Shorter almost+// always means a truncated paste, and base64 decoding is lenient enough to turn+// one into a short or even empty HMAC key, which anyone could reproduce. Fail+// here so the customer sees the cause instead of a 403 from the receiver. There+// is deliberately no upper bound: HMAC-SHA256 folds a long key down itself, so+// rejecting one would only break a receiver that issues them.+const MIN_SECRET_KEY_BYTES = 24++export type ResolvedStandardWebhooksKey = { ok: true; key: Buffer } | { ok: false; error: string }++export type SignStandardWebhooksRequestArgs = {+ webhookId: string+ body?: string | null+ headers?: Record<string, string>+ key: Buffer+ now?: Date+}++export function resolveStandardWebhooksKey(+ params: Pick<CyclotronInvocationQueueParametersFetchStandardWebhooksType, 'secret_input'>,+ hogFunction: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>+): ResolvedStandardWebhooksKey {+ const secret = resolveHogFunctionInputValue(hogFunction, params.secret_input)++ if (typeof secret !== 'string' || secret.length === 0) {+ return {+ ok: false,+ error: `Standard Webhooks signing failed: input ${params.secret_input} not found on hog function or not a string. Refusing to send an unsigned request.`,+ }+ }++ const encoded = secret.startsWith('whsec_') ? secret.slice('whsec_'.length) : secret++ if (!BASE64_SECRET_REGEX.test(encoded)) {+ return {+ ok: false,+ error: `Standard Webhooks signing failed: the signing secret is not valid base64. Provide the secret exactly as issued, with or without the whsec_ prefix.`,+ }+ }++ const key = Buffer.from(encoded, 'base64')++ if (key.length < MIN_SECRET_KEY_BYTES) {+ return {+ ok: false,+ error: `Standard Webhooks signing failed: the signing secret decodes to ${key.length} bytes, but the spec requires at least ${MIN_SECRET_KEY_BYTES}. Check that the whole secret was pasted.`,+ }+ }++ return { ok: true, key }+}++/**+ * Signs an HTTP request per the Standard Webhooks spec: HMAC-SHA256 over+ * `${webhook-id}.${webhook-timestamp}.${body}` with the base64-decoded secret,+ * sent as `webhook-signature: v1,<base64 digest>`.+ *+ * Returns a fresh headers object that callers should USE INSTEAD OF any prior+ * `webhook-*` headers: those are signing artifacts, and a stale timestamp+ * fails the receiver's tolerance check (5 minutes in the reference+ * implementations), so this must be called immediately before each fetch+ * attempt. `webhookId` deliberately stays the caller's job: the spec wants it+ * constant across retries (receivers use it for idempotency) while the+ * timestamp and signature must be fresh.+ */+export function signStandardWebhooksRequest({+ webhookId,+ body,+ headers,+ key,+ now,+}: SignStandardWebhooksRequestArgs): Record<string, string> {+ // Defaults to `Date.now()` so jest's `Date.now` mock (the standard PostHog+ // test seam) flows through to the signature timestamp.+ const timestamp = String(Math.floor((now?.getTime() ?? Date.now()) / 1000))+ const signature = createHmac('sha256', key)+ .update(`${webhookId}.${timestamp}.${body ?? ''}`)+ .digest('base64')++ const outHeaders: Record<string, string> = {}+ for (const [headerKey, headerValue] of Object.entries(headers ?? {})) {+ if (!SIGNING_HEADERS.has(headerKey.toLowerCase())) {+ outHeaders[headerKey] = headerValue+ }+ }++ return {+ ...outHeaders,+ 'webhook-id': webhookId,+ 'webhook-timestamp': timestamp,+ 'webhook-signature': `v1,${signature}`,+ }+}diff --git a/nodejs/tests/fixtures/hog-bytecode/0801926935bf71af60171779dab683f0b8fcb409e4d15afeb943c78581ce1c69.json b/nodejs/tests/fixtures/hog-bytecode/0801926935bf71af60171779dab683f0b8fcb409e4d15afeb943c78581ce1c69.jsonnew file mode 100644index 000000000000..7cd849d9ca57--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/0801926935bf71af60171779dab683f0b8fcb409e4d15afeb943c78581ce1c69.json@@ -0,0 +1 @@+["_H",1,32,"https://example.com",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/652477e39fb8ec5008cf9919562622d823c6b97f658724570ff0d3d04a7e3399.json b/nodejs/tests/fixtures/hog-bytecode/652477e39fb8ec5008cf9919562622d823c6b97f658724570ff0d3d04a7e3399.jsonnew file mode 100644index 000000000000..c9f5a21a6d0a--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/652477e39fb8ec5008cf9919562622d823c6b97f658724570ff0d3d04a7e3399.json@@ -0,0 +1 @@+["_H",1,32,"headers",32,"headers",32,"inputs",1,2,32,"body",32,"body",32,"inputs",1,2,32,"method",32,"method",32,"inputs",1,2,42,3,32,"signing_secret",32,"inputs",1,2,2,"empty",1,5,40,11,36,0,32,"standard_webhooks",32,"secret_input",32,"signing_secret",42,1,46,32,"debug",32,"inputs",1,2,40,14,32,"Request",32,"url",32,"inputs",1,2,36,0,2,"print",3,35,32,"url",32,"inputs",1,2,36,0,2,"fetch",2,33,400,36,1,32,"status",45,14,40,21,32,"Webhook failed with status ",36,1,32,"status",45,32,": ",36,1,32,"body",45,2,"concat",4,2,"Error",1,49,32,"debug",32,"inputs",1,2,40,16,32,"Response",36,1,32,"status",45,36,1,32,"body",45,2,"print",3,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/ab928a7c7c21744f7bb7e03347ee466ea5a7a49fd3bbd09d438ae34e9ed5cd3d.json b/nodejs/tests/fixtures/hog-bytecode/ab928a7c7c21744f7bb7e03347ee466ea5a7a49fd3bbd09d438ae34e9ed5cd3d.jsonnew file mode 100644index 000000000000..533888b0a59f--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/ab928a7c7c21744f7bb7e03347ee466ea5a7a49fd3bbd09d438ae34e9ed5cd3d.json@@ -0,0 +1 @@+["_H",1,32,"whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",38]