The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(server): resolve server routes by primary key, fall back to the legacy identifier (#26438)
Paul Rastoina828ed015116
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdxindex 87faefb1937..1743b555aae 100644--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx@@ -281,10 +281,24 @@ export default defineLogicFunction({The endpoint is reachable at:```-POST https://your-twenty-server.com/webhooks/server/:resolverLogicFunctionUniversalIdentifier+POST https://your-twenty-server.com/webhooks/server/:resolverLogicFunctionId```-The identifier is the resolver's `universalIdentifier` from your manifest. Register that URL with the provider.+The identifier is the resolver's `id`: the primary key the server assigns when the app is first synced into the owner workspace, not the `universalIdentifier` from your manifest. Read it back from the `/metadata` API of the owner workspace, then register that URL with the provider:++```graphql+query {+ findManyLogicFunctions {+ id+ name+ universalIdentifier+ }+}+```++<Note>+A URL carrying the resolver's `universalIdentifier` still resolves for now, and the response carries a `Deprecation` header. A `universalIdentifier` is unique per workspace, not globally: if another registration owned by a different workspace declares the same one, the platform answers `404` for that URL instead of choosing between them. Move the URLs registered with your providers to the `id` form.+</Note>**Answering a verification GET.** Some providers verify an endpoint before they deliver to it, by sending a `GET` carrying a challenge to the same URL they will later `POST` events to — Meta's WhatsApp Cloud API is one. A server route answers `POST` only unless you say otherwise, so declare both methods:diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-legacy-identifier-deprecation-header-value.constant.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-legacy-identifier-deprecation-header-value.constant.tsnew file mode 100644index 00000000000..ab410b01da2--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-legacy-identifier-deprecation-header-value.constant.ts@@ -0,0 +1 @@+export const SERVER_ROUTE_LEGACY_IDENTIFIER_DEPRECATION_HEADER_VALUE = `@${Math.floor(new Date('2026-09-22T00:00:00Z').getTime() / 1000)}`;diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.controller.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.controller.tsindex d71699238b9..073c3a749c0 100644--- a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.controller.ts@@ -14,6 +14,7 @@ import { ApiPath } from 'twenty-shared/types';import { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';import { sendRouteTriggerResponse } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/route-trigger-response.util';+import { SERVER_ROUTE_LEGACY_IDENTIFIER_DEPRECATION_HEADER_VALUE } from 'src/engine/core-modules/server-route-trigger/constants/server-route-legacy-identifier-deprecation-header-value.constant';import { ServerRouteTriggerRestApiExceptionFilter } from 'src/engine/core-modules/server-route-trigger/exceptions/server-route-trigger-rest-api-exception-filter';import { ServerRouteTriggerService } from 'src/engine/core-modules/server-route-trigger/server-route-trigger.service';import { UsageLimitRestApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter';@@ -33,42 +34,49 @@ export class ServerRouteTriggerController {) {}private async handleRequest(- resolverLogicFunctionUniversalIdentifier: string,+ resolverLogicFunctionIdentifier: string,request: Request,response: Response,) {- sendRouteTriggerResponse(- response,+ const { response: triggerResponse, isResolvedThroughLegacyIdentifier } =await this.serverRouteTriggerService.handle({request,- resolverLogicFunctionUniversalIdentifier,- }),- );+ resolverLogicFunctionIdentifier,+ });++ if (isResolvedThroughLegacyIdentifier) {+ response.setHeader(+ 'Deprecation',+ SERVER_ROUTE_LEGACY_IDENTIFIER_DEPRECATION_HEADER_VALUE,+ );+ }++ sendRouteTriggerResponse(response, triggerResponse);}- @Get(':resolverLogicFunctionUniversalIdentifier')+ @Get(':resolverLogicFunctionIdentifier')async get(- @Param('resolverLogicFunctionUniversalIdentifier')- resolverLogicFunctionUniversalIdentifier: string,+ @Param('resolverLogicFunctionIdentifier')+ resolverLogicFunctionIdentifier: string,@Req() request: Request,@Res() response: Response,) {await this.handleRequest(- resolverLogicFunctionUniversalIdentifier,+ resolverLogicFunctionIdentifier,request,response,);}- @Post(':resolverLogicFunctionUniversalIdentifier')+ @Post(':resolverLogicFunctionIdentifier')async post(- @Param('resolverLogicFunctionUniversalIdentifier')- resolverLogicFunctionUniversalIdentifier: string,+ @Param('resolverLogicFunctionIdentifier')+ resolverLogicFunctionIdentifier: string,@Req() request: Request,@Res() response: Response,) {await this.handleRequest(- resolverLogicFunctionUniversalIdentifier,+ resolverLogicFunctionIdentifier,request,response,);diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.service.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.service.tsindex 74b3be2bbb0..f73f389d309 100644--- a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.service.ts+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.service.ts@@ -3,6 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';import { Request } from 'express';import { isLogicFunctionHttpResponse } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';+import { type SelectQueryBuilder } from 'typeorm';import { isUsageRefusedError } from 'src/engine/core-modules/billing/utils/is-usage-refused-error.util';import {@@ -40,6 +41,16 @@ import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scopeconst QUEUED_TARGET_RETRY_LIMIT = 3;+export type ServerRouteTriggerResult = {+ response: RouteTriggerResponse;+ isResolvedThroughLegacyIdentifier: boolean;+};++type ResolvedServerRouteResolver = {+ resolver: LogicFunctionEntity;+ isResolvedThroughLegacyIdentifier: boolean;+};+@Injectable()export class ServerRouteTriggerService {private readonly logger = new Logger(ServerRouteTriggerService.name);@@ -54,22 +65,13 @@ export class ServerRouteTriggerService {async handle({request,- resolverLogicFunctionUniversalIdentifier,+ resolverLogicFunctionIdentifier,}: {request: Request;- resolverLogicFunctionUniversalIdentifier: string;- }): Promise<RouteTriggerResponse> {- const resolver = await this.findResolver({- logicFunctionUniversalIdentifier:- resolverLogicFunctionUniversalIdentifier,- });-- if (!isDefined(resolver)) {- throw new ServerRouteTriggerException(- `Server resolver function ${resolverLogicFunctionUniversalIdentifier} not found`,- ServerRouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND,- );- }+ resolverLogicFunctionIdentifier: string;+ }): Promise<ServerRouteTriggerResult> {+ const { resolver, isResolvedThroughLegacyIdentifier } =+ await this.findResolverOrThrow(resolverLogicFunctionIdentifier);const allowedHttpMethods =resolver.serverRouteTriggerSettings?.httpMethods ??@@ -79,14 +81,14 @@ export class ServerRouteTriggerService {!allowedHttpMethods.some((httpMethod) => httpMethod === request.method)) {throw new ServerRouteTriggerException(- `Server resolver function ${resolverLogicFunctionUniversalIdentifier} does not accept ${request.method} requests`,+ `Server resolver function ${resolverLogicFunctionIdentifier} does not accept ${request.method} requests`,ServerRouteTriggerExceptionCode.METHOD_NOT_ALLOWED,);}if (resolver.httpRouteTriggerSettings?.isAuthRequired === true) {throw new ServerRouteTriggerException(- `Server resolver function ${resolverLogicFunctionUniversalIdentifier} requires authentication and cannot be dispatched through the public server route`,+ `Server resolver function ${resolverLogicFunctionIdentifier} requires authentication and cannot be dispatched through the public server route`,ServerRouteTriggerExceptionCode.RESOLVER_REQUIRES_AUTHENTICATION,);}@@ -96,7 +98,7 @@ export class ServerRouteTriggerService {if (!isDefined(applicationRegistrationId)) {throw new ServerRouteTriggerException(- `Server resolver function ${resolverLogicFunctionUniversalIdentifier} is not linked to an application registration`,+ `Server resolver function ${resolverLogicFunctionIdentifier} is not linked to an application registration`,ServerRouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND,);}@@ -123,44 +125,89 @@ export class ServerRouteTriggerService {}if (isLogicFunctionHttpResponse(resolverResult.data)) {- return buildRouteTriggerResponse(resolverResult.data);+ return {+ response: buildRouteTriggerResponse(resolverResult.data),+ isResolvedThroughLegacyIdentifier,+ };}const dispatchResult = parseResolverDispatchResultOrThrow(resolverResult.data,);- return await this.enqueueTargetFunction({- logicFunctionUniversalIdentifier:- dispatchResult.targetLogicFunctionUniversalIdentifier,- workspaceId: dispatchResult.workspaceId,- payload: dispatchResult.payload ?? event,- applicationRegistrationId,- });+ return {+ response: await this.enqueueTargetFunction({+ logicFunctionUniversalIdentifier:+ dispatchResult.targetLogicFunctionUniversalIdentifier,+ workspaceId: dispatchResult.workspaceId,+ payload: dispatchResult.payload ?? event,+ applicationRegistrationId,+ }),+ isResolvedThroughLegacyIdentifier,+ };}- private async findResolver({- logicFunctionUniversalIdentifier,- }: {- logicFunctionUniversalIdentifier: string;- }): Promise<LogicFunctionEntity | null> {- return (- (await this.logicFunctionRepository- .createQueryBuilder('logicFunction')- .innerJoinAndSelect('logicFunction.application', 'application')- .innerJoinAndSelect(- 'application.applicationRegistration',- 'applicationRegistration',- )- .where('logicFunction.universalIdentifier = :universalIdentifier', {- universalIdentifier: logicFunctionUniversalIdentifier,- })- .andWhere('logicFunction.serverRouteTriggerSettings IS NOT NULL')- .andWhere(- 'logicFunction.workspaceId = applicationRegistration.ownerWorkspaceId',- )- .getOne()) ?? null+ private createResolverQueryBuilder(): SelectQueryBuilder<LogicFunctionEntity> {+ return this.logicFunctionRepository+ .createQueryBuilder('logicFunction')+ .innerJoinAndSelect('logicFunction.application', 'application')+ .innerJoinAndSelect(+ 'application.applicationRegistration',+ 'applicationRegistration',+ )+ .where('logicFunction.serverRouteTriggerSettings IS NOT NULL')+ .andWhere(+ 'logicFunction.workspaceId = applicationRegistration.ownerWorkspaceId',+ );+ }++ private async findResolverOrThrow(+ identifier: string,+ ): Promise<ResolvedServerRouteResolver> {+ const resolverById = await this.createResolverQueryBuilder()+ .andWhere('logicFunction.id = :id', { id: identifier })+ .getOne();++ if (isDefined(resolverById)) {+ return {+ resolver: resolverById,+ isResolvedThroughLegacyIdentifier: false,+ };+ }++ const legacyCandidates = await this.createResolverQueryBuilder()+ .andWhere('logicFunction.universalIdentifier = :universalIdentifier', {+ universalIdentifier: identifier,+ })+ .limit(2)+ .getMany();++ if (legacyCandidates.length > 1) {+ this.logger.error(+ `Server route ${identifier} is claimed by ${legacyCandidates.length} application registrations (owner workspaces: ${legacyCandidates+ .map((candidate) => candidate.workspaceId)+ .join(', ')}); refusing to dispatch`,+ );+ }++ const legacyResolver =+ legacyCandidates.length === 1 ? legacyCandidates[0] : undefined;++ if (!isDefined(legacyResolver)) {+ throw new ServerRouteTriggerException(+ `Server resolver function ${identifier} not found`,+ ServerRouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND,+ );+ }++ this.logger.warn(+ `Server route ${identifier} resolved through the deprecated universalIdentifier form (application registration ${legacyResolver.application?.applicationRegistration?.universalIdentifier}, owner workspace ${legacyResolver.workspaceId}); the registered URL should move to /webhooks/server/${legacyResolver.id}`,);++ return {+ resolver: legacyResolver,+ isResolvedThroughLegacyIdentifier: true,+ };}private async enqueueTargetFunction({diff --git a/packages/twenty-server/test/integration/server-route-trigger/suites/__snapshots__/server-route-trigger-resolution.integration-spec.ts.snap b/packages/twenty-server/test/integration/server-route-trigger/suites/__snapshots__/server-route-trigger-resolution.integration-spec.ts.snapnew file mode 100644index 00000000000..eaa739a519b--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/suites/__snapshots__/server-route-trigger-resolution.integration-spec.ts.snap@@ -0,0 +1,43 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`ServerRouteTrigger resolver resolution (integration) by legacy universalIdentifier refuses to dispatch once a foreign workspace claims the same identifier 1`] = `+{+ "body": {+ "code": "LOGIC_FUNCTION_NOT_FOUND",+ "error": "Error",+ "messages": [+ "Server resolver function 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b not found",+ ],+ "statusCode": 404,+ },+ "status": 404,+}+`;++exports[`ServerRouteTrigger resolver resolution (integration) by primary key answers 404 for an id that resolves to nothing 1`] = `+{+ "body": {+ "code": "LOGIC_FUNCTION_NOT_FOUND",+ "error": "Error",+ "messages": [+ "Server resolver function 11111111-1111-4111-8111-111111111111 not found",+ ],+ "statusCode": 404,+ },+ "status": 404,+}+`;++exports[`ServerRouteTrigger resolver resolution (integration) by primary key rejects the id of a copy installed in a workspace that does not own the app 1`] = `+{+ "body": {+ "code": "LOGIC_FUNCTION_NOT_FOUND",+ "error": "Error",+ "messages": [+ "Server resolver function <installed copy id> not found",+ ],+ "statusCode": 404,+ },+ "status": 404,+}+`;diff --git a/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-resolution.integration-spec.ts b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-resolution.integration-spec.tsnew file mode 100644index 00000000000..495306e011f--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-resolution.integration-spec.ts@@ -0,0 +1,251 @@+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';+import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';+import { callServerRoute } from 'test/integration/server-route-trigger/utils/call-server-route.util';+import { findLogicFunctionId } from 'test/integration/server-route-trigger/utils/find-logic-function-id.util';+import {+ removeApplicationInstallFromForeignWorkspace,+ seedApplicationInstallInForeignWorkspace,+} from 'test/integration/server-route-trigger/utils/seed-application-install-in-foreign-workspace.util';+import {+ removeForeignServerRouteClaimant,+ seedForeignServerRouteClaimant,+} from 'test/integration/server-route-trigger/utils/seed-foreign-server-route-claimant.util';+import { expectOneNotInternalServerErrorHttpResponseSnapshot } from 'test/integration/utils/expect-one-not-internal-server-error-http-response-snapshot.util';+import { type LogicFunctionManifest } from 'twenty-shared/application';+import { LOGIC_FUNCTION_HTTP_RESPONSE_MARKER } from 'twenty-shared/types';++import { SERVER_ROUTE_LEGACY_IDENTIFIER_DEPRECATION_HEADER_VALUE } from 'src/engine/core-modules/server-route-trigger/constants/server-route-legacy-identifier-deprecation-header-value.constant';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++const OWNER_APP_UNIVERSAL_IDENTIFIER = '7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f';+const OWNER_ROLE_UNIVERSAL_IDENTIFIER = '8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a';++const OWNER_RESOLVER_UNIVERSAL_IDENTIFIER =+ '9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b';++const SQUATTER_APP_UNIVERSAL_IDENTIFIER =+ '0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3c';++const UNKNOWN_IDENTIFIER = '11111111-1111-4111-8111-111111111111';++const OWNER_RESPONSE = { answeredBy: 'owner' };++const OWNER_RESOLVER_BUILT_HANDLER_CODE = `export const main = async () => ({+ ${LOGIC_FUNCTION_HTTP_RESPONSE_MARKER}: true,+ status: 200,+ body: ${JSON.stringify(OWNER_RESPONSE)},+});+`;++const buildResolverManifest = (): LogicFunctionManifest => ({+ universalIdentifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ name: 'owner-resolver',+ handlerName: 'main',+ sourceHandlerPath: 'src/owner-resolver.ts',+ builtHandlerPath: 'dist/owner-resolver.mjs',+ builtHandlerChecksum: 'checksum-owner-resolver',+ serverRouteTriggerSettings: { forwardedRequestHeaders: [] },+});++const seedSquatter = ({+ resolverUniversalIdentifier,+}: {+ resolverUniversalIdentifier: string;+}) =>+ seedForeignServerRouteClaimant({+ applicationUniversalIdentifier: SQUATTER_APP_UNIVERSAL_IDENTIFIER,+ resolverUniversalIdentifier,+ });++const removeSquatter = () =>+ removeForeignServerRouteClaimant({+ applicationUniversalIdentifier: SQUATTER_APP_UNIVERSAL_IDENTIFIER,+ });++const seedOwnerAppInstall = () =>+ seedApplicationInstallInForeignWorkspace({+ applicationUniversalIdentifier: OWNER_APP_UNIVERSAL_IDENTIFIER,+ resolverUniversalIdentifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ });++const removeOwnerAppInstall = () =>+ removeApplicationInstallFromForeignWorkspace({+ applicationUniversalIdentifier: OWNER_APP_UNIVERSAL_IDENTIFIER,+ });++describe('ServerRouteTrigger resolver resolution (integration)', () => {+ let ownerResolverId: string;++ beforeAll(async () => {+ await setupApplicationForSync({+ applicationUniversalIdentifier: OWNER_APP_UNIVERSAL_IDENTIFIER,+ name: 'Server Route Resolution Owner App',+ description: 'App owning the public server route under test',+ sourcePath: 'server-route-resolution-owner-app',+ });++ jest.useRealTimers();+ await uploadApplicationFile({+ applicationUniversalIdentifier: OWNER_APP_UNIVERSAL_IDENTIFIER,+ fileFolder: 'BuiltLogicFunction',+ filePath: 'dist/owner-resolver.mjs',+ fileBuffer: Buffer.from(OWNER_RESOLVER_BUILT_HANDLER_CODE),+ filename: 'owner-resolver.mjs',+ contentType: 'application/javascript',+ expectToFail: false,+ });+ jest.useFakeTimers();++ await syncApplication({+ manifest: buildBaseManifest({+ appId: OWNER_APP_UNIVERSAL_IDENTIFIER,+ roleId: OWNER_ROLE_UNIVERSAL_IDENTIFIER,+ overrides: { logicFunctions: [buildResolverManifest()] },+ }),+ expectToFail: false,+ });++ ownerResolverId = await findLogicFunctionId({+ universalIdentifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ });+ }, 60000);++ afterAll(async () => {+ await removeSquatter();+ await removeOwnerAppInstall();+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: OWNER_APP_UNIVERSAL_IDENTIFIER,+ });+ }, 60000);++ describe('by primary key', () => {+ it('dispatches to the resolver and does not flag the response as deprecated', async () => {+ const response = await callServerRoute({ identifier: ownerResolverId });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(OWNER_RESPONSE);+ expect(response.headers['deprecation']).toBeUndefined();+ }, 60000);++ it('rejects the id of a copy installed in a workspace that does not own the app', async () => {+ const { logicFunctionId: installedCopyId } = await seedOwnerAppInstall();++ try {+ const response = await callServerRoute({+ identifier: installedCopyId,+ expectToFail: true,+ });++ expect(response.status).toBe(404);+ expectOneNotInternalServerErrorHttpResponseSnapshot({+ status: response.status,+ body: {+ ...response.body,+ messages: response.body.messages.map((message: string) =>+ message.replace(installedCopyId, '<installed copy id>'),+ ),+ },+ });+ } finally {+ await removeOwnerAppInstall();+ }+ }, 60000);++ it('answers 404 for an id that resolves to nothing', async () => {+ const response = await callServerRoute({+ identifier: UNKNOWN_IDENTIFIER,+ expectToFail: true,+ });++ expect(response.status).toBe(404);+ expectOneNotInternalServerErrorHttpResponseSnapshot({+ status: response.status,+ body: response.body,+ });+ });++ it('keeps dispatching while the legacy identifier is contested by a foreign workspace', async () => {+ await seedSquatter({+ resolverUniversalIdentifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ });++ try {+ const response = await callServerRoute({ identifier: ownerResolverId });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(OWNER_RESPONSE);+ } finally {+ await removeSquatter();+ }+ }, 60000);++ it('wins over a foreign resolver whose universalIdentifier equals this id', async () => {+ await seedSquatter({ resolverUniversalIdentifier: ownerResolverId });++ try {+ const response = await callServerRoute({ identifier: ownerResolverId });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(OWNER_RESPONSE);+ } finally {+ await removeSquatter();+ }+ }, 60000);+ });++ describe('by legacy universalIdentifier', () => {+ it('still dispatches and flags the response as deprecated', async () => {+ const response = await callServerRoute({+ identifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(OWNER_RESPONSE);+ expect(response.headers['deprecation']).toBe(+ SERVER_ROUTE_LEGACY_IDENTIFIER_DEPRECATION_HEADER_VALUE,+ );+ }, 60000);++ it('refuses to dispatch once a foreign workspace claims the same identifier', async () => {+ await seedSquatter({+ resolverUniversalIdentifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ });++ try {+ const response = await callServerRoute({+ identifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ body: { victimSecret: 'synthetic-webhook-body' },+ expectToFail: true,+ });++ expect(response.status).toBe(404);+ expect(response.body).not.toEqual(OWNER_RESPONSE);+ expectOneNotInternalServerErrorHttpResponseSnapshot({+ status: response.status,+ body: response.body,+ });+ } finally {+ await removeSquatter();+ }+ }, 60000);++ it('does not count a copy installed in another workspace as a claimant', async () => {+ await seedOwnerAppInstall();++ try {+ const response = await callServerRoute({+ identifier: OWNER_RESOLVER_UNIVERSAL_IDENTIFIER,+ });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(OWNER_RESPONSE);+ } finally {+ await removeOwnerAppInstall();+ }+ }, 60000);+ });+});diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/call-server-route.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/call-server-route.util.tsnew file mode 100644index 00000000000..15b192155eb--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/call-server-route.util.ts@@ -0,0 +1,42 @@+import request, { type Response } from 'supertest';+import { isDefined } from 'twenty-shared/utils';++type ServerRouteHttpMethod = 'get' | 'post' | 'head';++export const callServerRoute = async ({+ identifier,+ method = 'post',+ body = {},+ query,+ expectToFail = false,+}: {+ identifier: string;+ method?: ServerRouteHttpMethod;+ body?: object;+ query?: Record<string, string>;+ expectToFail?: boolean;+}): Promise<Response> => {+ const client = request(`http://localhost:${APP_PORT}`);++ let pendingRequest = client[method](`/webhooks/server/${identifier}`);++ if (isDefined(query)) {+ pendingRequest = pendingRequest.query(query);+ }++ if (method === 'post') {+ pendingRequest = pendingRequest.send(body);+ }++ const response = await pendingRequest;++ if (expectToFail === true) {+ expect(response.status).toBeGreaterThanOrEqual(400);+ }++ if (expectToFail === false) {+ expect(response.status).toBeLessThan(400);+ }++ return response;+};diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/find-logic-function-id.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/find-logic-function-id.util.tsnew file mode 100644index 00000000000..65d71d18053--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/find-logic-function-id.util.ts@@ -0,0 +1,15 @@+export const findLogicFunctionId = async ({+ universalIdentifier,+ workspaceId,+}: {+ universalIdentifier: string;+ workspaceId: string;+}): Promise<string> => {+ const [{ id }] = await globalThis.testDataSource.query(+ `SELECT id FROM core."logicFunction"+ WHERE "universalIdentifier" = $1 AND "workspaceId" = $2`,+ [universalIdentifier, workspaceId],+ );++ return id;+};diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/insert-application.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/insert-application.util.tsnew file mode 100644index 00000000000..345fe1b9f5d--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/insert-application.util.ts@@ -0,0 +1,28 @@+export const insertApplication = async ({+ universalIdentifier,+ name,+ workspaceId,+ applicationRegistrationId,+}: {+ universalIdentifier: string;+ name: string;+ workspaceId: string;+ applicationRegistrationId: string;+}): Promise<string> => {+ const [{ id }] = await globalThis.testDataSource.query(+ `INSERT INTO core."application"+ ("universalIdentifier", name, "sourcePath", "workspaceId",+ "applicationRegistrationId")+ VALUES ($1, $2, $3, $4, $5)+ RETURNING id`,+ [+ universalIdentifier,+ name,+ name.toLowerCase().replace(/\s+/g, '-'),+ workspaceId,+ applicationRegistrationId,+ ],+ );++ return id;+};diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/insert-server-route-logic-function.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/insert-server-route-logic-function.util.tsnew file mode 100644index 00000000000..be82c1a2532--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/insert-server-route-logic-function.util.ts@@ -0,0 +1,30 @@+export const insertServerRouteLogicFunction = async ({+ universalIdentifier,+ applicationId,+ workspaceId,+}: {+ universalIdentifier: string;+ applicationId: string;+ workspaceId: string;+}): Promise<string> => {+ const [{ id }] = await globalThis.testDataSource.query(+ `INSERT INTO core."logicFunction"+ ("universalIdentifier", name, "sourceHandlerPath", "builtHandlerPath",+ "handlerName", "serverRouteTriggerSettings", "applicationId",+ "workspaceId")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ RETURNING id`,+ [+ universalIdentifier,+ 'seeded-resolver',+ 'src/seeded-resolver.ts',+ 'dist/seeded-resolver.mjs',+ 'main',+ JSON.stringify({ forwardedRequestHeaders: [] }),+ applicationId,+ workspaceId,+ ],+ );++ return id;+};diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/seed-application-install-in-foreign-workspace.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/seed-application-install-in-foreign-workspace.util.tsnew file mode 100644index 00000000000..bc87d74c5d1--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/seed-application-install-in-foreign-workspace.util.ts@@ -0,0 +1,49 @@+import { insertApplication } from 'test/integration/server-route-trigger/utils/insert-application.util';+import { insertServerRouteLogicFunction } from 'test/integration/server-route-trigger/utils/insert-server-route-logic-function.util';++import { SEED_YCOMBINATOR_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++export const seedApplicationInstallInForeignWorkspace = async ({+ applicationUniversalIdentifier,+ resolverUniversalIdentifier,+ workspaceId = SEED_YCOMBINATOR_WORKSPACE_ID,+}: {+ applicationUniversalIdentifier: string;+ resolverUniversalIdentifier: string;+ workspaceId?: string;+}): Promise<{ logicFunctionId: string }> => {+ const [{ id: applicationRegistrationId }] =+ await globalThis.testDataSource.query(+ `SELECT id FROM core."applicationRegistration" WHERE "universalIdentifier" = $1`,+ [applicationUniversalIdentifier],+ );++ const applicationId = await insertApplication({+ universalIdentifier: applicationUniversalIdentifier,+ name: 'Installed copy',+ workspaceId,+ applicationRegistrationId,+ });++ const logicFunctionId = await insertServerRouteLogicFunction({+ universalIdentifier: resolverUniversalIdentifier,+ applicationId,+ workspaceId,+ });++ return { logicFunctionId };+};++export const removeApplicationInstallFromForeignWorkspace = async ({+ applicationUniversalIdentifier,+ workspaceId = SEED_YCOMBINATOR_WORKSPACE_ID,+}: {+ applicationUniversalIdentifier: string;+ workspaceId?: string;+}): Promise<void> => {+ await globalThis.testDataSource.query(+ `DELETE FROM core."application"+ WHERE "universalIdentifier" = $1 AND "workspaceId" = $2`,+ [applicationUniversalIdentifier, workspaceId],+ );+};diff --git a/packages/twenty-server/test/integration/server-route-trigger/utils/seed-foreign-server-route-claimant.util.ts b/packages/twenty-server/test/integration/server-route-trigger/utils/seed-foreign-server-route-claimant.util.tsnew file mode 100644index 00000000000..0966560161a--- /dev/null+++ b/packages/twenty-server/test/integration/server-route-trigger/utils/seed-foreign-server-route-claimant.util.ts@@ -0,0 +1,53 @@+import { insertCatalogApplicationRegistration } from 'test/integration/metadata/suites/application/utils/insert-catalog-application-registration.util';+import { insertApplication } from 'test/integration/server-route-trigger/utils/insert-application.util';+import { insertServerRouteLogicFunction } from 'test/integration/server-route-trigger/utils/insert-server-route-logic-function.util';++import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';+import { SEED_YCOMBINATOR_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++export const seedForeignServerRouteClaimant = async ({+ applicationUniversalIdentifier,+ resolverUniversalIdentifier,+ workspaceId = SEED_YCOMBINATOR_WORKSPACE_ID,+}: {+ applicationUniversalIdentifier: string;+ resolverUniversalIdentifier: string;+ workspaceId?: string;+}): Promise<{ logicFunctionId: string }> => {+ const applicationRegistrationId = await insertCatalogApplicationRegistration({+ universalIdentifier: applicationUniversalIdentifier,+ name: 'Foreign server route claimant',+ sourceType: ApplicationRegistrationSourceType.TARBALL,+ workspaceId,+ });++ const applicationId = await insertApplication({+ universalIdentifier: applicationUniversalIdentifier,+ name: 'Foreign server route claimant',+ workspaceId,+ applicationRegistrationId,+ });++ const logicFunctionId = await insertServerRouteLogicFunction({+ universalIdentifier: resolverUniversalIdentifier,+ applicationId,+ workspaceId,+ });++ return { logicFunctionId };+};++export const removeForeignServerRouteClaimant = async ({+ applicationUniversalIdentifier,+}: {+ applicationUniversalIdentifier: string;+}): Promise<void> => {+ await globalThis.testDataSource.query(+ `DELETE FROM core."application" WHERE "universalIdentifier" = $1`,+ [applicationUniversalIdentifier],+ );+ await globalThis.testDataSource.query(+ `DELETE FROM core."applicationRegistration" WHERE "universalIdentifier" = $1`,+ [applicationUniversalIdentifier],+ );+};