Skip to content

The open alternative to Salesforce, designed for AI.

Route server webhooks by application registration and function universalIdentifier (#29204)

Charles Bochete46a4c7e7636
diff --git a/packages/twenty-agent-skills/references/concepts/how-apps-work.md b/packages/twenty-agent-skills/references/concepts/how-apps-work.md
index c3fd5501607..0835e2b1d53 100644
--- a/packages/twenty-agent-skills/references/concepts/how-apps-work.md
+++ b/packages/twenty-agent-skills/references/concepts/how-apps-work.md
@@ -110,4 +110,4 @@ my-app/
- **Remotes**: Named connections to Twenty instances. Stored in `~/.twenty/config.json`. Switch with `twenty remote use <name>`.
- **Sync**: `twenty app apply` builds, deploys, and installs the app on the active remote in one step. This is the standard way to get code changes onto a Twenty instance.
- **Publish**: `twenty app publish` packages the app for distribution to other instances or the marketplace. Requires a strictly higher semver version than the previously published version.
-- **Reserved variable names**: `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL` and `APPLICATION_ID` are set by Twenty for every logic function run, and every other name starting with `TWENTY_` is kept for variables Twenty adds later. A manifest that declares a reserved name as an application or server variable is rejected on sync and publish.
+- **Reserved variable names**: `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL`, `TWENTY_SERVER_ROUTES_URL` and `APPLICATION_ID` are set by Twenty for every logic function run, and every other name starting with `TWENTY_` is kept for variables Twenty adds later. A manifest that declares a reserved name as an application or server variable is rejected on sync and publish.
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 694078fd228..734d72641a2 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -22,7 +22,8 @@ Other rules:
- Prefer idempotent behavior for jobs and repeated invocations.
- Read secrets through the application-config helper, not raw `process.env`.
- An application variable declared with `scope: 'USER'` is in `process.env` with the value of the member who triggered the run, or its default until they set their own; a run nobody triggered (cron, install hooks) gets no user variables. That member is not always the one the run is about: a database event runs as whoever edited the record. For example, with a user `SLACK_TOKEN`, a function on opportunity update posts with the editor's token, not the opportunity owner's. When the run is about someone else or every member, read the values with `myUserApplicationVariables` through `new MetadataApiClient({ runAs: 'application' })`.
-- Twenty injects `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL` and `APPLICATION_ID` into every run. Never declare an application or server variable with one of these names, or any other name starting with `TWENTY_`: the manifest is rejected on sync and publish.
+- Twenty injects `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL`, `TWENTY_SERVER_ROUTES_URL` and `APPLICATION_ID` into every run. Never declare an application or server variable with one of these names, or any other name starting with `TWENTY_`: the manifest is rejected on sync and publish.
+- To register a server route with a webhook provider, build its URL with `getServerRouteUrl(logicFunctionUniversalIdentifier)` from `twenty-sdk/utils`. It returns `/webhooks/server/<applicationRegistrationId>/<logicFunctionUniversalIdentifier>` on the server's URL, and only works inside a logic function of an application. Do not build the URL by hand.
- Do not hide customer-impacting side effects behind UI-only actions.
Soft cap: a `*.logic-function.ts` or `*.post-install.ts` file over 200 lines is a refactor signal.
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts
index 12bdd44f4b4..3695e86e2fd 100644
--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts
@@ -1,8 +1,28 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { getFathomWebhookDestinationUrl } from 'src/logic-functions/utils/get-fathom-webhook-destination-url.util';
describe('getFathomWebhookDestinationUrl', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('builds the URL from the injected server routes URL', () => {
+ vi.stubEnv(
+ 'TWENTY_SERVER_ROUTES_URL',
+ 'https://twenty.example.com/webhooks/server/4f0e2a51-9c3b-4d8e-a1f7-6b2c9d0e3a14',
+ );
+
+ expect(
+ getFathomWebhookDestinationUrl({
+ apiUrl: 'https://twenty.example.com',
+ connectedAccountId: 'connection-id',
+ }),
+ ).toBe(
+ 'https://twenty.example.com/webhooks/server/4f0e2a51-9c3b-4d8e-a1f7-6b2c9d0e3a14/72b52885-e1ba-419f-8e2e-052700f2c9f2?connectionId=connection-id',
+ );
+ });
+
it('builds the server route with the connection identifier', () => {
expect(
getFathomWebhookDestinationUrl({
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts
index 30e5c8b211b..c2b5029aa15 100644
--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts
@@ -1,5 +1,6 @@
import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';
import { FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { getServerRouteUrl } from 'src/logic-functions/utils/get-server-route-url.util';
export const getFathomWebhookDestinationUrl = ({
apiUrl,
@@ -8,10 +9,11 @@ export const getFathomWebhookDestinationUrl = ({
apiUrl: string;
connectedAccountId: string;
}): string => {
- const destinationUrl = new URL(apiUrl);
- const apiBasePath = destinationUrl.pathname.replace(/\/+$/, '');
-
- destinationUrl.pathname = `${apiBasePath}/webhooks/server/${FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;
+ const destinationUrl = getServerRouteUrl({
+ apiUrl,
+ logicFunctionUniversalIdentifier:
+ FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
destinationUrl.searchParams.set(
FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER,
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-server-route-url.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-server-route-url.util.ts
new file mode 100644
index 00000000000..1b3ced954e0
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-server-route-url.util.ts
@@ -0,0 +1,22 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+// TODO(@charlesBochet): delete once the app's twenty-sdk ships getServerRouteUrl.
+export const getServerRouteUrl = ({
+ apiUrl,
+ logicFunctionUniversalIdentifier,
+}: {
+ apiUrl: string;
+ logicFunctionUniversalIdentifier: string;
+}): URL => {
+ const serverRoutesUrl = process.env.TWENTY_SERVER_ROUTES_URL;
+ const serverRouteUrl = new URL(
+ isNonEmptyString(serverRoutesUrl) ? serverRoutesUrl : apiUrl,
+ );
+ const basePath = serverRouteUrl.pathname.replace(/\/+$/, '');
+
+ serverRouteUrl.pathname = isNonEmptyString(serverRoutesUrl)
+ ? `${basePath}/${logicFunctionUniversalIdentifier}`
+ : `${basePath}/webhooks/server/${logicFunctionUniversalIdentifier}`;
+
+ return serverRouteUrl;
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts
index 3c4c44b1b69..04d2bd9c278 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/__tests__/get-granola-webhook-destination-url-or-throw.test.ts
@@ -1,8 +1,28 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { getGranolaWebhookDestinationUrlOrThrow } from 'src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util';
describe('getGranolaWebhookDestinationUrlOrThrow', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('builds the URL from the injected server routes URL', () => {
+ vi.stubEnv(
+ 'TWENTY_SERVER_ROUTES_URL',
+ 'https://crm.example.com/webhooks/server/4f0e2a51-9c3b-4d8e-a1f7-6b2c9d0e3a14',
+ );
+
+ expect(
+ getGranolaWebhookDestinationUrlOrThrow({
+ apiUrl: 'https://crm.example.com/',
+ registrationId: 'reg-1',
+ }),
+ ).toBe(
+ 'https://crm.example.com/webhooks/server/4f0e2a51-9c3b-4d8e-a1f7-6b2c9d0e3a14/91dd18b2-ddfd-4516-bda6-db0e3a2d3e33?registrationId=reg-1',
+ );
+ });
+
it('builds the server route under the API URL with the registration id', () => {
expect(
getGranolaWebhookDestinationUrlOrThrow({
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts
index 01400a6949d..04dc0344a1b 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-granola-webhook-destination-url-or-throw.util.ts
@@ -1,4 +1,5 @@
import { GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { getServerRouteUrl } from 'src/logic-functions/utils/get-server-route-url.util';
export const getGranolaWebhookDestinationUrlOrThrow = ({
apiUrl,
@@ -7,11 +8,14 @@ export const getGranolaWebhookDestinationUrlOrThrow = ({
apiUrl: string;
registrationId: string;
}): string => {
- const destinationUrl = new URL(apiUrl);
+ const destinationUrl = getServerRouteUrl({
+ apiUrl,
+ logicFunctionUniversalIdentifier:
+ GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
if (destinationUrl.protocol !== 'https:') {
throw new Error('Granola requires a public HTTPS Twenty server URL.');
}
- destinationUrl.pathname = `${destinationUrl.pathname.replace(/\/+$/, '')}/webhooks/server/${GRANOLA_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;
destinationUrl.search = '';
destinationUrl.hash = '';
destinationUrl.searchParams.set('registrationId', registrationId);
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/get-server-route-url.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-server-route-url.util.ts
new file mode 100644
index 00000000000..1b3ced954e0
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/get-server-route-url.util.ts
@@ -0,0 +1,22 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+// TODO(@charlesBochet): delete once the app's twenty-sdk ships getServerRouteUrl.
+export const getServerRouteUrl = ({
+ apiUrl,
+ logicFunctionUniversalIdentifier,
+}: {
+ apiUrl: string;
+ logicFunctionUniversalIdentifier: string;
+}): URL => {
+ const serverRoutesUrl = process.env.TWENTY_SERVER_ROUTES_URL;
+ const serverRouteUrl = new URL(
+ isNonEmptyString(serverRoutesUrl) ? serverRoutesUrl : apiUrl,
+ );
+ const basePath = serverRouteUrl.pathname.replace(/\/+$/, '');
+
+ serverRouteUrl.pathname = isNonEmptyString(serverRoutesUrl)
+ ? `${basePath}/${logicFunctionUniversalIdentifier}`
+ : `${basePath}/webhooks/server/${logicFunctionUniversalIdentifier}`;
+
+ return serverRouteUrl;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts
index 4aa938dc7f1..35139addc26 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts
@@ -1,5 +1,6 @@
import { TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
import { TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter';
+import { getServerRouteUrl } from 'src/utils/get-server-route-url';
export const buildTeamsTranscriptsWebhookUrl = ({
apiUrl,
@@ -8,10 +9,12 @@ export const buildTeamsTranscriptsWebhookUrl = ({
apiUrl: string;
connectedAccountId: string;
}): string => {
- const webhookUrl = new URL(apiUrl);
- const apiBasePath = webhookUrl.pathname.replace(/\/+$/, '');
+ const webhookUrl = getServerRouteUrl({
+ apiUrl,
+ logicFunctionUniversalIdentifier:
+ TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
- webhookUrl.pathname = `${apiBasePath}/webhooks/server/${TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;
webhookUrl.searchParams.set(
TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER,
connectedAccountId,
diff --git a/packages/twenty-apps/public/teams/src/utils/get-server-route-url.ts b/packages/twenty-apps/public/teams/src/utils/get-server-route-url.ts
new file mode 100644
index 00000000000..1b3ced954e0
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/utils/get-server-route-url.ts
@@ -0,0 +1,22 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+// TODO(@charlesBochet): delete once the app's twenty-sdk ships getServerRouteUrl.
+export const getServerRouteUrl = ({
+ apiUrl,
+ logicFunctionUniversalIdentifier,
+}: {
+ apiUrl: string;
+ logicFunctionUniversalIdentifier: string;
+}): URL => {
+ const serverRoutesUrl = process.env.TWENTY_SERVER_ROUTES_URL;
+ const serverRouteUrl = new URL(
+ isNonEmptyString(serverRoutesUrl) ? serverRoutesUrl : apiUrl,
+ );
+ const basePath = serverRouteUrl.pathname.replace(/\/+$/, '');
+
+ serverRouteUrl.pathname = isNonEmptyString(serverRoutesUrl)
+ ? `${basePath}/${logicFunctionUniversalIdentifier}`
+ : `${basePath}/webhooks/server/${logicFunctionUniversalIdentifier}`;
+
+ return serverRouteUrl;
+};
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index a63fda3d3cf..d39d8b49b7c 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -54,7 +54,7 @@ Notes:
- An app can report its own configuration state with [`defineHealthCheck()`](/developers/extend/apps/logic/logic-functions#health-check), for what only the app can know — a key that is present but revoked, a third-party account on the wrong plan. `isRequired` covers what Twenty can see by itself; the health check covers the rest.
- Both kinds of variable accept `isRequired: true`. A required variable the workspace has not filled in yet leaves the app unconfigured: its settings page shows a banner naming the missing variables, with a button that jumps to the tab where they are set. Mark as required only what the app genuinely cannot run without — an optional variable with a sensible default should stay optional.
- Both kinds of variable accept `isDeprecated: true`. Use it to retire a variable instead of deleting it: keeping the key declared preserves the stored value (deleting it destroys the value the operator entered), and the variable is still injected, so your code can fall back to it — `process.env.NEW_API_KEY ?? process.env.API_KEY`. A deprecated variable disappears from the app's settings once it has no value, and never counts toward the app's configuration check, so `isDeprecated` beats `isRequired`.
-- Twenty sets these names for every logic function run, so they are reserved: `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL` and `APPLICATION_ID`. Every other name starting with `TWENTY_` is reserved too, for variables Twenty adds later. A manifest that declares a reserved name as an application or server variable is rejected when the app is synced or published.
+- Twenty sets these names for every logic function run, so they are reserved: `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL`, `TWENTY_SERVER_ROUTES_URL` and `APPLICATION_ID`. Every other name starting with `TWENTY_` is reserved too, for variables Twenty adds later. A manifest that declares a reserved name as an application or server variable is rejected when the app is synced or published.
- To add your own entries to the app's settings menu (in place of the generated **Variables** page), declare a front component and point a [`defineSettingsMenuItem()`](/developers/extend/apps/layout/front-components#settings-menu-items) at it, in its own file. Declare as many as you need and order them with `position`; `scope` puts an item under the workspace settings or under each member's own settings. The system-managed **General** item (auto-upgrade, App URL, connections) always comes first, and App URL only shows when the app has HTTP-triggered functions.
## Requested media capabilities
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 5dc2abea26e..2b40491652b 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -293,28 +293,25 @@ export default defineLogicFunction({
The endpoint is reachable at:
```
-POST https://your-twenty-server.com/webhooks/server/:resolverLogicFunctionId
+POST https://your-twenty-server.com/webhooks/server/:applicationRegistrationId/:resolverLogicFunctionUniversalIdentifier
```
-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:
+The first segment is your app registration's id, the second the resolver's `universalIdentifier` from your manifest. A route only resolves to a resolver of that registration, in its owner workspace. When your app registers the webhook itself, build the URL from inside a logic function with `getServerRouteUrl`; Twenty injects the base URL of your app's server routes as `TWENTY_SERVER_ROUTES_URL`:
-```graphql
-query {
- findManyLogicFunctions {
- id
- name
- universalIdentifier
- }
-}
+```ts
+import { getServerRouteUrl } from 'twenty-sdk/utils';
+
+const destinationUrl = getServerRouteUrl(
+ INVOICE_PAID_RESOLVER_UNIVERSAL_IDENTIFIER,
+);
```
<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.
+ URLs carrying only the resolver's `id` or `universalIdentifier`
+ (`/webhooks/server/:identifier`) still resolve for now. The
+ `universalIdentifier` form answers with a `Deprecation` header and returns
+ `404` when two registrations declare the same identifier. Move the URLs
+ registered with your providers to the registration 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-sdk/src/sdk/utils/__tests__/get-server-route-url.test.ts b/packages/twenty-sdk/src/sdk/utils/__tests__/get-server-route-url.test.ts
new file mode 100644
index 00000000000..b404799be03
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/utils/__tests__/get-server-route-url.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getServerRouteUrl } from '@/sdk/utils/get-server-route-url';
+
+const RESOLVER_UNIVERSAL_IDENTIFIER = '72b52885-e1ba-419f-8e2e-052700f2c9f2';
+const APPLICATION_REGISTRATION_ID = '4f0e2a51-9c3b-4d8e-a1f7-6b2c9d0e3a14';
+
+describe('getServerRouteUrl', () => {
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_SERVER_ROUTES_URL', '');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('should append the logic function universal identifier to the routes URL', () => {
+ vi.stubEnv(
+ 'TWENTY_SERVER_ROUTES_URL',
+ `https://api.twenty.com/webhooks/server/${APPLICATION_REGISTRATION_ID}`,
+ );
+
+ expect(getServerRouteUrl(RESOLVER_UNIVERSAL_IDENTIFIER)).toBe(
+ `https://api.twenty.com/webhooks/server/${APPLICATION_REGISTRATION_ID}/${RESOLVER_UNIVERSAL_IDENTIFIER}`,
+ );
+ });
+
+ it('should throw outside the app runtime', () => {
+ expect(() => getServerRouteUrl(RESOLVER_UNIVERSAL_IDENTIFIER)).toThrow();
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/utils/get-server-route-url.ts b/packages/twenty-sdk/src/sdk/utils/get-server-route-url.ts
new file mode 100644
index 00000000000..096babc306d
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/utils/get-server-route-url.ts
@@ -0,0 +1,16 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { DEFAULT_SERVER_ROUTES_URL_NAME } from 'twenty-shared/application-runtime';
+
+export const getServerRouteUrl = (
+ logicFunctionUniversalIdentifier: string,
+): string => {
+ const serverRoutesUrl = process.env[DEFAULT_SERVER_ROUTES_URL_NAME];
+
+ if (!isNonEmptyString(serverRoutesUrl)) {
+ throw new Error(
+ 'getServerRouteUrl can only be called from within a logic function of an application',
+ );
+ }
+
+ return `${serverRoutesUrl}/${logicFunctionUniversalIdentifier}`;
+};
diff --git a/packages/twenty-sdk/src/sdk/utils/index.ts b/packages/twenty-sdk/src/sdk/utils/index.ts
index 539fee95303..9255c976ab4 100644
--- a/packages/twenty-sdk/src/sdk/utils/index.ts
+++ b/packages/twenty-sdk/src/sdk/utils/index.ts
@@ -1,2 +1,3 @@
export { getPublicAssetUrl } from '@/sdk/utils/get-public-asset-url';
+export { getServerRouteUrl } from '@/sdk/utils/get-server-route-url';
export { isDefined } from 'twenty-shared/utils';
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/engine-injected-env-variable-names.constant.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/engine-injected-env-variable-names.constant.ts
index cdc7b6be295..694832bc725 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/engine-injected-env-variable-names.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/engine-injected-env-variable-names.constant.ts
@@ -4,6 +4,7 @@ import {
DEFAULT_APP_ACCESS_TOKEN_NAME,
DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
DEFAULT_FUNCTIONS_URL_NAME,
+ DEFAULT_SERVER_ROUTES_URL_NAME,
} from 'twenty-shared/application-runtime';
export const ENGINE_INJECTED_ENV_VARIABLE_NAMES = new Set<string>([
@@ -12,5 +13,6 @@ export const ENGINE_INJECTED_ENV_VARIABLE_NAMES = new Set<string>([
DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
DEFAULT_API_KEY_NAME,
DEFAULT_FUNCTIONS_URL_NAME,
+ DEFAULT_SERVER_ROUTES_URL_NAME,
'APPLICATION_ID',
]);
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index e8cb9dc2943..a60dfc38e2a 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -9,6 +9,7 @@ import {
DEFAULT_APP_ACCESS_TOKEN_NAME,
DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
DEFAULT_FUNCTIONS_URL_NAME,
+ DEFAULT_SERVER_ROUTES_URL_NAME,
} from 'twenty-shared/application-runtime';
import {
type LogicFunctionExecutionContext,
@@ -43,6 +44,7 @@ import { buildLogicFunctionErrorLogLine } from 'src/engine/core-modules/logic-fu
import { buildLogicFunctionExecutionUsage } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util';
import { buildLogicFunctionRunMetricEvent } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-run-metric-event.util';
import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
+import { SERVER_ROUTE_PATH } from 'src/engine/core-modules/server-route-trigger/constants/server-route-path.constant';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import {
ThrottlerException,
@@ -488,6 +490,11 @@ export class LogicFunctionExecutorService {
[DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME]: applicationAccessToken.token,
[DEFAULT_API_KEY_NAME]: applicationAccessToken.token,
[DEFAULT_FUNCTIONS_URL_NAME]: functionsBaseUrl ?? '',
+ [DEFAULT_SERVER_ROUTES_URL_NAME]: isDefined(
+ flatApplication.applicationRegistrationId,
+ )
+ ? `${baseUrl ?? ''}/${SERVER_ROUTE_PATH}/${flatApplication.applicationRegistrationId}`
+ : '',
APPLICATION_ID: flatApplication.id,
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-path.constant.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-path.constant.ts
new file mode 100644
index 00000000000..dd9bd48d736
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/constants/server-route-path.constant.ts
@@ -0,0 +1,3 @@
+import { ApiPath } from 'twenty-shared/types';
+
+export const SERVER_ROUTE_PATH = `${ApiPath.Webhooks}/server`;
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.ts
index 073c3a749c0..6d1fa5552e2 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
@@ -10,18 +10,18 @@ import {
} from '@nestjs/common';
import { Request, Response } from 'express';
-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 { SERVER_ROUTE_PATH } from 'src/engine/core-modules/server-route-trigger/constants/server-route-path.constant';
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';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
-@Controller(`${ApiPath.Webhooks}/server`)
+@Controller(SERVER_ROUTE_PATH)
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
@UseFilters(
ServerRouteTriggerRestApiExceptionFilter,
@@ -33,15 +33,22 @@ export class ServerRouteTriggerController {
private readonly serverRouteTriggerService: ServerRouteTriggerService,
) {}
- private async handleRequest(
- resolverLogicFunctionIdentifier: string,
- request: Request,
- response: Response,
- ) {
+ private async handleRequest({
+ resolverLogicFunctionIdentifier,
+ resolverApplicationRegistrationId,
+ request,
+ response,
+ }: {
+ resolverLogicFunctionIdentifier: string;
+ resolverApplicationRegistrationId?: string;
+ request: Request;
+ response: Response;
+ }) {
const { response: triggerResponse, isResolvedThroughLegacyIdentifier } =
await this.serverRouteTriggerService.handle({
request,
resolverLogicFunctionIdentifier,
+ resolverApplicationRegistrationId,
});
if (isResolvedThroughLegacyIdentifier) {
@@ -54,6 +61,40 @@ export class ServerRouteTriggerController {
sendRouteTriggerResponse(response, triggerResponse);
}
+ @Get(':resolverApplicationRegistrationId/:resolverLogicFunctionIdentifier')
+ async getInApplicationRegistration(
+ @Param('resolverApplicationRegistrationId')
+ resolverApplicationRegistrationId: string,
+ @Param('resolverLogicFunctionIdentifier')
+ resolverLogicFunctionIdentifier: string,
+ @Req() request: Request,
+ @Res() response: Response,
+ ) {
+ await this.handleRequest({
+ resolverLogicFunctionIdentifier,
+ resolverApplicationRegistrationId,
+ request,
+ response,
+ });
+ }
+
+ @Post(':resolverApplicationRegistrationId/:resolverLogicFunctionIdentifier')
+ async postInApplicationRegistration(
+ @Param('resolverApplicationRegistrationId')
+ resolverApplicationRegistrationId: string,
+ @Param('resolverLogicFunctionIdentifier')
+ resolverLogicFunctionIdentifier: string,
+ @Req() request: Request,
+ @Res() response: Response,
+ ) {
+ await this.handleRequest({
+ resolverLogicFunctionIdentifier,
+ resolverApplicationRegistrationId,
+ request,
+ response,
+ });
+ }
+
@Get(':resolverLogicFunctionIdentifier')
async get(
@Param('resolverLogicFunctionIdentifier')
@@ -61,11 +102,11 @@ export class ServerRouteTriggerController {
@Req() request: Request,
@Res() response: Response,
) {
- await this.handleRequest(
+ await this.handleRequest({
resolverLogicFunctionIdentifier,
request,
response,
- );
+ });
}
@Post(':resolverLogicFunctionIdentifier')
@@ -75,10 +116,10 @@ export class ServerRouteTriggerController {
@Req() request: Request,
@Res() response: Response,
) {
- await this.handleRequest(
+ await this.handleRequest({
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.ts
index 9d584b58d0e..c936e09e305 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
@@ -34,6 +34,7 @@ import {
import { ServerRouteAuthorizationHeaderService } from 'src/engine/core-modules/server-route-trigger/server-route-authorization-header.service';
import { buildServerRouteFailureLogEntry } from 'src/engine/core-modules/server-route-trigger/utils/build-server-route-failure-log-entry.util';
import { isAppFacingServerRouteError } from 'src/engine/core-modules/server-route-trigger/utils/is-app-facing-server-route-error.util';
+import { isUuidShaped } from 'src/engine/core-modules/server-route-trigger/utils/is-uuid-shaped.util';
import { parseResolverDispatchResultOrThrow } from 'src/engine/core-modules/server-route-trigger/utils/parse-resolver-dispatch-result-or-throw.util';
import { SERVER_ROUTE_FORWARDABLE_CREDENTIAL_HEADER_NAME } from 'src/engine/metadata-modules/logic-function/constants/server-route-forwardable-credential-header-name.constant';
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -73,12 +74,20 @@ export class ServerRouteTriggerService {
async handle({
request,
resolverLogicFunctionIdentifier,
+ resolverApplicationRegistrationId,
}: {
request: Request;
resolverLogicFunctionIdentifier: string;
+ resolverApplicationRegistrationId?: string;
}): Promise<ServerRouteTriggerResult> {
- const { resolver, isResolvedThroughLegacyIdentifier } =
- await this.findResolverOrThrow(resolverLogicFunctionIdentifier);
+ const { resolver, isResolvedThroughLegacyIdentifier } = isDefined(
+ resolverApplicationRegistrationId,
+ )
+ ? await this.findRegistrationResolverOrThrow({
+ applicationRegistrationId: resolverApplicationRegistrationId,
+ logicFunctionUniversalIdentifier: resolverLogicFunctionIdentifier,
+ })
+ : await this.findResolverOrThrow(resolverLogicFunctionIdentifier);
const applicationRegistrationId =
resolver.application?.applicationRegistration?.id;
@@ -226,6 +235,43 @@ export class ServerRouteTriggerService {
);
}
+ private async findRegistrationResolverOrThrow({
+ applicationRegistrationId,
+ logicFunctionUniversalIdentifier,
+ }: {
+ applicationRegistrationId: string;
+ logicFunctionUniversalIdentifier: string;
+ }): Promise<ResolvedServerRouteResolver> {
+ const buildNotFoundException = () =>
+ new ServerRouteTriggerException(
+ `Server resolver function ${logicFunctionUniversalIdentifier} not found in application registration ${applicationRegistrationId}`,
+ ServerRouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
+ );
+
+ if (
+ !isUuidShaped(applicationRegistrationId) ||
+ !isUuidShaped(logicFunctionUniversalIdentifier)
+ ) {
+ throw buildNotFoundException();
+ }
+
+ const resolver = await this.createResolverQueryBuilder()
+ .andWhere('applicationRegistration.id = :applicationRegistrationId', {
+ applicationRegistrationId,
+ })
+ .andWhere(
+ 'logicFunction.universalIdentifier = :logicFunctionUniversalIdentifier',
+ { logicFunctionUniversalIdentifier },
+ )
+ .getOne();
+
+ if (!isDefined(resolver)) {
+ throw buildNotFoundException();
+ }
+
+ return { resolver, isResolvedThroughLegacyIdentifier: false };
+ }
+
private async findResolverOrThrow(
identifier: string,
): Promise<ResolvedServerRouteResolver> {
@@ -266,7 +312,7 @@ export class ServerRouteTriggerService {
}
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}`,
+ `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.application?.applicationRegistration?.id}/${legacyResolver.universalIdentifier}`,
);
return {
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/__tests__/is-uuid-shaped.util.spec.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/__tests__/is-uuid-shaped.util.spec.ts
new file mode 100644
index 00000000000..e206c3c1ba1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/__tests__/is-uuid-shaped.util.spec.ts
@@ -0,0 +1,19 @@
+import { isUuidShaped } from 'src/engine/core-modules/server-route-trigger/utils/is-uuid-shaped.util';
+
+describe('isUuidShaped', () => {
+ it.each([
+ '72b52885-e1ba-419f-8e2e-052700f2c9f2',
+ '0192f5b8-7c3d-7a10-9e4b-2f6d8c1a3b5e',
+ '20202020-b3a4-0ef2-c94b-c3f5e8a1d6b7',
+ '00000000-0000-0000-0000-000000000000',
+ ])('accepts %s', (value) => {
+ expect(isUuidShaped(value)).toBe(true);
+ });
+
+ it.each(['not-a-uuid', '72b52885e1ba419f8e2e052700f2c9f2', ''])(
+ 'rejects %s',
+ (value) => {
+ expect(isUuidShaped(value)).toBe(false);
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/is-uuid-shaped.util.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/is-uuid-shaped.util.ts
new file mode 100644
index 00000000000..03fbc07380c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/utils/is-uuid-shaped.util.ts
@@ -0,0 +1,6 @@
+// Matches what a Postgres uuid column accepts, whatever the UUID version.
+const UUID_SHAPE_REGEX =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export const isUuidShaped = (value: string): boolean =>
+ UUID_SHAPE_REGEX.test(value);
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index fa468b09480..993810b25d7 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -526,7 +526,9 @@ exports[`endpoint permission declarations should match the auth principals, perm
"SearchResolver.search {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"SendEmailResolver.sendEmail {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["SEND_EMAIL_TOOL"]}",
"ServerRouteTriggerController.get {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "ServerRouteTriggerController.getInApplicationRegistration {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ServerRouteTriggerController.post {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "ServerRouteTriggerController.postInApplicationRegistration {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"SkillResolver.activateSkill {"applicationTarget":{"argName":"id","kind":"applicationOwnedEntity","metadataName":"skill","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI","AI_SETTINGS"]}",
"SkillResolver.createSkill {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI","AI_SETTINGS"]}",
"SkillResolver.deactivateSkill {"applicationTarget":{"argName":"id","kind":"applicationOwnedEntity","metadataName":"skill","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI","AI_SETTINGS"]}",
diff --git a/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-authorization.integration-spec.ts b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-authorization.integration-spec.ts
index c2bc259924b..928d9421240 100644
--- a/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-authorization.integration-spec.ts
+++ b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-trigger-authorization.integration-spec.ts
@@ -37,6 +37,20 @@ const GET_HANDSHAKE_RESOLVER_UNIVERSAL_IDENTIFIER =
'6f6f983f-5c1a-4c60-a3c8-7d0e2a4a66f6';
const AUTHORIZATION_ECHO_RESOLVER_UNIVERSAL_IDENTIFIER =
'7a7f983f-5c1a-4c60-a3c8-7d0e2a4a77a7';
+const ROUTES_URL_ECHO_RESOLVER_UNIVERSAL_IDENTIFIER =
+ '8b8f983f-5c1a-4c60-a3c8-7d0e2a4a88b8';
+
+const OTHER_APPLICATION_REGISTRATION_ID =
+ '9c9f983f-5c1a-4c60-a3c8-7d0e2a4a99c9';
+
+const findApplicationRegistrationId = async (): Promise<string> => {
+ const [{ id }]: { id: string }[] = await globalThis.testDataSource.query(
+ `SELECT id FROM core."applicationRegistration" WHERE "universalIdentifier" = $1`,
+ [APP_UNIVERSAL_IDENTIFIER],
+ );
+
+ return id;
+};
const TARGET_FUNCTION_RESPONSE = { greeting: 'hello from target function' };
@@ -72,6 +86,13 @@ const AUTHORIZATION_ECHO_RESOLVER_BUILT_HANDLER_CODE = `export const main = asyn
});
`;
+const ROUTES_URL_ECHO_RESOLVER_BUILT_HANDLER_CODE = `export const main = async () => ({
+ ${LOGIC_FUNCTION_HTTP_RESPONSE_MARKER}: true,
+ status: 200,
+ body: { serverRoutesUrl: process.env.TWENTY_SERVER_ROUTES_URL },
+});
+`;
+
const TARGET_BUILT_HANDLER_CODE = `export const main = async () => (${JSON.stringify(
TARGET_FUNCTION_RESPONSE,
)});
@@ -170,6 +191,11 @@ describe('ServerRouteTrigger authorization (integration)', () => {
builtHandlerCode: AUTHORIZATION_ECHO_RESOLVER_BUILT_HANDLER_CODE,
});
+ await uploadBuiltHandlerFile({
+ builtHandlerPath: 'dist/routes-url-echo-resolver.mjs',
+ builtHandlerCode: ROUTES_URL_ECHO_RESOLVER_BUILT_HANDLER_CODE,
+ });
+
await uploadBuiltHandlerFile({
builtHandlerPath: 'dist/target-function.mjs',
builtHandlerCode: TARGET_BUILT_HANDLER_CODE,
@@ -220,6 +246,13 @@ describe('ServerRouteTrigger authorization (integration)', () => {
authRequired: false,
forwardedRequestHeaders: ['authorization'],
}),
+ buildLogicFunctionManifest({
+ universalIdentifier:
+ ROUTES_URL_ECHO_RESOLVER_UNIVERSAL_IDENTIFIER,
+ name: 'routes-url-echo-resolver',
+ serverRouteExposed: true,
+ authRequired: false,
+ }),
buildLogicFunctionManifest({
universalIdentifier: TARGET_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'target-function',
@@ -270,6 +303,56 @@ describe('ServerRouteTrigger authorization (integration)', () => {
expect(response.body).toEqual({ challenge: 'abc123' });
}, 60000);
+ it('gives the resolver the server routes URL of its application registration', async () => {
+ const applicationRegistrationId = await findApplicationRegistrationId();
+
+ const response = await request(baseUrl)
+ .post(
+ `/webhooks/server/${applicationRegistrationId}/${ROUTES_URL_ECHO_RESOLVER_UNIVERSAL_IDENTIFIER}`,
+ )
+ .send({});
+
+ expect(response.status).toBe(200);
+ expect(response.body.serverRoutesUrl).toMatch(
+ new RegExp(`/webhooks/server/${applicationRegistrationId}$`),
+ );
+ }, 60000);
+
+ it('answers through the application registration scoped route', async () => {
+ const applicationRegistrationId = await findApplicationRegistrationId();
+
+ const response = await request(baseUrl)
+ .post(
+ `/webhooks/server/${applicationRegistrationId}/${HANDSHAKE_RESOLVER_UNIVERSAL_IDENTIFIER}`,
+ )
+ .send({ type: 'url_verification', challenge: 'abc123' });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ challenge: 'abc123' });
+ }, 60000);
+
+ it('does not find a resolver under another application registration', async () => {
+ const response = await request(baseUrl)
+ .post(
+ `/webhooks/server/${OTHER_APPLICATION_REGISTRATION_ID}/${HANDSHAKE_RESOLVER_UNIVERSAL_IDENTIFIER}`,
+ )
+ .send({ type: 'url_verification', challenge: 'abc123' });
+
+ expect(response.status).toBe(404);
+ });
+
+ it('does not expose a function without server route settings through the scoped route', async () => {
+ const applicationRegistrationId = await findApplicationRegistrationId();
+
+ const response = await request(baseUrl)
+ .post(
+ `/webhooks/server/${applicationRegistrationId}/${TARGET_FUNCTION_UNIVERSAL_IDENTIFIER}`,
+ )
+ .send({});
+
+ expect(response.status).toBe(404);
+ });
+
it('forwards a third-party JWT to a resolver that asked for it', async () => {
const thirdPartyToken = jwt.sign(
{
diff --git a/packages/twenty-shared/src/application-runtime/constants/DefaultServerRoutesUrlName.ts b/packages/twenty-shared/src/application-runtime/constants/DefaultServerRoutesUrlName.ts
new file mode 100644
index 00000000000..00f103ccf46
--- /dev/null
+++ b/packages/twenty-shared/src/application-runtime/constants/DefaultServerRoutesUrlName.ts
@@ -0,0 +1 @@
+export const DEFAULT_SERVER_ROUTES_URL_NAME = 'TWENTY_SERVER_ROUTES_URL';
diff --git a/packages/twenty-shared/src/application-runtime/index.ts b/packages/twenty-shared/src/application-runtime/index.ts
index 35dd304f121..94136fe291f 100644
--- a/packages/twenty-shared/src/application-runtime/index.ts
+++ b/packages/twenty-shared/src/application-runtime/index.ts
@@ -13,6 +13,7 @@ export { DEFAULT_API_URL_NAME } from './constants/DefaultApiUrlName';
export { DEFAULT_APP_ACCESS_TOKEN_NAME } from './constants/DefaultAppAccessTokenName';
export { DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME } from './constants/DefaultAppApplicationAccessTokenName';
export { DEFAULT_FUNCTIONS_URL_NAME } from './constants/DefaultFunctionsUrlName';
+export { DEFAULT_SERVER_ROUTES_URL_NAME } from './constants/DefaultServerRoutesUrlName';
export { LEGACY_CONNECTION_VISIBILITY_BY_SCOPE } from './constants/LegacyConnectionVisibilityByScope';
export type {
CreditUnavailableReason,