The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Store Cloudflare country, region and city on user sessions (#29196)
Félix Malfait8b0c80574b30
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex a91d3cd5230..bf9b354dd85 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -5801,6 +5801,8 @@ enum UserCreditsFallback {type UserSession {authProvider: String!+ city: String+ country: StringcreatedAt: DateTime!expiresAt: DateTime!id: UUID!@@ -5808,6 +5810,7 @@ type UserSession {isCurrent: Boolean!isImpersonating: Boolean!lastActiveAt: DateTime!+ region: StringuserAgent: StringworkspaceId: UUID}diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex b3069b1ba74..6050b043149 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3772,6 +3772,8 @@ export type UserCreditsFallback = 'STOP' | 'WORKSPACE_CREDITS'export interface UserSession {authProvider: Scalars['String']+ city?: Scalars['String']+ country?: Scalars['String']createdAt: Scalars['DateTime']expiresAt: Scalars['DateTime']id: Scalars['UUID']@@ -3779,6 +3781,7 @@ export interface UserSession {isCurrent: Scalars['Boolean']isImpersonating: Scalars['Boolean']lastActiveAt: Scalars['DateTime']+ region?: Scalars['String']userAgent?: Scalars['String']workspaceId?: Scalars['UUID']__typename: 'UserSession'@@ -8633,6 +8636,8 @@ export interface UserApplicationVariableValueGenqlSelection{export interface UserSessionGenqlSelection{authProvider?: boolean | number+ city?: boolean | number+ country?: boolean | numbercreatedAt?: boolean | numberexpiresAt?: boolean | numberid?: boolean | number@@ -8640,6 +8645,7 @@ export interface UserSessionGenqlSelection{isCurrent?: boolean | numberisImpersonating?: boolean | numberlastActiveAt?: boolean | number+ region?: boolean | numberuserAgent?: boolean | numberworkspaceId?: boolean | number__typename?: boolean | numberdiff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex d2b879b2e79..67937a7f226 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -15053,6 +15053,12 @@ export default {"authProvider": [1],+ "city": [+ 1+ ],+ "country": [+ 1+ ],"createdAt": [209],@@ -15074,6 +15080,9 @@ export default {"lastActiveAt": [209],+ "region": [+ 1+ ],"userAgent": [1],diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 3c154d510bd..0a2222d9882 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -2260,7 +2260,7 @@ export type RevokeUserSessionMutation = { revokeUserSession: boolean };export type CurrentUserSessionsQueryVariables = Exact<{ [key: string]: never; }>;-export type CurrentUserSessionsQuery = { currentUserSessions: Array<{ __typename: 'UserSession', id: string, workspaceId: string | null, authProvider: string, isImpersonating: boolean, userAgent: string | null, ipAddress: string | null, createdAt: string, lastActiveAt: string, expiresAt: string, isCurrent: boolean }> };+export type CurrentUserSessionsQuery = { currentUserSessions: Array<{ __typename: 'UserSession', id: string, workspaceId: string | null, authProvider: string, isImpersonating: boolean, userAgent: string | null, ipAddress: string | null, country: string | null, region: string | null, city: string | null, createdAt: string, lastActiveAt: string, expiresAt: string, isCurrent: boolean }> };export type UpdateUserEmailMutationVariables = Exact<{newEmail: string;@@ -3154,7 +3154,7 @@ export const UpdateLabPublicFeatureFlagDocument = {"kind":"Document","definitionexport const CompleteWorkspaceMemberProfilePictureUploadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CompleteWorkspaceMemberProfilePictureUpload"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fileId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"completeWorkspaceMemberProfilePictureUpload"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"fileId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fileId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"path"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<CompleteWorkspaceMemberProfilePictureUploadMutation, CompleteWorkspaceMemberProfilePictureUploadMutationVariables>;export const RevokeAllOtherUserSessionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RevokeAllOtherUserSessions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"revokeAllOtherUserSessions"}}]}}]} as unknown as DocumentNode<RevokeAllOtherUserSessionsMutation, RevokeAllOtherUserSessionsMutationVariables>;export const RevokeUserSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RevokeUserSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userSessionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"revokeUserSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userSessionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userSessionId"}}}]}]}}]} as unknown as DocumentNode<RevokeUserSessionMutation, RevokeUserSessionMutationVariables>;-export const CurrentUserSessionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"CurrentUserSessions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentUserSessions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"authProvider"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"userAgent"}},{"kind":"Field","name":{"kind":"Name","value":"ipAddress"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastActiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"isCurrent"}}]}}]}}]} as unknown as DocumentNode<CurrentUserSessionsQuery, CurrentUserSessionsQueryVariables>;+export const CurrentUserSessionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"CurrentUserSessions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentUserSessions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"authProvider"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"userAgent"}},{"kind":"Field","name":{"kind":"Name","value":"ipAddress"}},{"kind":"Field","name":{"kind":"Name","value":"country"}},{"kind":"Field","name":{"kind":"Name","value":"region"}},{"kind":"Field","name":{"kind":"Name","value":"city"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastActiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"isCurrent"}}]}}]}}]} as unknown as DocumentNode<CurrentUserSessionsQuery, CurrentUserSessionsQueryVariables>;export const UpdateUserEmailDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUserEmail"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"newEmail"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"verifyEmailRedirectPath"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUserEmail"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"newEmail"},"value":{"kind":"Variable","name":{"kind":"Name","value":"newEmail"}}},{"kind":"Argument","name":{"kind":"Name","value":"verifyEmailRedirectPath"},"value":{"kind":"Variable","name":{"kind":"Name","value":"verifyEmailRedirectPath"}}}]}]}}]} as unknown as DocumentNode<UpdateUserEmailMutation, UpdateUserEmailMutationVariables>;export const CreateOneRoleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateOneRole"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"createRoleInput"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateRoleInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createOneRole"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"createRoleInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"createRoleInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RoleFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllAgentChatChannels"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}}]}}]} as unknown as DocumentNode<CreateOneRoleMutation, CreateOneRoleMutationVariables>;export const DeleteOneRoleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteOneRole"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteOneRole"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<DeleteOneRoleMutation, DeleteOneRoleMutationVariables>;diff --git a/packages/twenty-front/src/generated-metadata/schema.ts b/packages/twenty-front/src/generated-metadata/schema.tsindex b4b7f2f1ba6..4e67642fbf3 100644--- a/packages/twenty-front/src/generated-metadata/schema.ts+++ b/packages/twenty-front/src/generated-metadata/schema.ts@@ -8072,6 +8072,8 @@ export enum UserCreditsFallback {export type UserSession = {__typename?: 'UserSession';authProvider: Scalars['String']['output'];+ city?: Maybe<Scalars['String']['output']>;+ country?: Maybe<Scalars['String']['output']>;createdAt: Scalars['DateTime']['output'];expiresAt: Scalars['DateTime']['output'];id: Scalars['UUID']['output'];@@ -8079,6 +8081,7 @@ export type UserSession = {isCurrent: Scalars['Boolean']['output'];isImpersonating: Scalars['Boolean']['output'];lastActiveAt: Scalars['DateTime']['output'];+ region?: Maybe<Scalars['String']['output']>;userAgent?: Maybe<Scalars['String']['output']>;workspaceId?: Maybe<Scalars['UUID']['output']>;};diff --git a/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx b/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsxindex d686ae93e08..cffd2d23c71 100644--- a/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx+++ b/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx@@ -6,6 +6,7 @@ import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';import { SettingsListCard } from '@/settings/components/SettingsListCard';import { SettingsDeviceSessionRowRightComponent } from '@/settings/profile/devices/components/SettingsDeviceSessionRowRightComponent';+import { formatSessionLocation } from '@/settings/profile/devices/utils/formatSessionLocation';import { parseUserAgentDescription } from '@/settings/profile/devices/utils/parseUserAgentDescription';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useToast } from 'twenty-ui/components/feedback';@@ -35,7 +36,7 @@ const StyledButtonContainer = styled.div``;export const SettingsProfileDevicesSection = () => {- const { t } = useLingui();+ const { t, i18n } = useLingui();const { localeCatalog } = useAtomStateValue(dateLocaleState);const { enqueueToast } = useToast();@@ -88,8 +89,17 @@ export const SettingsProfileDevicesSection = () => {localeCatalog,);- return isNonEmptyString(session.ipAddress)- ? t`Last active ${lastActive} · ${session.ipAddress}`+ const location = formatSessionLocation({+ city: session.city,+ region: session.region,+ country: session.country,+ locale: i18n.locale,+ });+ const details = [location, session.ipAddress].filter(isNonEmptyString);++ // An expression, not a variable, keeps the "{0}" placeholder and so the existing translations.+ return isNonEmptyArray(details)+ ? t`Last active ${lastActive} · ${details.join(' · ')}`: t`Last active ${lastActive}`;};diff --git a/packages/twenty-front/src/modules/settings/profile/devices/components/__tests__/SettingsProfileDevicesSection.test.tsx b/packages/twenty-front/src/modules/settings/profile/devices/components/__tests__/SettingsProfileDevicesSection.test.tsxindex 6026fe7b69d..3fcf92c4bad 100644--- a/packages/twenty-front/src/modules/settings/profile/devices/components/__tests__/SettingsProfileDevicesSection.test.tsx+++ b/packages/twenty-front/src/modules/settings/profile/devices/components/__tests__/SettingsProfileDevicesSection.test.tsx@@ -16,6 +16,9 @@ const buildSession = (id: string, isCurrent: boolean) => ({isImpersonating: false,userAgent: 'Mozilla/5.0 (Macintosh) Chrome/128.0',ipAddress: '127.0.0.1',+ country: 'FR',+ region: 'Île-de-France',+ city: 'Paris',lastActiveAt: new Date().toISOString(),});@@ -64,6 +67,21 @@ describe('SettingsProfileDevicesSection', () => {expect(screen.queryByText('Devices')).not.toBeInTheDocument();});+ it('shows where each device was signed in from', async () => {+ render(+ <I18nProvider i18n={i18n}>+ <MemoryRouter>+ <SettingsProfileDevicesSection />+ </MemoryRouter>+ </I18nProvider>,+ { wrapper: Wrapper },+ );++ expect(+ await screen.findAllByText(/Paris, France · 127\.0\.0\.1/),+ ).toHaveLength(2);+ });+it('keeps a session row mounted across a re-render of the section', async () => {const tree = (<I18nProvider i18n={i18n}>diff --git a/packages/twenty-front/src/modules/settings/profile/devices/graphql/queries/currentUserSessions.ts b/packages/twenty-front/src/modules/settings/profile/devices/graphql/queries/currentUserSessions.tsindex bfa7fe3ae46..23e1396715c 100644--- a/packages/twenty-front/src/modules/settings/profile/devices/graphql/queries/currentUserSessions.ts+++ b/packages/twenty-front/src/modules/settings/profile/devices/graphql/queries/currentUserSessions.ts@@ -9,6 +9,9 @@ export const CURRENT_USER_SESSIONS = gql`isImpersonatinguserAgentipAddress+ country+ region+ citycreatedAtlastActiveAtexpiresAtdiff --git a/packages/twenty-front/src/modules/settings/profile/devices/utils/__tests__/formatSessionLocation.test.ts b/packages/twenty-front/src/modules/settings/profile/devices/utils/__tests__/formatSessionLocation.test.tsnew file mode 100644index 00000000000..2339e4b8270--- /dev/null+++ b/packages/twenty-front/src/modules/settings/profile/devices/utils/__tests__/formatSessionLocation.test.ts@@ -0,0 +1,42 @@+import { formatSessionLocation } from '@/settings/profile/devices/utils/formatSessionLocation';++describe('formatSessionLocation', () => {+ it('should show the city and the country name', () => {+ expect(+ formatSessionLocation({+ city: 'Paris',+ region: 'Île-de-France',+ country: 'FR',+ locale: 'en',+ }),+ ).toBe('Paris, France');+ });++ it('should name the country in the given locale', () => {+ expect(+ formatSessionLocation({ city: 'Berlin', country: 'DE', locale: 'fr-FR' }),+ ).toBe('Berlin, Allemagne');+ });++ it('should fall back to the region without a city', () => {+ expect(+ formatSessionLocation({+ city: null,+ region: 'California',+ country: 'US',+ locale: 'en',+ }),+ ).toBe('California, United States');+ });++ it('should return nothing without any location', () => {+ expect(+ formatSessionLocation({+ city: null,+ region: null,+ country: null,+ locale: 'en',+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-front/src/modules/settings/profile/devices/utils/formatSessionLocation.ts b/packages/twenty-front/src/modules/settings/profile/devices/utils/formatSessionLocation.tsnew file mode 100644index 00000000000..17da50cd747--- /dev/null+++ b/packages/twenty-front/src/modules/settings/profile/devices/utils/formatSessionLocation.ts@@ -0,0 +1,39 @@+import { isNonEmptyString } from '@sniptt/guards';++const getCountryName = ({+ countryCode,+ locale,+}: {+ countryCode: string;+ locale: string;+}): string => {+ try {+ return (+ new Intl.DisplayNames([locale], { type: 'region' }).of(countryCode) ??+ countryCode+ );+ } catch {+ return countryCode;+ }+};++export const formatSessionLocation = ({+ city,+ region,+ country,+ locale,+}: {+ city?: string | null;+ region?: string | null;+ country?: string | null;+ locale: string;+}): string | undefined => {+ const place = isNonEmptyString(city) ? city : region;+ const countryName = isNonEmptyString(country)+ ? getCountryName({ countryCode: country, locale })+ : undefined;++ const location = [place, countryName].filter(isNonEmptyString).join(', ');++ return isNonEmptyString(location) ? location : undefined;+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793274494191-add-geolocation-to-user-session.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793274494191-add-geolocation-to-user-session.tsnew file mode 100644index 00000000000..229c0b7bb8c--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793274494191-add-geolocation-to-user-session.ts@@ -0,0 +1,29 @@+import { type QueryRunner } from 'typeorm';++import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++@RegisteredInstanceCommand('2.54.0', 1793274494191)+export class AddGeolocationToUserSessionFastInstanceCommand implements FastInstanceCommand {+ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ 'ALTER TABLE "core"."userSession" ADD "country" text',+ );+ await queryRunner.query(+ 'ALTER TABLE "core"."userSession" ADD "region" text',+ );+ await queryRunner.query('ALTER TABLE "core"."userSession" ADD "city" text');+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ 'ALTER TABLE "core"."userSession" DROP COLUMN "city"',+ );+ await queryRunner.query(+ 'ALTER TABLE "core"."userSession" DROP COLUMN "region"',+ );+ await queryRunner.query(+ 'ALTER TABLE "core"."userSession" DROP COLUMN "country"',+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex 64281831f06..6b111630c19 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts@@ -266,6 +266,7 @@ import { AddMcpServerFastInstanceCommand } from 'src/database/commands/upgrade-vimport { AgentAndSkillOverridableEntityFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-53/2-53-instance-command-fast-1793203146887-agent-and-skill-overridable-entity';import { DropIsCustomFromAgentSkillViewIndexAndAgentChatChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793139794914-drop-is-custom-from-agent-skill-view-index-and-agent-chat-channel';import { PurgeSoftDeletedAgentsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-slow-1793272266091-purge-soft-deleted-agents';+import { AddGeolocationToUserSessionFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793274494191-add-geolocation-to-user-session';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -534,4 +535,5 @@ export const INSTANCE_COMMANDS = [DropIsCustomFromAgentSkillViewIndexAndAgentChatChannelFastInstanceCommand,AddFieldMetadataDisabledFieldPermissionActionsFastInstanceCommand,PurgeSoftDeletedAgentsSlowInstanceCommand,+ AddGeolocationToUserSessionFastInstanceCommand,];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 404652cd104..3a122dd92f1 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@@ -2061,6 +2061,19 @@ export class ConfigVariables {@IsOptional()CLOUDFLARE_DCV_DELEGATION_ID: string;+ @ConfigVariablesMetadata({+ group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,+ description:+ 'Store the visitor location headers Cloudflare adds (cf-ipcountry, ' ++ 'cf-region, cf-ipcity) on user sessions. Only enable when every ' ++ 'request reaches the server through Cloudflare: otherwise clients ' ++ 'can forge them.',+ type: ConfigVariableType.BOOLEAN,+ isEnvOnly: true,+ })+ @IsOptional()+ IS_CLOUDFLARE_GEOLOCATION_ENABLED = false;+@ConfigVariablesMetadata({group: ConfigVariablesGroup.LLM,isSensitive: true,diff --git a/packages/twenty-server/src/engine/core-modules/user-session/dtos/user-session.dto.ts b/packages/twenty-server/src/engine/core-modules/user-session/dtos/user-session.dto.tsindex be5f20e8e73..807a4b06b70 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/dtos/user-session.dto.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/dtos/user-session.dto.ts@@ -22,6 +22,15 @@ export class UserSessionDTO {@Field(() => String, { nullable: true })ipAddress: string | null;+ @Field(() => String, { nullable: true })+ country: string | null;++ @Field(() => String, { nullable: true })+ region: string | null;++ @Field(() => String, { nullable: true })+ city: string | null;+@Field(() => Date)createdAt: Date;diff --git a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.tsindex 671bf201175..34e68e51ffb 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts@@ -34,6 +34,7 @@ import { UserSessionCookieService } from 'src/engine/core-modules/user-session/simport { type CachedUserSession } from 'src/engine/core-modules/user-session/types/cached-user-session.type';import { type CreateUserSessionInput } from 'src/engine/core-modules/user-session/types/create-user-session-input.type';import { type UserSessionCreationOrigin } from 'src/engine/core-modules/user-session/types/user-session-creation-origin.type';+import { extractCloudflareGeolocationFromRequest } from 'src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util';import { isRequestOriginAllowed } from 'src/engine/core-modules/user-session/utils/is-request-origin-allowed.util';import { generateUserSessionToken } from 'src/engine/core-modules/user-session/utils/generate-user-session-token.util';import { hashUserSessionToken } from 'src/engine/core-modules/user-session/utils/hash-user-session-token.util';@@ -247,6 +248,9 @@ export class UserSessionService {const requestMetadata = {userAgent: request.headers['user-agent'] ?? null,ipAddress: request.ip ?? null,+ ...(this.twentyConfigService.get('IS_CLOUDFLARE_GEOLOCATION_ENABLED')+ ? extractCloudflareGeolocationFromRequest(request)+ : {}),};if (payload.type === JwtTokenTypeEnum.ACCESS) {@@ -331,6 +335,9 @@ export class UserSessionService {: null,userAgent: input.userAgent ?? null,ipAddress: input.ipAddress ?? null,+ country: input.country ?? null,+ region: input.region ?? null,+ city: input.city ?? null,expiresAt: addMilliseconds(now, ms(lifetime)),lastActiveAt: now,}),diff --git a/packages/twenty-server/src/engine/core-modules/user-session/types/create-user-session-input.type.ts b/packages/twenty-server/src/engine/core-modules/user-session/types/create-user-session-input.type.tsindex 2096111e5ab..a4c1ad54ba1 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/types/create-user-session-input.type.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/types/create-user-session-input.type.ts@@ -11,5 +11,8 @@ export type CreateUserSessionInput = {impersonatedUserWorkspaceId?: string | null;userAgent?: string | null;ipAddress?: string | null;+ country?: string | null;+ region?: string | null;+ city?: string | null;origin: UserSessionCreationOrigin;};diff --git a/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts b/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.tsindex dbb0b2518e7..8e4555a3844 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts@@ -83,6 +83,16 @@ export class UserSessionEntity {@Column({ type: 'text', nullable: true })ipAddress: string | null;+ // ISO 3166-1 alpha-2+ @Column({ type: 'text', nullable: true })+ country: string | null;++ @Column({ type: 'text', nullable: true })+ region: string | null;++ @Column({ type: 'text', nullable: true })+ city: string | null;+@Index('IDX_USER_SESSION_EXPIRES_AT')@Column({ type: 'timestamptz' })expiresAt: Date;diff --git a/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts b/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.tsindex 54652ba926c..5a2f8e91260 100644--- a/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts@@ -177,6 +177,9 @@ export class UserSessionResolver {isImpersonating: session.isImpersonating,userAgent: session.userAgent,ipAddress: session.ipAddress,+ country: session.country,+ region: session.region,+ city: session.city,createdAt: session.createdAt,lastActiveAt: session.lastActiveAt,expiresAt: session.expiresAt,diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.spec.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.spec.tsnew file mode 100644index 00000000000..9adcb84a61e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.spec.ts@@ -0,0 +1,52 @@+import { extractCloudflareGeolocationFromRequest } from 'src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util';++const buildRequest = (headers: Record<string, string>) => ({ headers });++// How Node exposes a header whose raw bytes are UTF-8.+const asReceivedByNode = (value: string) =>+ Buffer.from(value, 'utf8').toString('latin1');++describe('extractCloudflareGeolocationFromRequest', () => {+ it('should read country, region and city', () => {+ expect(+ extractCloudflareGeolocationFromRequest(+ buildRequest({+ 'cf-ipcountry': 'US',+ 'cf-region': 'California',+ 'cf-ipcity': 'San Francisco',+ }),+ ),+ ).toEqual({ country: 'US', region: 'California', city: 'San Francisco' });+ });++ it('should decode non-ASCII values sent as UTF-8 bytes', () => {+ expect(+ extractCloudflareGeolocationFromRequest(+ buildRequest({+ 'cf-ipcountry': 'CH',+ 'cf-region': asReceivedByNode('Zürich'),+ 'cf-ipcity': asReceivedByNode('Zürich'),+ }),+ ),+ ).toEqual({ country: 'CH', region: 'Zürich', city: 'Zürich' });+ });++ it('should return nulls without Cloudflare headers', () => {+ expect(extractCloudflareGeolocationFromRequest(buildRequest({}))).toEqual({+ country: null,+ region: null,+ city: null,+ });+ });++ it.each(['XX', 'T1', 'France', ''])(+ 'should drop the non-country code %p',+ (countryCode) => {+ expect(+ extractCloudflareGeolocationFromRequest(+ buildRequest({ 'cf-ipcountry': countryCode }),+ ).country,+ ).toBe(null);+ },+ );+});diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.tsnew file mode 100644index 00000000000..9714314209d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-cloudflare-geolocation-from-request.util.ts@@ -0,0 +1,57 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Request } from 'express';++export type CloudflareGeolocation = {+ country: string | null;+ region: string | null;+ city: string | null;+};++// XX is Cloudflare's "unknown" and T1 is Tor: neither is an ISO 3166 country.+const UNKNOWN_COUNTRY_CODES = new Set(['XX', 'T1']);++// Cloudflare sends non-ASCII values as raw UTF-8 bytes, which Node reads as latin1.+type RequestWithHeaders = Pick<Request, 'headers'>;++const readUtf8Header = ({+ request,+ headerName,+}: {+ request: RequestWithHeaders;+ headerName: string;+}): string | null => {+ const value = request.headers[headerName];++ if (!isNonEmptyString(value)) {+ return null;+ }++ const decodedValue = Buffer.from(value, 'latin1').toString('utf8').trim();++ return isNonEmptyString(decodedValue) ? decodedValue : null;+};++const readCountryCode = (request: RequestWithHeaders): string | null => {+ const countryCode = readUtf8Header({+ request,+ headerName: 'cf-ipcountry',+ })?.toUpperCase();++ if (+ !isNonEmptyString(countryCode) ||+ !/^[A-Z]{2}$/.test(countryCode) ||+ UNKNOWN_COUNTRY_CODES.has(countryCode)+ ) {+ return null;+ }++ return countryCode;+};++export const extractCloudflareGeolocationFromRequest = (+ request: RequestWithHeaders,+): CloudflareGeolocation => ({+ country: readCountryCode(request),+ region: readUtf8Header({ request, headerName: 'cf-region' }),+ city: readUtf8Header({ request, headerName: 'cf-ipcity' }),+});