The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(website): drop the secret from the affiliate application webhook (#29311)
Etienne2a9fba157853
diff --git a/packages/twenty-website/.env.example b/packages/twenty-website/.env.exampleindex 899b08c3751..53d90a1dabc 100644--- a/packages/twenty-website/.env.example+++ b/packages/twenty-website/.env.example@@ -17,10 +17,7 @@ CLIENT_BRIEF_SECRET=# /api/affiliate-application, which forwards the payload to the webhook of the# "Affiliate form: create affiliate application" workflow in the partners# workspace (https://api.twenty.com/webhooks/workflows/<workspaceId>/<workflowId>).-# Workflows cannot read headers, so the secret is sent as applicationSecret in-# the body; the workflow must stop when it does not match.AFFILIATE_APPLICATION_WEBHOOK_URL=-AFFILIATE_APPLICATION_SECRET=# Partners marketplace — the Twenty workspace the partner directory reads from# (server-side only) via the /s/partners REST endpoint.diff --git a/packages/twenty-website/src/app/api/affiliate-application/route.test.ts b/packages/twenty-website/src/app/api/affiliate-application/route.test.tsindex 89c3c0b6408..31fa483c16c 100644--- a/packages/twenty-website/src/app/api/affiliate-application/route.test.ts+++ b/packages/twenty-website/src/app/api/affiliate-application/route.test.ts@@ -3,7 +3,6 @@ export {};const ORIGINAL_FETCH = global.fetch;const ORIGINAL_WEBHOOK_URL = process.env.AFFILIATE_APPLICATION_WEBHOOK_URL;-const ORIGINAL_SECRET = process.env.AFFILIATE_APPLICATION_SECRET;const VALID_PAYLOAD = {name: 'Ada Lovelace',@@ -43,7 +42,6 @@ describe('POST /api/affiliate-application', () => {beforeEach(() => {process.env.AFFILIATE_APPLICATION_WEBHOOK_URL ='https://hooks.example/workflow';- process.env.AFFILIATE_APPLICATION_SECRET = 'test-secret-abc123';jest.spyOn(console, 'error').mockImplementation(() => {});});@@ -51,10 +49,9 @@ describe('POST /api/affiliate-application', () => {jest.restoreAllMocks();global.fetch = ORIGINAL_FETCH;process.env.AFFILIATE_APPLICATION_WEBHOOK_URL = ORIGINAL_WEBHOOK_URL;- process.env.AFFILIATE_APPLICATION_SECRET = ORIGINAL_SECRET;});- it('forwards the workflow payload with the secret in the body and accepts success:true', async () => {+ it('forwards the workflow payload without a secret and accepts success:true', async () => {const fetchSpy = mockWebhookReply({success: true,workflowRunId: 'run-id',@@ -67,6 +64,7 @@ describe('POST /api/affiliate-application', () => {await expect(response.json()).resolves.toEqual({ success: true });const [url, init] = fetchSpy.mock.calls[0];expect(url).toBe('https://hooks.example/workflow');+ expect(init.headers).toEqual({ 'Content-Type': 'application/json' });expect(JSON.parse(init.body)).toEqual({name: 'Ada Lovelace',email: '[email protected]',@@ -76,7 +74,6 @@ describe('POST /api/affiliate-application', () => {country: '',promotionPlan: '',isIntegrationPartner: false,- applicationSecret: 'test-secret-abc123',});});@@ -100,17 +97,6 @@ describe('POST /api/affiliate-application', () => {expect(fetchSpy).not.toHaveBeenCalled();});- it('returns 503 without calling the workflow when the secret is not set', async () => {- delete process.env.AFFILIATE_APPLICATION_SECRET;- const fetchSpy = mockWebhookReply({ success: true });- const { POST } = await loadRoute();-- const response = await POST(buildRequest({ ip: '198.51.100.5' }));-- expect(response.status).toBe(503);- expect(fetchSpy).not.toHaveBeenCalled();- });-it('returns 400 when the promotion plan is over the length limit', async () => {const fetchSpy = mockWebhookReply({ success: true });const { POST } = await loadRoute();diff --git a/packages/twenty-website/src/app/api/affiliate-application/route.ts b/packages/twenty-website/src/app/api/affiliate-application/route.tsindex 1023eeae8bd..bb7e8263cd6 100644--- a/packages/twenty-website/src/app/api/affiliate-application/route.ts+++ b/packages/twenty-website/src/app/api/affiliate-application/route.ts@@ -4,7 +4,6 @@ import { createWebhookForwardingRoute } from '@/platform/http';export const POST = createWebhookForwardingRoute({webhookUrlEnvVar: 'AFFILIATE_APPLICATION_WEBHOOK_URL',- secretEnvVar: 'AFFILIATE_APPLICATION_SECRET',upstreamKind: 'workflow-webhook',schema: affiliateApplicationRequestSchema,buildPayload: buildAffiliateWorkflowPayload,diff --git a/packages/twenty-website/src/platform/http/create-webhook-forwarding-route.ts b/packages/twenty-website/src/platform/http/create-webhook-forwarding-route.tsindex de2fe4a9801..0920281f67a 100644--- a/packages/twenty-website/src/platform/http/create-webhook-forwarding-route.ts+++ b/packages/twenty-website/src/platform/http/create-webhook-forwarding-route.ts@@ -1,4 +1,5 @@import { NextResponse } from 'next/server';+import { isDefined } from 'twenty-shared/utils';import { z } from 'zod';import { getClientIpKey } from './client-ip-key';@@ -18,20 +19,23 @@ const applicationSecretSchema = z.string().trim().min(1);const MAX_BODY_BYTES = 16 * 1024;const WEBHOOK_TIMEOUT_MS = 8_000;-// Twenty workflow webhooks cannot read headers, so they get the secret in the-// body, and they answer { success: true } where logic functions answer { ok: true }.-type UpstreamKind = 'logic-function' | 'workflow-webhook';--type WebhookForwardingRouteConfig<TSchema extends z.ZodType> = {- webhookUrlEnvVar: string;- secretEnvVar: string;- upstreamKind?: UpstreamKind;- schema: TSchema;- buildPayload: (data: z.infer<TSchema>) => object;- logTag: string;- notConfiguredMessage: string;- failureMessage: string;-};+// Logic functions answer { ok: true }; Twenty workflow webhooks answer+// { success: true } and cannot read headers, so they take no secret.+type UpstreamConfig =+ | { upstreamKind?: 'logic-function'; secretEnvVar: string }+ | { upstreamKind: 'workflow-webhook'; secretEnvVar?: never };++type UpstreamKind = NonNullable<UpstreamConfig['upstreamKind']>;++type WebhookForwardingRouteConfig<TSchema extends z.ZodType> =+ UpstreamConfig & {+ webhookUrlEnvVar: string;+ schema: TSchema;+ buildPayload: (data: z.infer<TSchema>) => object;+ logTag: string;+ notConfiguredMessage: string;+ failureMessage: string;+ };const UPSTREAM_SUCCESS_KEY: Record<UpstreamKind, string> = {'logic-function': 'ok',@@ -57,13 +61,15 @@ export function createWebhookForwardingRoute<TSchema extends z.ZodType>({const webhookUrlResult = webhookUrlSchema.safeParse(process.env[webhookUrlEnvVar],);- const secretResult = applicationSecretSchema.safeParse(- process.env[secretEnvVar],- );+ const secretResult = isDefined(secretEnvVar)+ ? applicationSecretSchema.safeParse(process.env[secretEnvVar])+ : undefined;- if (!webhookUrlResult.success || !secretResult.success) {+ if (!webhookUrlResult.success || secretResult?.success === false) {const rawWebhookUrl = process.env[webhookUrlEnvVar];- const rawSecret = process.env[secretEnvVar];+ const rawSecret = isDefined(secretEnvVar)+ ? process.env[secretEnvVar]+ : undefined;console.error(`[${logTag}] 503 — endpoint env vars failed validation`,JSON.stringify({@@ -75,14 +81,17 @@ export function createWebhookForwardingRoute<TSchema extends z.ZodType>({? null: (webhookUrlResult.error.issues[0]?.message ?? 'unknown'),},- [secretEnvVar]: {- present: rawSecret !== undefined,- isEmptyAfterTrim: (rawSecret ?? '').trim() === '',- length: (rawSecret ?? '').length,- parseError: secretResult.success- ? null- : (secretResult.error.issues[0]?.message ?? 'unknown'),- },+ ...(isDefined(secretEnvVar) && {+ [secretEnvVar]: {+ present: rawSecret !== undefined,+ isEmptyAfterTrim: (rawSecret ?? '').trim() === '',+ length: (rawSecret ?? '').length,+ parseError:+ secretResult?.success === false+ ? (secretResult.error.issues[0]?.message ?? 'unknown')+ : null,+ },+ }),envFileHint:'Next dev reads .env.local. After editing env vars restart the dev server — Next does not hot-reload them.',}),@@ -94,7 +103,7 @@ export function createWebhookForwardingRoute<TSchema extends z.ZodType>({}const webhookUrl = webhookUrlResult.data;- const applicationSecret = secretResult.data;+ const applicationSecret = secretResult?.data;const rateLimit = checkRateLimit(getClientIpKey(request));if (!rateLimit.allowed) {@@ -144,14 +153,12 @@ export function createWebhookForwardingRoute<TSchema extends z.ZodType>({const upstream = await fetchWithTimeout(webhookUrl,{- body: JSON.stringify(- upstreamKind === 'workflow-webhook'- ? { ...payload, applicationSecret }- : payload,- ),+ body: JSON.stringify(payload),headers: {'Content-Type': 'application/json',- 'X-Application-Secret': applicationSecret,+ ...(isDefined(applicationSecret) && {+ 'X-Application-Secret': applicationSecret,+ }),},method: 'POST',},