Files
twenty/packages/twenty-server/src/main.ts
T
Paul Rastoin 8bfa9c4adb Proxy API routes through the vite dev server to keep local dev same-origin (#23779)
Replaces #23774 (closed), rebased on latest main.

## Problem

Since the cookie-session migration (#23642), the front sends every
request with `credentials: 'include'` and the server only reflects
`Access-Control-Allow-Origin` for the exact origins in the credentialed
allowlist (`SERVER_URL`, `FRONTEND_URL`, `AUTH_COOKIE_ALLOWED_ORIGINS`).
Any other origin gets the `*` wildcard, which browsers reject for
credentialed requests.

Local dev is split-origin by default (front on `localhost:3001`, API on
`localhost:3000`), and with `IS_MULTIWORKSPACE_ENABLED` every workspace
subdomain (`apple.localhost:3001`, ...) is yet another origin. Each
locally created workspace would need a manual
`AUTH_COOKIE_ALLOWED_ORIGINS` entry.

## Solution

Make local dev same-origin instead of widening the CORS policy: the vite
dev server now proxies all top-level API route prefixes to the backend,
and the front calls its own origin.

- `vite.config.ts` adds a `server.proxy` covering the backend's
top-level prefixes (`/graphql`, `/metadata`, `/admin-panel`, `/auth`,
`/rest`, `/file`, `/client-config`, ...), defined in
`src/config/apiProxyPrefixes.ts`. Keys are anchored regexes
(`^/auth($|[/?])`) so SPA routes sharing a prefix (`/authorize`,
`/settings`) are not swallowed. The target defaults to
`http://localhost:3000` and follows `REACT_APP_SERVER_BASE_URL`.
`changeOrigin` stays off so the backend sees the browser's Host:
same-origin checks (CSRF, cookie issuance) and workspace resolution by
subdomain work unchanged through the proxy.
- `config/index.ts` collapses to
`window._env_?.REACT_APP_SERVER_BASE_URL || window.location.origin`.
Every supported production path injects `window._env_` (docker
entrypoint fails hard without `REACT_APP_SERVER_BASE_URL`; a
server-served front gets it from `generateFrontConfig()`), and in dev
the current origin is correct on `localhost:3001` and every
`*.localhost:3001` workspace subdomain thanks to the proxy. The removed
`http://<hostname>:3000` fallback only served an un-injected production
bundle browsed on localhost, a setup whose credentialed auth the
cookie-session migration had already broken.

The credentialed allowlist itself is unchanged and stays strict; since
dev traffic is same-origin, the per-subdomain cookie-allowlist problem
disappears without loosening any production CORS/CSRF policy.

## Tests

- `src/config/__tests__/apiProxyPrefixes.test.ts` guards the proxy
boundary in both directions: representative backend path shapes
(including `/metadata?query=...` and `/auth/...`) must match, every SPA
route from the `AppPath` enum and vite's own dev paths must not — so a
future route collision fails unit tests instead of breaking dev.
- Verified against running dev servers: API paths proxy to the backend
from both `localhost:3001` and `apple.localhost:3001`, while SPA routes
`/settings` and `/authorize` still serve the vite app; a same-origin
POST from `apple.localhost:3001` goes through with no CORS involvement.
- `lint:diff-with-main` and `typecheck` pass for twenty-front.

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2026-08-05 08:08:51 +00:00

118 lines
4.0 KiB
TypeScript

import { NestFactory } from '@nestjs/core';
import { type NestExpressApplication } from '@nestjs/platform-express';
import fs from 'fs';
import { inspect } from 'util';
import bytes from 'bytes';
import { useContainer } from 'class-validator';
import session from 'express-session';
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import { ApiPath } from 'twenty-shared/types';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
import { setPgDateTypeParser } from 'src/database/pg/set-pg-date-type-parser';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
import { getSessionStorageOptions } from 'src/engine/core-modules/session-storage/session-storage.module-factory';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { configTransformers } from 'src/engine/core-modules/twenty-config/utils/config-transformers.util';
import { applyCredentialedCors } from 'src/engine/core-modules/user-session/utils/apply-credentialed-cors.util';
import { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';
import { AppModule } from './app.module';
import './instrument';
import { settings } from './engine/constants/settings';
import { generateFrontConfig } from './utils/generate-front-config';
// Trigger
const bootstrap = async () => {
setPgDateTypeParser();
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
bufferLogs: process.env.LOGGER_IS_BUFFER_ENABLED === 'true',
rawBody: true,
snapshot: process.env.NODE_ENV === NodeEnvironment.DEVELOPMENT,
...(process.env.SSL_KEY_PATH && process.env.SSL_CERT_PATH
? {
httpsOptions: {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH),
},
}
: {}),
});
const logger = app.get(LoggerService);
const twentyConfigService = app.get(TwentyConfigService);
const exceptionHandlerService = app.get(ExceptionHandlerService);
process.on('unhandledRejection', (reason) => {
const error =
reason instanceof Error
? reason
: new Error(typeof reason === 'string' ? reason : inspect(reason));
if (shouldCaptureException(error)) {
exceptionHandlerService.captureExceptions([error]);
}
});
const trustProxyRaw = twentyConfigService.get('TRUST_PROXY');
const trustProxy = /^\d+$/.test(trustProxyRaw)
? Number(trustProxyRaw)
: (configTransformers.boolean(trustProxyRaw) ?? trustProxyRaw);
app.set('trust proxy', trustProxy);
applyCredentialedCors(app, twentyConfigService);
app.use(session(getSessionStorageOptions(twentyConfigService)));
// Apply class-validator container so that we can use injection in validators
useContainer(app.select(AppModule), { fallbackOnErrors: true });
// Use our logger
app.useLogger(logger);
app.useBodyParser('json', { limit: settings.storage.maxFileSize });
app.useBodyParser('urlencoded', {
limit: settings.storage.maxFileSize,
extended: true,
});
app.useBodyParser('text', { type: 'text/plain', limit: '1024kb' });
// Graphql file upload
app.use(
`/${ApiPath.GraphQL}`,
graphqlUploadExpress({
maxFieldSize: bytes(settings.storage.maxFileSize)!,
maxFiles: 10,
}),
);
app.use(
`/${ApiPath.Metadata}`,
graphqlUploadExpress({
maxFieldSize: bytes(settings.storage.maxFileSize)!,
maxFiles: 10,
}),
);
// Inject the server url in the frontend page
generateFrontConfig();
const keepAliveTimeout = twentyConfigService.get(
'SERVER_KEEP_ALIVE_TIMEOUT_MS',
);
const httpServer = app.getHttpServer();
httpServer.keepAliveTimeout = keepAliveTimeout;
httpServer.headersTimeout = keepAliveTimeout + 1000;
await app.listen(twentyConfigService.get('NODE_PORT'));
};
void bootstrap();