The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Make server-served front same-origin by default and surface CORS misconfig (#24041)
Félix Malfait51abfb3e402a
diff --git a/packages/twenty-docs/developers/self-host/capabilities/docker-compose.mdx b/packages/twenty-docs/developers/self-host/capabilities/docker-compose.mdxindex 683112be819..650a2c9b632 100644--- a/packages/twenty-docs/developers/self-host/capabilities/docker-compose.mdx+++ b/packages/twenty-docs/developers/self-host/capabilities/docker-compose.mdx@@ -102,7 +102,7 @@ curl http://localhost:3000### Expose Twenty to External Access-By default, Twenty runs on `localhost` at port `3000`. To access it via an external domain or IP address, you need to configure the `SERVER_URL` in your `.env` file.+By default, Twenty runs on `localhost` at port `3000`. The UI resolves the API from the browser's own origin, so it loads from any hostname that reaches the container — but still set `SERVER_URL` to your public URL: the server uses it for generated links (emails, OAuth callbacks) and to detect HTTPS for secure cookies.#### Understanding `SERVER_URL`@@ -217,7 +217,7 @@ Add to your crontab (`crontab -e`):1. Stop the application:```bash-docker compose stop twenty-server twenty-front+docker compose stop server worker```2. Restore the database:diff --git a/packages/twenty-docs/developers/self-host/capabilities/setup.mdx b/packages/twenty-docs/developers/self-host/capabilities/setup.mdxindex 722b2eca6df..14c4c5291c7 100644--- a/packages/twenty-docs/developers/self-host/capabilities/setup.mdx+++ b/packages/twenty-docs/developers/self-host/capabilities/setup.mdx@@ -382,17 +382,23 @@ Only relevant if you do not let the back-end serve the front-end. Same-origindeployments need nothing here.Declare every browser origin that talks to the API, comma separated. `SERVER_URL`-and `FRONTEND_URL` are already trusted.+and `FRONTEND_URL` are already trusted. The server logs a warning when a browser+calls it from an undeclared origin.```bashAUTH_COOKIE_ALLOWED_ORIGINS=https://app.example.com```<Warning>-Upgrading to a version with cookie sessions makes this required. The front-end-now sends credentials on every request, and browsers reject a credentialed-response from an undeclared origin, so the app fails to load until you set this.+The front-end sends credentials on every request, and browsers reject a+credentialed response from an undeclared origin, so the app fails to load until+you set this.</Warning>If the two hosts are on different registrable domains (not just differentsubdomains), also set `AUTH_COOKIE_SAME_SITE=none`, which requires HTTPS.++With multi-workspace enabled, do not list every workspace subdomain here.+Instead, route API paths (`/graphql`, `/metadata`, `/rest`, `/auth/`,+`/client-config`, `/file`) to the back-end on each workspace hostname, so every+workspace stays same-origin — this is how Twenty Cloud runs.diff --git a/packages/twenty-front/src/modules/client-config/utils/__tests__/clientConfigUtils.test.ts b/packages/twenty-front/src/modules/client-config/utils/__tests__/clientConfigUtils.test.tsindex d0630dad116..0851a3238ec 100644--- a/packages/twenty-front/src/modules/client-config/utils/__tests__/clientConfigUtils.test.ts+++ b/packages/twenty-front/src/modules/client-config/utils/__tests__/clientConfigUtils.test.ts@@ -63,13 +63,6 @@ describe('getClientConfig', () => {expect(fetch).toHaveBeenCalledWith(`${REACT_APP_SERVER_BASE_URL}/client-config`,- {- method: 'GET',- headers: {- 'Content-Type': 'application/json',- },- credentials: 'include',- },);expect(result).toEqual(mockClientConfig);});diff --git a/packages/twenty-front/src/modules/client-config/utils/getClientConfig.ts b/packages/twenty-front/src/modules/client-config/utils/getClientConfig.tsindex 32051ebb961..d9544112db1 100644--- a/packages/twenty-front/src/modules/client-config/utils/getClientConfig.ts+++ b/packages/twenty-front/src/modules/client-config/utils/getClientConfig.ts@@ -2,13 +2,7 @@ import { type ClientConfig } from '@/client-config/types/ClientConfig';import { REACT_APP_SERVER_BASE_URL } from '~/config';export const getClientConfig = async (): Promise<ClientConfig> => {- const response = await fetch(`${REACT_APP_SERVER_BASE_URL}/client-config`, {- method: 'GET',- headers: {- 'Content-Type': 'application/json',- },- credentials: 'include',- });+ const response = await fetch(`${REACT_APP_SERVER_BASE_URL}/client-config`);if (!response.ok) {throw new Error(diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.tsindex 3598e847261..15981d81964 100644--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts@@ -1439,23 +1439,6 @@ export class ConfigVariables {@IsOptional()SERVER_URL = 'http://localhost:3000';- @ConfigVariablesMetadata({- group: ConfigVariablesGroup.SERVER_CONFIG,- description:- 'When enabled, the served frontend resolves the API base URL from ' +- "the browser's current origin (window.location) instead of the " +- 'baked-in SERVER_URL. Useful for self-hosted deployments reachable ' +- 'from multiple hostnames (Tailscale IP, LAN DNS, SSH tunnel, public ' +- 'DNS), where pinning a single SERVER_URL would break every other ' +- 'host with CORS or unreachable-host errors. Read at startup by ' +- 'generate-front-config; SERVER_URL is still used for all server-side ' +- 'URL generation.',- type: ConfigVariableType.BOOLEAN,- isEnvOnly: true,- })- @IsOptional()- FRONT_AUTO_BASE_URL = false;-@ConfigVariablesMetadata({group: ConfigVariablesGroup.SERVER_CONFIG,description:diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.spec.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.spec.tsnew file mode 100644index 00000000000..409a2fdbb98--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.spec.ts@@ -0,0 +1,119 @@+import { Logger } from '@nestjs/common';++import { type Request } from 'express';++import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { warnOnceOnDisallowedBrowserPreflight } from 'src/engine/core-modules/user-session/utils/apply-credentialed-cors.util';++describe('warnOnceOnDisallowedBrowserPreflight', () => {+ const defaultConfig: Record<string, unknown> = {+ NODE_ENV: 'production',+ SERVER_URL: 'https://crm.example.com',+ FRONTEND_URL: undefined,+ AUTH_COOKIE_ALLOWED_ORIGINS: '',+ };++ let mockConfig: Record<string, unknown> = { ...defaultConfig };++ const twentyConfigService = {+ get: jest.fn((key: string) => mockConfig[key]),+ } as unknown as TwentyConfigService;++ const buildPreflightRequest = ({+ origin,+ host = 'crm.example.com',+ method = 'OPTIONS',+ requestedMethod = 'POST',+ }: {+ origin?: string;+ host?: string;+ method?: string;+ requestedMethod?: string;+ }): Request =>+ ({+ method,+ protocol: 'https',+ headers: {+ origin,+ 'access-control-request-method': requestedMethod,+ },+ get: jest.fn().mockReturnValue(host),+ }) as unknown as Request;++ let warnSpy: jest.SpyInstance;+ let warnedOrigins: Set<string>;++ beforeEach(() => {+ mockConfig = { ...defaultConfig };+ warnedOrigins = new Set<string>();+ warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation();+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('should warn once per disallowed cross-origin preflight', () => {+ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({ origin: 'https://tenant.example.net' }),+ twentyConfigService,+ warnedOrigins,+ });+ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({ origin: 'https://tenant.example.net' }),+ twentyConfigService,+ warnedOrigins,+ });++ expect(warnSpy).toHaveBeenCalledTimes(1);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('https://tenant.example.net'),+ );+ });++ it('should not warn for an allowlisted origin', () => {+ mockConfig.AUTH_COOKIE_ALLOWED_ORIGINS = 'https://front.example.net';++ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({ origin: 'https://front.example.net' }),+ twentyConfigService,+ warnedOrigins,+ });++ expect(warnSpy).not.toHaveBeenCalled();+ });++ it('should not warn for a same-origin preflight since browsers do not enforce CORS on it', () => {+ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({+ origin: 'https://lan.example.internal',+ host: 'lan.example.internal',+ }),+ twentyConfigService,+ warnedOrigins,+ });++ expect(warnSpy).not.toHaveBeenCalled();+ });++ it('should not warn for requests that are not browser preflights', () => {+ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({+ origin: 'https://tenant.example.net',+ method: 'POST',+ }),+ twentyConfigService,+ warnedOrigins,+ });+ warnOnceOnDisallowedBrowserPreflight({+ request: buildPreflightRequest({+ origin: 'https://tenant.example.net',+ requestedMethod: '',+ }),+ twentyConfigService,+ warnedOrigins,+ });++ expect(warnSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.tsindex 0f02c369d76..6dc52440109 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts@@ -1,9 +1,81 @@-import { type INestApplication } from '@nestjs/common';+import { type INestApplication, Logger } from '@nestjs/common';+import { isNonEmptyString } from '@sniptt/guards';import { type NextFunction, type Request, type Response } from 'express';import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { resolveAllowedCredentialedOrigins } from 'src/engine/core-modules/user-session/utils/resolve-allowed-credentialed-origins.util';+import { getRequestBaseUrl } from 'src/utils/get-request-base-url.util';++const logger = new Logger('CredentialedCors');++// Prevents junk Origin headers from growing the warned set unbounded.+const WARNED_ORIGINS_MAX = 1_000;++const toComparableOrigin = (value: string): string | undefined => {+ try {+ return new URL(value).origin.toLowerCase();+ } catch {+ return undefined;+ }+};++// The browser reports a rejected credentialed wildcard response only in its+// own console, leaving nothing server-side for the operator to act on+// (#24037). Warn once per origin on cross-origin browser preflights that will+// be answered with the wildcard.+export const warnOnceOnDisallowedBrowserPreflight = ({+ request,+ twentyConfigService,+ warnedOrigins,+}: {+ request: Request;+ twentyConfigService: TwentyConfigService;+ warnedOrigins: Set<string>;+}): void => {+ if (+ request.method !== 'OPTIONS' ||+ !isNonEmptyString(request.headers['access-control-request-method'])+ ) {+ return;+ }++ const origin = request.headers.origin;++ if (!isNonEmptyString(origin)) {+ return;+ }++ const comparableOrigin = toComparableOrigin(origin);++ if (!isNonEmptyString(comparableOrigin)) {+ return;+ }++ // Browsers do not enforce CORS on same-origin requests.+ if (comparableOrigin === toComparableOrigin(getRequestBaseUrl(request))) {+ return;+ }++ if (+ resolveAllowedCredentialedOrigins(twentyConfigService).has(comparableOrigin)+ ) {+ return;+ }++ if (+ warnedOrigins.has(comparableOrigin) ||+ warnedOrigins.size >= WARNED_ORIGINS_MAX+ ) {+ return;+ }++ warnedOrigins.add(comparableOrigin);++ logger.warn(+ `Cross-origin browser request from ${comparableOrigin} (API host: ${getRequestBaseUrl(request)}); credentialed requests from it will be blocked by the browser. If this is your Twenty front-end, serve it same-origin with the API, or add the origin to AUTH_COOKIE_ALLOWED_ORIGINS. Logged once per origin.`,+ );+};// Shared between the production bootstrap and the integration test harness so// the CORS behavior under test is the deployed one.@@ -11,11 +83,18 @@ export const applyCredentialedCors = (app: INestApplication,twentyConfigService: TwentyConfigService,): void => {+ const warnedOrigins = new Set<string>();+// The cors package only emits Vary: Origin when it reflects one, so wildcard// and reflected responses would share a cache entry and a credentialed// request could be served the wildcard, which browsers reject.- app.use((_request: Request, response: Response, next: NextFunction) => {+ app.use((request: Request, response: Response, next: NextFunction) => {response.vary('Origin');+ warnOnceOnDisallowedBrowserPreflight({+ request,+ twentyConfigService,+ warnedOrigins,+ });next();});diff --git a/packages/twenty-server/src/utils/__test__/generate-front-config.spec.ts b/packages/twenty-server/src/utils/__test__/generate-front-config.spec.tsindex fe85c9fc11a..d28665c1c64 100644--- a/packages/twenty-server/src/utils/__test__/generate-front-config.spec.ts+++ b/packages/twenty-server/src/utils/__test__/generate-front-config.spec.ts@@ -20,8 +20,8 @@ const INDEX_TEMPLATE = `<html></html>`;// Pull the injected _env_ object back out of the written index.html and-// normalize whitespace so the multi-line JSON.stringify(..., 2) output can be-// compared against a compact expected string.+// normalize whitespace so the multi-line output can be compared against a+// compact expected string.const getInjectedEnv = (): string => {const writtenContent = mockedFs.writeFileSync.mock.calls[0][1] as string;const match = writtenContent.match(/window\._env_ = (\{[\s\S]*?\});/);@@ -42,43 +42,11 @@ describe('generateFrontConfig', () => {process.env = ORIGINAL_ENV;});- it('should inject the absolute SERVER_URL when set and the toggle is unset', () => {+ it('should clear any baked value so the front resolves the API origin from the page origin', () => {process.env.SERVER_URL = 'http://x.com';- delete process.env.FRONT_AUTO_BASE_URL;-- generateFrontConfig();-- expect(getInjectedEnv()).toBe(- '{"REACT_APP_SERVER_BASE_URL":"http://x.com"}',- );- });-- it('should inject an empty _env_ when SERVER_URL is unset', () => {- delete process.env.SERVER_URL;- delete process.env.FRONT_AUTO_BASE_URL;-- generateFrontConfig();-- expect(getInjectedEnv()).toBe('{}');- });-- it('should inject an empty _env_ when FRONT_AUTO_BASE_URL=true even if SERVER_URL is set', () => {- process.env.SERVER_URL = 'http://x.com';- process.env.FRONT_AUTO_BASE_URL = 'true';generateFrontConfig();expect(getInjectedEnv()).toBe('{}');});-- it('should keep the absolute SERVER_URL when FRONT_AUTO_BASE_URL is not exactly "true"', () => {- process.env.SERVER_URL = 'http://x.com';- process.env.FRONT_AUTO_BASE_URL = 'false';-- generateFrontConfig();-- expect(getInjectedEnv()).toBe(- '{"REACT_APP_SERVER_BASE_URL":"http://x.com"}',- );- });});diff --git a/packages/twenty-server/src/utils/generate-front-config.ts b/packages/twenty-server/src/utils/generate-front-config.tsindex 43878dc94ad..03413d3047c 100644--- a/packages/twenty-server/src/utils/generate-front-config.ts+++ b/packages/twenty-server/src/utils/generate-front-config.ts@@ -8,21 +8,13 @@ config({});export function generateFrontConfig(): void {- // When FRONT_AUTO_BASE_URL=true (or SERVER_URL is unset), inject an empty- // _env_ so the frontend's getDefaultUrl() fallback resolves the API origin- // from the page's own hostname at request time. This lets the same deploy- // be reached at both http://<external-ip> and http://localhost without a- // hairpin through the public interface.- const useAutoUrl =- process.env.FRONT_AUTO_BASE_URL === 'true' || !process.env.SERVER_URL;-- const envForFront = useAutoUrl- ? {}- : { REACT_APP_SERVER_BASE_URL: process.env.SERVER_URL };-+ // A page served by this server can always reach the API on the origin it+ // was loaded from, so the front resolves it from window.location (see+ // packages/twenty-front/src/config). Rewriting clears any value baked into+ // index.html at build time.const configString = `<!-- BEGIN: Twenty Config --><script id="twenty-env-config">- window._env_ = ${JSON.stringify(envForFront, null, 2)};+ window._env_ = {};</script><!-- END: Twenty Config -->`;