The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix: ignore inherited Object keys when validating locales and normalize the x-locale header (#24919)
Guillaume Flambardef758e3e4691
diff --git a/packages/twenty-server/src/engine/middlewares/middleware.service.ts b/packages/twenty-server/src/engine/middlewares/middleware.service.tsindex 5b4977d8866..94b13f229c6 100644--- a/packages/twenty-server/src/engine/middlewares/middleware.service.ts+++ b/packages/twenty-server/src/engine/middlewares/middleware.service.ts@@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common';import { isNonEmptyString } from '@sniptt/guards';import { type Request, type Response } from 'express';-import { type APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';import { isDefined } from 'twenty-shared/utils';import {@@ -20,6 +19,7 @@ import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flatimport { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';import { INTERNAL_SERVER_ERROR } from 'src/engine/middlewares/constants/default-error-message.constant';import { bindDataToRequestObject } from 'src/engine/utils/bind-data-to-request-object.util';+import { getRequestLocaleFromHeader } from 'src/engine/utils/get-request-locale-from-header.util';import {handleException,handleExceptionAndConvertToGraphQLError,@@ -155,9 +155,7 @@ export class MiddlewareService {public async hydrateGraphqlRequest(request: Request) {if (!this.isTokenPresent(request)) {- request.locale =- (request.headers['x-locale'] as keyof typeof APP_LOCALES) ??- SOURCE_LOCALE;+ request.locale = getRequestLocaleFromHeader(request);return;}diff --git a/packages/twenty-server/src/engine/utils/bind-data-to-request-object.util.ts b/packages/twenty-server/src/engine/utils/bind-data-to-request-object.util.tsindex 242aa8a99be..597130d8dfb 100644--- a/packages/twenty-server/src/engine/utils/bind-data-to-request-object.util.ts+++ b/packages/twenty-server/src/engine/utils/bind-data-to-request-object.util.ts@@ -1,7 +1,7 @@import { type Request } from 'express';-import { type APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';import { type RawAuthContext } from 'src/engine/core-modules/auth/types/raw-auth-context.type';+import { getRequestLocaleFromHeader } from 'src/engine/utils/get-request-locale-from-header.util';export const bindDataToRequestObject = (data: RawAuthContext,@@ -24,7 +24,5 @@ export const bindDataToRequestObject = (request.authenticatedAt = data.authenticatedAt;request.locale =- data.userWorkspace?.locale ??- (request.headers['x-locale'] as keyof typeof APP_LOCALES) ??- SOURCE_LOCALE;+ data.userWorkspace?.locale ?? getRequestLocaleFromHeader(request);};diff --git a/packages/twenty-server/src/engine/utils/get-request-locale-from-header.util.ts b/packages/twenty-server/src/engine/utils/get-request-locale-from-header.util.tsnew file mode 100644index 00000000000..4d95d1ff67f--- /dev/null+++ b/packages/twenty-server/src/engine/utils/get-request-locale-from-header.util.ts@@ -0,0 +1,10 @@+import { isString } from '@sniptt/guards';+import { type Request } from 'express';+import { type AppLocale } from 'twenty-shared/translations';+import { normalizeLocale } from 'twenty-shared/utils';++export const getRequestLocaleFromHeader = (request: Request): AppLocale => {+ const headerLocale = request.headers['x-locale'];++ return normalizeLocale(isString(headerLocale) ? headerLocale : null);+};diff --git a/packages/twenty-server/test/integration/graphql/suites/locale/request-locale-header.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/locale/request-locale-header.integration-spec.tsnew file mode 100644index 00000000000..103a8b5bfa9--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/locale/request-locale-header.integration-spec.ts@@ -0,0 +1,33 @@+import request from 'supertest';++const SERVER_URL = `http://localhost:${APP_PORT}`;++const queryCurrentUserWithLocaleHeader = (locale: string) =>+ request(SERVER_URL)+ .post('/metadata')+ .set('x-locale', locale)+ .send({ query: 'query { currentUser { id } }' })+ .expect(200);++describe('x-locale request header (integration)', () => {+ it('translates errors into a supported locale', async () => {+ const response = await queryCurrentUserWithLocaleHeader('fr-FR');++ expect(response.body.errors[0].extensions.code).toBe('UNAUTHENTICATED');+ expect(response.body.errors[0].extensions.userFriendlyMessage).toBe(+ 'Vous devez être authentifié pour effectuer cette action.',+ );+ });++ it.each(['xx', 'xx-YY', 'toString', 'constructor'])(+ 'falls back to the source locale for unsupported locale %s',+ async (locale) => {+ const response = await queryCurrentUserWithLocaleHeader(locale);++ expect(response.body.errors[0].extensions.code).toBe('UNAUTHENTICATED');+ expect(response.body.errors[0].extensions.userFriendlyMessage).toBe(+ 'You must be authenticated to perform this action.',+ );+ },+ );+});diff --git a/packages/twenty-shared/src/utils/validation/__tests__/isValidLocale.test.ts b/packages/twenty-shared/src/utils/validation/__tests__/isValidLocale.test.tsindex 1931b93634b..d235fa8db98 100644--- a/packages/twenty-shared/src/utils/validation/__tests__/isValidLocale.test.ts+++ b/packages/twenty-shared/src/utils/validation/__tests__/isValidLocale.test.ts@@ -11,4 +11,9 @@ describe('isValidLocale', () => {expect(isValidLocale('invalidLocale')).toBe(false);expect(isValidLocale(null)).toBe(false);});++ it('should return false for inherited Object prototype keys', () => {+ expect(isValidLocale('toString')).toBe(false);+ expect(isValidLocale('constructor')).toBe(false);+ });});diff --git a/packages/twenty-shared/src/utils/validation/__tests__/normalizeLocale.test.ts b/packages/twenty-shared/src/utils/validation/__tests__/normalizeLocale.test.tsindex 79652fe778e..242b8cb370f 100644--- a/packages/twenty-shared/src/utils/validation/__tests__/normalizeLocale.test.ts+++ b/packages/twenty-shared/src/utils/validation/__tests__/normalizeLocale.test.ts@@ -39,6 +39,13 @@ describe('normalizeLocale', () => {expect(normalizeLocale('')).toBe(SOURCE_LOCALE);});+ it('should not treat inherited Object prototype keys as valid locales', () => {+ expect(normalizeLocale('toString')).toBe(SOURCE_LOCALE);+ expect(normalizeLocale('constructor')).toBe(SOURCE_LOCALE);+ expect(normalizeLocale('valueOf')).toBe(SOURCE_LOCALE);+ expect(normalizeLocale('hasOwnProperty')).toBe(SOURCE_LOCALE);+ });+it('should handle SOURCE_LOCALE and its variants correctly', () => {expect(normalizeLocale(SOURCE_LOCALE)).toBe(SOURCE_LOCALE);// If SOURCE_LOCALE is 'en', test 'en-US', 'en-GB', etc.diff --git a/packages/twenty-shared/src/utils/validation/isValidLocale.ts b/packages/twenty-shared/src/utils/validation/isValidLocale.tsindex 322f907ef79..f78c457bb20 100644--- a/packages/twenty-shared/src/utils/validation/isValidLocale.ts+++ b/packages/twenty-shared/src/utils/validation/isValidLocale.ts@@ -4,4 +4,4 @@ import {} from '@/translations/constants/AppLocales';export const isValidLocale = (value: string | null): value is AppLocale =>- value !== null && value in APP_LOCALES;+ value !== null && Object.keys(APP_LOCALES).includes(value);diff --git a/packages/twenty-shared/src/utils/validation/normalizeLocale.ts b/packages/twenty-shared/src/utils/validation/normalizeLocale.tsindex 5c9c96575fc..9df7aad2272 100644--- a/packages/twenty-shared/src/utils/validation/normalizeLocale.ts+++ b/packages/twenty-shared/src/utils/validation/normalizeLocale.ts@@ -3,31 +3,31 @@ import {type AppLocale,} from '@/translations/constants/AppLocales';import { SOURCE_LOCALE } from '@/translations/constants/SourceLocale';+import { isDefined } from '@/utils/validation/isDefined';+import { isValidLocale } from '@/utils/validation/isValidLocale';// Maps language codes to full locale keys in APP_LOCALES// Example: 'fr' -> 'fr-FR', 'en' -> 'en'-const languageToLocaleMap = Object.keys(APP_LOCALES).reduce<- Record<string, string>->((map, locale) => {+const languageToLocaleMap = Object.keys(APP_LOCALES).reduce((map, locale) => {const language = locale.split('-')[0].toLowerCase();// Only add to the map if not already added or if the current locale is the source locale// This ensures language codes map to their full locale version (e.g., 'es' -> 'es-ES')// but preserves 'en' -> 'en' since it's the source locale- if (!map[language] || locale === SOURCE_LOCALE) {- map[language] = locale;+ if (!map.has(language) || locale === SOURCE_LOCALE) {+ map.set(language, locale as AppLocale);}return map;-}, {});+}, new Map<string, AppLocale>());export const normalizeLocale = (value: string | null): AppLocale => {if (value === null) {return SOURCE_LOCALE;}- if (value in APP_LOCALES) {- return value as AppLocale;+ if (isValidLocale(value)) {+ return value;}const caseInsensitiveMatch = Object.keys(APP_LOCALES).find(@@ -39,8 +39,10 @@ export const normalizeLocale = (value: string | null): AppLocale => {// Try matching just the language part (e.g., 'fr' -> 'fr-FR')const languageCode = value?.trim() ? value.split('-')[0].toLowerCase() : '';- if (languageToLocaleMap[languageCode]) {- return languageToLocaleMap[languageCode] as AppLocale;+ const languageLocale = languageToLocaleMap.get(languageCode);++ if (isDefined(languageLocale)) {+ return languageLocale;}return SOURCE_LOCALE;