The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(domain): serve frontend when its host is under public domain (#27248)
Yaduraj41849ba09fe0
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex c77502aaf05..666dc1478e2 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -555,7 +555,7 @@ The following system variables are always available via `process.env`:Twenty also injects `TWENTY_FUNCTIONS_URL` into front components and logic functions: the base URL your app's HTTP-triggered logic functions are served from.-It exists because that URL is not always the Twenty server itself. On Twenty Cloud, app routes are served on a dedicated per-workspace domain (`https://<your-workspace-subdomain>.withtwenty.com`, or the application's primary public domain when one is configured) so that app-authored responses run on an isolated origin rather than on the Twenty app origin. Self-hosted and local instances serve app routes under the `/s` prefix on the server itself and may not set the variable at all. Since the base URL varies per workspace and per instance, your code cannot hard-code it — the server injects the right value at runtime.+It exists because that URL is not always the Twenty server itself. On Twenty Cloud, app routes are served on a dedicated per-workspace domain (`https://<your-workspace-subdomain>.withtwenty.com`, or the application's primary public domain when one is configured) so that app-authored responses run on their own origin rather than on the Twenty app origin. Self-hosted and local instances serve app routes under the `/s` prefix on the server itself and may not set the variable at all. Since the base URL varies per workspace and per instance, your code cannot hard-code it — the server injects the right value at runtime.You rarely need to read it directly. Call your routes through `RestApiClient` with a `/s/`-prefixed path and the client resolves the URL for you: it strips the `/s` prefix and targets `TWENTY_FUNCTIONS_URL`, falling back to `<TWENTY_API_URL>/s` when the variable is not set. Use `resolveUrl('/s/<path>')` to get the absolute URL without sending a request, e.g. for a link. Read the variable directly only when building a URL by hand:diff --git a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service.ts b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service.tsindex b04edcd8711..d22f6e94db6 100644--- a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service.ts+++ b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service.ts@@ -1,12 +1,8 @@import { Injectable } from '@nestjs/common';-import { isDefined } from 'twenty-shared/utils';-import { buildUrlWithPathnameAndSearchParams } from 'src/engine/core-modules/domain/domain-server-config/utils/build-url-with-pathname-and-search-params.util';-import {- getHostnameFromUrlOrUndefined,- isHostUnderPublicFunctionDomain,-} from 'src/engine/core-modules/domain/domain-server-config/utils/public-function-domain.util';+import { getSubdomainAndCustomDomainFromHostname } from 'src/engine/core-modules/domain/domain-server-config/utils/get-subdomain-and-custom-domain-from-hostname.util';+import { getHostnameFromUrlOrUndefined } from 'src/engine/core-modules/domain/domain-server-config/utils/public-function-domain.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';@Injectable()@@ -60,49 +56,11 @@ export class DomainServerConfigService {});}- getSubdomainAndDomainFromUrl = (url: string) => {- const { hostname: originHostname } = new URL(url);-- const frontDomain = this.getFrontUrl().hostname;-- const isFrontdomain = originHostname.endsWith(`.${frontDomain}`);-- if (isFrontdomain) {- const subdomain = originHostname.replace(`.${frontDomain}`, '');-- return {- subdomain: this.isDefaultSubdomain(subdomain) ? undefined : subdomain,- domain: null,- isPublicDomainOrigin: false,- };- }-- const publicBaseDomain = this.getPublicBaseHostnameOrUndefined();-- if (- isDefined(publicBaseDomain) &&- isHostUnderPublicFunctionDomain({- host: originHostname,- publicDomainBaseHostname: publicBaseDomain,- })- ) {- const subdomain = originHostname.replace(`.${publicBaseDomain}`, '');-- return {- subdomain: this.isDefaultSubdomain(subdomain) ? undefined : subdomain,- domain: null,- isPublicDomainOrigin: true,- };- }-- return {- subdomain: undefined,- domain: originHostname,- isPublicDomainOrigin: false,- };- };-- isDefaultSubdomain(subdomain: string) {- return subdomain === this.twentyConfigService.get('DEFAULT_SUBDOMAIN');- }+ getSubdomainAndCustomDomainFromUrl = (url: string) =>+ getSubdomainAndCustomDomainFromHostname({+ hostname: new URL(url).hostname,+ frontDomain: this.getFrontUrl().hostname,+ publicBaseDomain: this.getPublicBaseHostnameOrUndefined(),+ defaultSubdomain: this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),+ });}diff --git a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/__tests__/get-subdomain-and-custom-domain-from-hostname.util.spec.ts b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/__tests__/get-subdomain-and-custom-domain-from-hostname.util.spec.tsnew file mode 100644index 00000000000..6ca91962c09--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/__tests__/get-subdomain-and-custom-domain-from-hostname.util.spec.ts@@ -0,0 +1,105 @@+import { getSubdomainAndCustomDomainFromHostname } from 'src/engine/core-modules/domain/domain-server-config/utils/get-subdomain-and-custom-domain-from-hostname.util';++describe('getSubdomainAndCustomDomainFromHostname', () => {+ const config = {+ frontDomain: 'twenty.com',+ publicBaseDomain: 'withtwenty.com',+ defaultSubdomain: 'app',+ };++ it.each([+ {+ case: 'the front host',+ hostname: 'twenty.com',+ expected: {+ subdomain: undefined,+ customDomain: null,+ isUnderPublicDomainUrl: false,+ },+ },+ {+ case: 'a workspace subdomain',+ hostname: 'acme.twenty.com',+ expected: {+ subdomain: 'acme',+ customDomain: null,+ isUnderPublicDomainUrl: false,+ },+ },+ {+ case: 'the default subdomain',+ hostname: 'app.twenty.com',+ expected: {+ subdomain: undefined,+ customDomain: null,+ isUnderPublicDomainUrl: false,+ },+ },+ {+ case: 'a public domain host',+ hostname: 'acme.withtwenty.com',+ expected: {+ subdomain: 'acme',+ customDomain: null,+ isUnderPublicDomainUrl: true,+ },+ },+ {+ case: 'a custom domain',+ hostname: 'crm.acme.com',+ expected: {+ subdomain: undefined,+ customDomain: 'crm.acme.com',+ isUnderPublicDomainUrl: false,+ },+ },+ ])('should resolve $case', ({ hostname, expected }) => {+ expect(+ getSubdomainAndCustomDomainFromHostname({ ...config, hostname }),+ ).toEqual(expected);+ });++ it('should resolve the front host as the front domain when it sits under the public domain', () => {+ expect(+ getSubdomainAndCustomDomainFromHostname({+ hostname: 'twenty.example.com',+ frontDomain: 'twenty.example.com',+ publicBaseDomain: 'example.com',+ defaultSubdomain: 'app',+ }),+ ).toEqual({+ subdomain: undefined,+ customDomain: null,+ isUnderPublicDomainUrl: false,+ });+ });++ it('should resolve workspace subdomains of a front host under the public domain', () => {+ expect(+ getSubdomainAndCustomDomainFromHostname({+ hostname: 'acme.twenty.example.com',+ frontDomain: 'twenty.example.com',+ publicBaseDomain: 'example.com',+ defaultSubdomain: 'app',+ }),+ ).toEqual({+ subdomain: 'acme',+ customDomain: null,+ isUnderPublicDomainUrl: false,+ });+ });++ it('should not treat hosts as public domains when no public domain is configured', () => {+ expect(+ getSubdomainAndCustomDomainFromHostname({+ hostname: 'acme.withtwenty.com',+ frontDomain: 'twenty.com',+ defaultSubdomain: 'app',+ }),+ ).toEqual({+ subdomain: undefined,+ customDomain: 'acme.withtwenty.com',+ isUnderPublicDomainUrl: false,+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/get-subdomain-and-custom-domain-from-hostname.util.ts b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/get-subdomain-and-custom-domain-from-hostname.util.tsnew file mode 100644index 00000000000..d6eb7ace2a4--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/get-subdomain-and-custom-domain-from-hostname.util.ts@@ -0,0 +1,57 @@+import { isDefined } from 'twenty-shared/utils';++import { isHostUnderPublicFunctionDomain } from 'src/engine/core-modules/domain/domain-server-config/utils/public-function-domain.util';++export const getSubdomainAndCustomDomainFromHostname = ({+ hostname,+ frontDomain,+ publicBaseDomain,+ defaultSubdomain,+}: {+ hostname: string;+ frontDomain: string;+ publicBaseDomain?: string;+ defaultSubdomain?: string;+}): {+ subdomain: string | undefined;+ customDomain: string | null;+ isUnderPublicDomainUrl: boolean;+} => {+ const isFrontDomain =+ hostname === frontDomain || hostname.endsWith(`.${frontDomain}`);++ if (isFrontDomain) {+ const subdomain =+ hostname === frontDomain+ ? undefined+ : hostname.replace(`.${frontDomain}`, '');++ return {+ subdomain: subdomain === defaultSubdomain ? undefined : subdomain,+ customDomain: null,+ isUnderPublicDomainUrl: false,+ };+ }++ if (+ isDefined(publicBaseDomain) &&+ isHostUnderPublicFunctionDomain({+ host: hostname,+ publicDomainBaseHostname: publicBaseDomain,+ })+ ) {+ const subdomain = hostname.replace(`.${publicBaseDomain}`, '');++ return {+ subdomain: subdomain === defaultSubdomain ? undefined : subdomain,+ customDomain: null,+ isUnderPublicDomainUrl: true,+ };+ }++ return {+ subdomain: undefined,+ customDomain: hostname,+ isUnderPublicDomainUrl: false,+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.tsindex 1fa0e91d3e0..7f26cf3411a 100644--- a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts+++ b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts@@ -103,25 +103,27 @@ export class WorkspaceDomainsService {async resolveWorkspaceAndPublicDomain(origin: string): Promise<{workspace: WorkspaceEntity | undefined;publicDomain: PublicDomainEntity | null;- isIsolatedOrigin: boolean;+ isPublicDomain: boolean;}> {- const { subdomain, domain, isPublicDomainOrigin } =- this.domainServerConfigService.getSubdomainAndDomainFromUrl(origin);+ const { subdomain, customDomain, isUnderPublicDomainUrl } =+ this.domainServerConfigService.getSubdomainAndCustomDomainFromUrl(origin);if (!this.twentyConfigService.get('IS_MULTIWORKSPACE_ENABLED')) {// Still resolve the public domain so route triggers can scope by application.- const publicDomain = isDefined(domain)- ? await this.publicDomainRepository.findOne({ where: { domain } })+ const publicDomain = isDefined(customDomain)+ ? await this.publicDomainRepository.findOne({+ where: { domain: customDomain },+ }): null;return {workspace: await this.getDefaultWorkspace(),publicDomain: publicDomain ?? null,- isIsolatedOrigin: isPublicDomainOrigin || isDefined(publicDomain),+ isPublicDomain: isUnderPublicDomainUrl || isDefined(publicDomain),};}- if (isPublicDomainOrigin) {+ if (isUnderPublicDomainUrl) {const hostname = new URL(origin).hostname;const registeredPublicDomain = await this.publicDomainRepository.findOne({@@ -133,7 +135,7 @@ export class WorkspaceDomainsService {return {workspace: registeredPublicDomain.workspace ?? undefined,publicDomain: registeredPublicDomain,- isIsolatedOrigin: true,+ isPublicDomain: true,};}@@ -147,19 +149,19 @@ export class WorkspaceDomainsService {return {workspace: workspaceFromSubdomain,publicDomain: null,- isIsolatedOrigin: true,+ isPublicDomain: true,};}- if (!domain && !subdomain) {+ if (!customDomain && !subdomain) {return {workspace: undefined,publicDomain: null,- isIsolatedOrigin: false,+ isPublicDomain: false,};}- const where = isDefined(domain) ? { customDomain: domain } : { subdomain };+ const where = isDefined(customDomain) ? { customDomain } : { subdomain };const workspaceFromCustomDomainOrSubdomain =(await this.workspaceRepository.findOne({@@ -167,23 +169,26 @@ export class WorkspaceDomainsService {relations: ['workspaceSsoIdentityProviders'],})) ?? undefined;- if (isDefined(workspaceFromCustomDomainOrSubdomain) || !isDefined(domain)) {+ if (+ isDefined(workspaceFromCustomDomainOrSubdomain) ||+ !isDefined(customDomain)+ ) {return {workspace: workspaceFromCustomDomainOrSubdomain,publicDomain: null,- isIsolatedOrigin: false,+ isPublicDomain: false,};}const publicDomain = await this.publicDomainRepository.findOne({- where: { domain },+ where: { domain: customDomain },relations: ['workspace', 'workspace.workspaceSsoIdentityProviders'],});return {workspace: publicDomain?.workspace ?? undefined,publicDomain: publicDomain ?? null,- isIsolatedOrigin: isDefined(publicDomain),+ isPublicDomain: isDefined(publicDomain),};}diff --git a/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts b/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.tsindex d649c74eeb6..964212a2c15 100644--- a/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts+++ b/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts@@ -113,17 +113,17 @@ export class FrontendService {);try {- const { workspace, isIsolatedOrigin } = await this.workspaceDomainsService+ const { workspace, isPublicDomain } = await this.workspaceDomainsService.resolveWorkspaceAndPublicDomain(getRequestBaseUrl(request)).catch((error: unknown) => {if (error === WorkspaceNotFoundDefaultError) {- return { workspace: undefined, isIsolatedOrigin: false };+ return { workspace: undefined, isPublicDomain: false };}throw error;});- if (isIsolatedOrigin) {+ if (isPublicDomain) {response.status(404).end();return;diff --git a/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts b/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.tsindex 219fccdcf67..70fd8c8452a 100644--- a/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts+++ b/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts@@ -49,17 +49,17 @@ export class GuardRedirectService {getSubdomainAndCustomDomainFromContext(context: ExecutionContext) {const request = context.switchToHttp().getRequest<Request>();- const subdomainAndDomainFromReferer = request.headers.referer- ? this.domainsServerConfigService.getSubdomainAndDomainFromUrl(+ const subdomainAndCustomDomainFromReferer = request.headers.referer+ ? this.domainsServerConfigService.getSubdomainAndCustomDomainFromUrl(request.headers.referer,): null;- return subdomainAndDomainFromReferer &&- subdomainAndDomainFromReferer.subdomain+ return subdomainAndCustomDomainFromReferer &&+ subdomainAndCustomDomainFromReferer.subdomain? {- subdomain: subdomainAndDomainFromReferer.subdomain,- customDomain: subdomainAndDomainFromReferer.domain,+ subdomain: subdomainAndCustomDomainFromReferer.subdomain,+ customDomain: subdomainAndCustomDomainFromReferer.customDomain,}: {subdomain: this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/route-trigger.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/route-trigger.service.tsindex 902ab199299..d69d89e0d26 100644--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/route-trigger.service.ts+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/route-trigger.service.ts@@ -44,7 +44,7 @@ type RouteTriggerWorkspace = Pick<type RouteTriggerRequestContext = {workspace: RouteTriggerWorkspace;applicationId: string | null;- isIsolatedOrigin: boolean;+ isPublicDomain: boolean;authenticationContext: RawAuthContext | undefined;};@@ -94,7 +94,7 @@ export class RouteTriggerService {const {workspace: workspaceFromHost,publicDomain,- isIsolatedOrigin,+ isPublicDomain,} = await this.workspaceDomainsService.resolveWorkspaceAndPublicDomain(host,);@@ -125,7 +125,7 @@ export class RouteTriggerService {return {workspace,applicationId: publicDomain?.applicationId ?? null,- isIsolatedOrigin,+ isPublicDomain,authenticationContext,};}@@ -174,13 +174,13 @@ export class RouteTriggerService {private assertLegacyRouteIsServableOrThrow({logicFunction,workspace,- isIsolatedOrigin,+ isPublicDomain,}: {logicFunction: LogicFunctionEntity;workspace: RouteTriggerWorkspace;- isIsolatedOrigin: boolean;+ isPublicDomain: boolean;}) {- if (isIsolatedOrigin) {+ if (isPublicDomain) {return;}@@ -255,13 +255,9 @@ export class RouteTriggerService {}: {request: Request;httpMethod: HTTPMethod;- }): Promise<{ response: RouteTriggerResponse; isIsolatedOrigin: boolean }> {- const {- workspace,- applicationId,- isIsolatedOrigin,- authenticationContext,- } = await this.resolveRouteTriggerRequestContextOrFail(request);+ }): Promise<{ response: RouteTriggerResponse; isPublicDomain: boolean }> {+ const { workspace, applicationId, isPublicDomain, authenticationContext } =+ await this.resolveRouteTriggerRequestContextOrFail(request);const logicFunctionsWithHttpRouteTrigger =await this.logicFunctionRepository.find(workspace.id, {@@ -281,7 +277,7 @@ export class RouteTriggerService {this.assertLegacyRouteIsServableOrThrow({logicFunction,workspace,- isIsolatedOrigin,+ isPublicDomain,});const httpRouteSettings = logicFunction.httpRouteTriggerSettings;@@ -321,7 +317,7 @@ export class RouteTriggerService {pathParameters: pathParams,forwardedRequestHeaders:httpRouteSettings?.forwardedRequestHeaders ?? [],- forwardAllHeaders: isIsolatedOrigin,+ forwardAllHeaders: isPublicDomain,userId,userWorkspaceId,});@@ -359,6 +355,6 @@ export class RouteTriggerService {);}- return { response: outcome.response, isIsolatedOrigin };+ return { response: outcome.response, isPublicDomain };}}diff --git a/packages/twenty-server/src/engine/metadata-modules/route-trigger/__tests__/route-trigger.controller.spec.ts b/packages/twenty-server/src/engine/metadata-modules/route-trigger/__tests__/route-trigger.controller.spec.tsindex 57518ca6d0b..d558d21d70e 100644--- a/packages/twenty-server/src/engine/metadata-modules/route-trigger/__tests__/route-trigger.controller.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/route-trigger/__tests__/route-trigger.controller.spec.ts@@ -42,7 +42,7 @@ describe('RouteTriggerController', () => {handle.mockResolvedValue({response: { statusCode: 200, headers: {}, body: { ok: true } },- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.post(request, response);@@ -64,7 +64,7 @@ describe('RouteTriggerController', () => {headers: { 'Content-Type': 'text/html', 'Cache-Control': 'no-store' },body: '<h1>Hi</h1>',},- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);@@ -95,7 +95,7 @@ describe('RouteTriggerController', () => {},body: '<h1>Hi</h1>',},- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);@@ -115,7 +115,7 @@ describe('RouteTriggerController', () => {expect(response.setHeader).not.toHaveBeenCalledWith('X-Custom', 'foo');});- it('forwards every header when the request is served from an isolated origin', async () => {+ it('forwards every header when the request is served from a public domain', async () => {const response = createResponseMock();handle.mockResolvedValue({@@ -131,7 +131,7 @@ describe('RouteTriggerController', () => {},body: '<h1>Hi</h1>',},- isIsolatedOrigin: true,+ isPublicDomain: true,});await controller.get({} as never, response);@@ -160,7 +160,7 @@ describe('RouteTriggerController', () => {handle.mockResolvedValue({response: { statusCode: 200, headers: {}, body: null },- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);@@ -175,7 +175,7 @@ describe('RouteTriggerController', () => {handle.mockResolvedValue({response: { statusCode: 200, headers: {}, body: 'plain' },- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);@@ -192,7 +192,7 @@ describe('RouteTriggerController', () => {handle.mockResolvedValue({response: { statusCode: 200, headers: {}, body: { ok: true } },- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);@@ -209,7 +209,7 @@ describe('RouteTriggerController', () => {headers: { 'Content-Type': 'application/ld+json' },body: { ok: true },},- isIsolatedOrigin: false,+ isPublicDomain: false,});await controller.get({} as never, response);diff --git a/packages/twenty-server/src/engine/metadata-modules/route-trigger/route-trigger.controller.ts b/packages/twenty-server/src/engine/metadata-modules/route-trigger/route-trigger.controller.tsindex a32c68fb20d..4fbf28328d8 100644--- a/packages/twenty-server/src/engine/metadata-modules/route-trigger/route-trigger.controller.ts+++ b/packages/twenty-server/src/engine/metadata-modules/route-trigger/route-trigger.controller.ts@@ -37,11 +37,11 @@ export class RouteTriggerController {response: Response,httpMethod: HTTPMethod,) {- const { response: triggerResponse, isIsolatedOrigin } =+ const { response: triggerResponse, isPublicDomain } =await this.routeTriggerService.handle({ request, httpMethod });sendRouteTriggerResponse(response, triggerResponse, {- allowAllHeaders: isIsolatedOrigin,+ allowAllHeaders: isPublicDomain,});}