8bfa9c4adb
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>
172 lines
6.4 KiB
TypeScript
172 lines
6.4 KiB
TypeScript
import {
|
|
type DynamicModule,
|
|
type MiddlewareConsumer,
|
|
Module,
|
|
RequestMethod,
|
|
} from '@nestjs/common';
|
|
import { APP_FILTER } from '@nestjs/core';
|
|
import { GraphQLModule } from '@nestjs/graphql';
|
|
import { ServeStaticModule } from '@nestjs/serve-static';
|
|
|
|
import { existsSync } from 'fs';
|
|
import { join } from 'path';
|
|
|
|
import { YogaDriver, type YogaDriverConfig } from '@graphql-yoga/nestjs';
|
|
import { SentryModule } from '@sentry/nestjs/setup';
|
|
import { ApiPath } from 'twenty-shared/types';
|
|
|
|
import { AdminPanelGraphQLApiModule } from 'src/engine/api/graphql/admin-panel-graphql-api.module';
|
|
import { CoreGraphQLApiModule } from 'src/engine/api/graphql/core-graphql-api.module';
|
|
import { GraphQLConfigModule } from 'src/engine/api/graphql/graphql-config/graphql-config.module';
|
|
import { GraphQLConfigService } from 'src/engine/api/graphql/graphql-config/graphql-config.service';
|
|
import { MetadataGraphQLApiModule } from 'src/engine/api/graphql/metadata-graphql-api.module';
|
|
import { McpMethodGuardMiddleware } from 'src/engine/api/mcp/middlewares/mcp-method-guard.middleware';
|
|
import { McpModule } from 'src/engine/api/mcp/mcp.module';
|
|
import { RestApiModule } from 'src/engine/api/rest/rest-api.module';
|
|
import { WorkspaceAuthContextMiddleware } from 'src/engine/core-modules/auth/middlewares/workspace-auth-context.middleware';
|
|
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
|
|
import { DataloaderModule } from 'src/engine/dataloaders/dataloader.module';
|
|
import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.module';
|
|
import { CookieSessionCsrfMiddleware } from 'src/engine/middlewares/cookie-session-csrf.middleware';
|
|
import { GraphQLHydrateRequestFromTokenMiddleware } from 'src/engine/middlewares/graphql-hydrate-request-from-token.middleware';
|
|
import { MiddlewareModule } from 'src/engine/middlewares/middleware.module';
|
|
import { JwtModule } from 'src/engine/core-modules/jwt/jwt.module';
|
|
import { UserSessionModule } from 'src/engine/core-modules/user-session/user-session.module';
|
|
import { RestCoreMiddleware } from 'src/engine/middlewares/rest-core.middleware';
|
|
import { GlobalWorkspaceDataSourceModule } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-datasource.module';
|
|
import { TwentyORMModule } from 'src/engine/twenty-orm/twenty-orm.module';
|
|
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
|
|
import { UnhandledExceptionFilter } from 'src/filters/unhandled-exception.filter';
|
|
import { ModulesModule } from 'src/modules/modules.module';
|
|
|
|
import { ClickHouseModule } from './database/clickHouse/clickHouse.module';
|
|
import { CoreEngineModule } from './engine/core-modules/core-engine.module';
|
|
import { I18nModule } from './engine/core-modules/i18n/i18n.module';
|
|
|
|
// TODO: Remove this middleware when all the rest endpoints are migrated to TwentyORM
|
|
const MIGRATED_REST_METHODS = [
|
|
RequestMethod.DELETE,
|
|
RequestMethod.POST,
|
|
RequestMethod.PATCH,
|
|
RequestMethod.PUT,
|
|
RequestMethod.GET,
|
|
];
|
|
|
|
@Module({
|
|
imports: [
|
|
SentryModule.forRoot(),
|
|
GraphQLModule.forRootAsync<YogaDriverConfig>({
|
|
driver: YogaDriver,
|
|
imports: [GraphQLConfigModule, MetricsModule, DataloaderModule],
|
|
useClass: GraphQLConfigService,
|
|
}),
|
|
TwentyORMModule,
|
|
GlobalWorkspaceDataSourceModule,
|
|
ClickHouseModule,
|
|
// Core engine module, contains all the core modules
|
|
CoreEngineModule,
|
|
// Modules module, contains all business logic modules
|
|
ModulesModule,
|
|
// Needed for the user workspace middleware
|
|
WorkspaceCacheStorageModule,
|
|
// Api modules
|
|
CoreGraphQLApiModule,
|
|
MetadataGraphQLApiModule,
|
|
AdminPanelGraphQLApiModule,
|
|
RestApiModule,
|
|
McpModule,
|
|
MiddlewareModule,
|
|
JwtModule,
|
|
UserSessionModule,
|
|
WorkspaceMetadataVersionModule,
|
|
// I18n module for translations
|
|
I18nModule,
|
|
// Conditional modules
|
|
...AppModule.getConditionalModules(),
|
|
],
|
|
providers: [
|
|
{
|
|
provide: APP_FILTER,
|
|
useClass: UnhandledExceptionFilter,
|
|
},
|
|
],
|
|
})
|
|
export class AppModule {
|
|
private static getConditionalModules(): DynamicModule[] {
|
|
const modules: DynamicModule[] = [];
|
|
const frontPath = join(__dirname, 'front');
|
|
|
|
// NestJS DevTools - can be useful for debugging and profiling
|
|
/* if (process.env.NODE_ENV === NodeEnvironment.DEVELOPMENT) {
|
|
modules.push(
|
|
DevtoolsModule.register({
|
|
http: true,
|
|
}),
|
|
);
|
|
} */
|
|
|
|
if (existsSync(frontPath)) {
|
|
modules.push(
|
|
ServeStaticModule.forRoot({
|
|
rootPath: frontPath,
|
|
}),
|
|
);
|
|
}
|
|
|
|
// Messaque Queue explorer only for sync driver
|
|
// Maybe we don't need to conditionaly register the explorer, because we're creating a jobs module
|
|
// that will expose classes that are only used in the queue worker
|
|
/*
|
|
if (process.env.MESSAGE_QUEUE_TYPE === MessageQueueDriverType.Sync) {
|
|
modules.push(MessageQueueModule.registerExplorer());
|
|
}
|
|
*/
|
|
|
|
return modules;
|
|
}
|
|
|
|
configure(consumer: MiddlewareConsumer) {
|
|
// Before any middleware that authenticates from the session cookie.
|
|
consumer
|
|
.apply(CookieSessionCsrfMiddleware)
|
|
// A cross-origin form post from the identity provider, authenticated on the
|
|
// assertion rather than the cookie.
|
|
.exclude({
|
|
path: `${ApiPath.Auth}/saml/callback/:identityProviderId`,
|
|
method: RequestMethod.POST,
|
|
})
|
|
.forRoutes({ path: '*path', method: RequestMethod.ALL });
|
|
|
|
consumer
|
|
.apply(
|
|
GraphQLHydrateRequestFromTokenMiddleware,
|
|
WorkspaceAuthContextMiddleware,
|
|
)
|
|
.forRoutes({ path: ApiPath.GraphQL, method: RequestMethod.ALL });
|
|
|
|
consumer
|
|
.apply(
|
|
GraphQLHydrateRequestFromTokenMiddleware,
|
|
WorkspaceAuthContextMiddleware,
|
|
)
|
|
.forRoutes({ path: ApiPath.Metadata, method: RequestMethod.ALL });
|
|
|
|
consumer
|
|
.apply(
|
|
GraphQLHydrateRequestFromTokenMiddleware,
|
|
WorkspaceAuthContextMiddleware,
|
|
)
|
|
.forRoutes({ path: ApiPath.AdminPanel, method: RequestMethod.ALL });
|
|
|
|
consumer
|
|
.apply(McpMethodGuardMiddleware)
|
|
.forRoutes({ path: ApiPath.Mcp, method: RequestMethod.ALL });
|
|
|
|
for (const method of MIGRATED_REST_METHODS) {
|
|
consumer
|
|
.apply(RestCoreMiddleware, WorkspaceAuthContextMiddleware)
|
|
.forRoutes({ path: `${ApiPath.Rest}/*path`, method });
|
|
}
|
|
}
|
|
}
|