Skip to content

The open alternative to Salesforce, designed for AI.

Serve backend HTML with startup config and workspace iframe settings (#26459)

Félix Malfaitdee3395c79c1
diff --git a/.github/workflows/ci-test-docker-compose.yaml b/.github/workflows/ci-test-docker-compose.yaml
index 28a63460499..3ab57529016 100644
--- a/.github/workflows/ci-test-docker-compose.yaml
+++ b/.github/workflows/ci-test-docker-compose.yaml
@@ -17,7 +17,10 @@ jobs:
uses: ./.github/workflows/changed-files.yaml
with:
files: |
+ .github/workflows/ci-test-docker-compose.yaml
packages/twenty-docker/**
+ packages/twenty-server/src/engine/core-modules/frontend/**
+ packages/twenty-server/src/engine/core-modules/client-config/**
docker-compose.yml
test-compose:
needs: changed-files-check
@@ -112,7 +115,7 @@ jobs:
- name: Create frontend placeholder
run: |
mkdir -p packages/twenty-front/build
- echo '<html><body>CI placeholder</body></html>' > packages/twenty-front/build/index.html
+ echo '<html><head></head><body>CI placeholder</body></html>' > packages/twenty-front/build/index.html
- name: Build app-dev image
run: |
docker build \
@@ -154,6 +157,15 @@ jobs:
echo "Still waiting... (${count}/300s) [HTTP ${status}]"
sleep 1
done
+ - name: Verify backend HTML bootstrap
+ run: |
+ for path in / /index.html /objects/people; do
+ curl --fail --silent --show-error --header "Accept: text/html" --dump-header /tmp/twenty-headers \
+ "http://localhost:2020${path}" --output /tmp/twenty-document
+ grep -qi '^cache-control: no-store' /tmp/twenty-headers
+ grep -qi "^content-security-policy: frame-ancestors 'self';" /tmp/twenty-headers
+ grep -q 'id="twenty-client-config" type="application/json"' /tmp/twenty-document
+ done
ci-test-docker-status-check:
if: always() && !cancelled()
timeout-minutes: 5
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 9d69e590f02..cbb32bf544e 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -869,6 +869,7 @@ type Workspace {
isMicrosoftAuthBypassEnabled: Boolean!
isCustomDomainEnabled: Boolean!
isInternalMessagesImportEnabled: Boolean!
+ allowedIframeOrigins: [String!]
editableProfileFields: [String!]
defaultRole: Role
aiChatModelTier: AiModelTier!
@@ -4112,6 +4113,7 @@ type Mutation {
deleteFrontComponent(id: UUID!): FrontComponent!
activateWorkspace(data: ActivateWorkspaceInput!): Workspace!
updateWorkspace(data: UpdateWorkspaceInput!): Workspace!
+ updateWorkspaceAllowedIframeOrigins(data: UpdateWorkspaceAllowedIframeOriginsInput!): Workspace!
deleteCurrentWorkspace: Workspace!
checkCustomDomainValidRecords: DomainValidRecords
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult!
@@ -5004,6 +5006,11 @@ input UpdateWorkspaceInput {
isInternalMessagesImportEnabled: Boolean
}
+input UpdateWorkspaceAllowedIframeOriginsInput {
+ operation: String!
+ origin: String!
+}
+
input CreateApplicationRegistrationInput {
name: String!
universalIdentifier: String
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 4e87e6dff7b..90d89d127ef 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -610,6 +610,7 @@ export interface Workspace {
isMicrosoftAuthBypassEnabled: Scalars['Boolean']
isCustomDomainEnabled: Scalars['Boolean']
isInternalMessagesImportEnabled: Scalars['Boolean']
+ allowedIframeOrigins?: Scalars['String'][]
editableProfileFields?: Scalars['String'][]
defaultRole?: Role
aiChatModelTier: AiModelTier
@@ -3525,6 +3526,7 @@ export interface Mutation {
deleteFrontComponent: FrontComponent
activateWorkspace: Workspace
updateWorkspace: Workspace
+ updateWorkspaceAllowedIframeOrigins: Workspace
deleteCurrentWorkspace: Workspace
checkCustomDomainValidRecords?: DomainValidRecords
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult
@@ -4308,6 +4310,7 @@ export interface WorkspaceGenqlSelection{
isMicrosoftAuthBypassEnabled?: boolean | number
isCustomDomainEnabled?: boolean | number
isInternalMessagesImportEnabled?: boolean | number
+ allowedIframeOrigins?: boolean | number
editableProfileFields?: boolean | number
defaultRole?: RoleGenqlSelection
aiChatModelTier?: boolean | number
@@ -7404,6 +7407,7 @@ export interface MutationGenqlSelection{
deleteFrontComponent?: (FrontComponentGenqlSelection & { __args: {id: Scalars['UUID']} })
activateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: ActivateWorkspaceInput} })
updateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceInput} })
+ updateWorkspaceAllowedIframeOrigins?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceAllowedIframeOriginsInput} })
deleteCurrentWorkspace?: WorkspaceGenqlSelection
checkCustomDomainValidRecords?: DomainValidRecordsGenqlSelection
enrichWorkspaceCompany?: WorkspaceCompanyEnrichmentResultGenqlSelection
@@ -7810,6 +7814,8 @@ displayName?: (Scalars['String'] | null)}
export interface UpdateWorkspaceInput {subdomain?: (Scalars['String'] | null),customDomain?: (Scalars['String'] | null),displayName?: (Scalars['String'] | null),logo?: (Scalars['String'] | null),inviteHash?: (Scalars['String'] | null),isPublicInviteLinkEnabled?: (Scalars['Boolean'] | null),workspaceDiscoverability?: (WorkspaceDiscoverability | null),allowImpersonation?: (Scalars['Boolean'] | null),isGoogleAuthEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthEnabled?: (Scalars['Boolean'] | null),isPasswordAuthEnabled?: (Scalars['Boolean'] | null),isGoogleAuthBypassEnabled?: (Scalars['Boolean'] | null),isMicrosoftAuthBypassEnabled?: (Scalars['Boolean'] | null),isPasswordAuthBypassEnabled?: (Scalars['Boolean'] | null),defaultRoleId?: (Scalars['UUID'] | null),isTwoFactorAuthenticationEnforced?: (Scalars['Boolean'] | null),trashRetentionDays?: (Scalars['Float'] | null),eventLogRetentionDays?: (Scalars['Float'] | null),aiChatModelTier?: (AiModelTier | null),aiAgentModelTier?: (AiModelTier | null),isAutoModelSelectionEnabled?: (Scalars['Boolean'] | null),aiModelIdByTier?: (Scalars['JSON'] | null),aiEvaluationModelId?: (Scalars['String'] | null),aiAdditionalInstructions?: (Scalars['String'] | null),editableProfileFields?: (Scalars['String'][] | null),isInternalMessagesImportEnabled?: (Scalars['Boolean'] | null)}
+export interface UpdateWorkspaceAllowedIframeOriginsInput {operation: Scalars['String'],origin: Scalars['String']}
+
export interface CreateApplicationRegistrationInput {name: Scalars['String'],universalIdentifier?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
export interface UpdateApplicationRegistrationInput {id: Scalars['String'],update: UpdateApplicationRegistrationPayload}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 28ccb19ec64..bade3b01483 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -103,9 +103,9 @@ export default {
406,
423,
435,
- 556,
- 560,
- 587
+ 557,
+ 561,
+ 588
],
"types": {
"BillingProductDTO": {
@@ -1685,6 +1685,9 @@ export default {
"isInternalMessagesImportEnabled": [
8
],
+ "allowedIframeOrigins": [
+ 1
+ ],
"editableProfileFields": [
1
],
@@ -9563,6 +9566,15 @@ export default {
]
}
],
+ "updateWorkspaceAllowedIframeOrigins": [
+ 71,
+ {
+ "data": [
+ 509,
+ "UpdateWorkspaceAllowedIframeOriginsInput!"
+ ]
+ }
+ ],
"deleteCurrentWorkspace": [
71
],
@@ -9589,7 +9601,7 @@ export default {
228,
{
"input": [
- 509,
+ 510,
"CreateApplicationRegistrationInput!"
]
}
@@ -9598,7 +9610,7 @@ export default {
78,
{
"input": [
- 510,
+ 511,
"UpdateApplicationRegistrationInput!"
]
}
@@ -9625,7 +9637,7 @@ export default {
200,
{
"input": [
- 512,
+ 513,
"CreateApplicationRegistrationVariableInput!"
]
}
@@ -9634,7 +9646,7 @@ export default {
200,
{
"input": [
- 513,
+ 514,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -9695,7 +9707,7 @@ export default {
253,
{
"input": [
- 515,
+ 516,
"GrantApplicationCapabilitiesInput!"
]
}
@@ -9728,7 +9740,7 @@ export default {
251,
{
"input": [
- 516,
+ 517,
"TriggerInstallApplicationJobInput!"
]
}
@@ -9737,7 +9749,7 @@ export default {
252,
{
"input": [
- 517,
+ 518,
"TriggerUninstallApplicationJobInput!"
]
}
@@ -9750,7 +9762,7 @@ export default {
"UUID!"
],
"input": [
- 518,
+ 519,
"UpdateApplicationInput!"
]
}
@@ -9780,7 +9792,7 @@ export default {
257,
{
"input": [
- 519,
+ 520,
"CreateOneFieldMetadataInput!"
]
}
@@ -9789,7 +9801,7 @@ export default {
257,
{
"input": [
- 521,
+ 522,
"UpdateOneFieldMetadataInput!"
]
}
@@ -9798,7 +9810,7 @@ export default {
257,
{
"input": [
- 523,
+ 524,
"DeleteOneFieldInput!"
]
}
@@ -9807,7 +9819,7 @@ export default {
61,
{
"input": [
- 524,
+ 525,
"CreateViewGroupInput!"
]
}
@@ -9816,7 +9828,7 @@ export default {
61,
{
"inputs": [
- 524,
+ 525,
"[CreateViewGroupInput!]!"
]
}
@@ -9825,7 +9837,7 @@ export default {
61,
{
"input": [
- 525,
+ 526,
"UpdateViewGroupInput!"
]
}
@@ -9834,7 +9846,7 @@ export default {
61,
{
"inputs": [
- 525,
+ 526,
"[UpdateViewGroupInput!]!"
]
}
@@ -9843,7 +9855,7 @@ export default {
61,
{
"input": [
- 527,
+ 528,
"DeleteViewGroupInput!"
]
}
@@ -9852,7 +9864,7 @@ export default {
61,
{
"input": [
- 528,
+ 529,
"DestroyViewGroupInput!"
]
}
@@ -9874,7 +9886,7 @@ export default {
50,
{
"createRoleInput": [
- 529,
+ 530,
"CreateRoleInput!"
]
}
@@ -9883,7 +9895,7 @@ export default {
50,
{
"updateRoleInput": [
- 530,
+ 531,
"UpdateRoleInput!"
]
}
@@ -9901,7 +9913,7 @@ export default {
47,
{
"upsertObjectPermissionsInput": [
- 532,
+ 533,
"UpsertObjectPermissionsInput!"
]
}
@@ -9910,7 +9922,7 @@ export default {
48,
{
"upsertPermissionFlagsInput": [
- 534,
+ 535,
"UpsertPermissionFlagsInput!"
]
}
@@ -9919,7 +9931,7 @@ export default {
42,
{
"upsertFieldPermissionsInput": [
- 535,
+ 536,
"UpsertFieldPermissionsInput!"
]
}
@@ -9928,7 +9940,7 @@ export default {
278,
{
"input": [
- 537,
+ 538,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9959,7 +9971,7 @@ export default {
337,
{
"input": [
- 540,
+ 541,
"SendEmailViaDomainInput!"
]
}
@@ -9968,7 +9980,7 @@ export default {
338,
{
"input": [
- 541,
+ 542,
"SendMessageCampaignInput!"
]
}
@@ -9977,7 +9989,7 @@ export default {
336,
{
"input": [
- 542,
+ 543,
"CancelMessageCampaignInput!"
]
}
@@ -9986,7 +9998,7 @@ export default {
337,
{
"input": [
- 543,
+ 544,
"SendMessageCampaignTestInput!"
]
}
@@ -10004,7 +10016,7 @@ export default {
340,
{
"input": [
- 544,
+ 545,
"CreateMessageSuppressionInput!"
]
}
@@ -10022,7 +10034,7 @@ export default {
344,
{
"input": [
- 545,
+ 546,
"CreateUnsubscribeTopicInput!"
]
}
@@ -10031,7 +10043,7 @@ export default {
344,
{
"input": [
- 546,
+ 547,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -10049,7 +10061,7 @@ export default {
324,
{
"input": [
- 547,
+ 548,
"UpdateMessageChannelInput!"
]
}
@@ -10058,7 +10070,7 @@ export default {
334,
{
"input": [
- 549,
+ 550,
"CreateEmailGroupChannelInput!"
]
}
@@ -10067,7 +10079,7 @@ export default {
324,
{
"input": [
- 550,
+ 551,
"UpdateEmailGroupChannelInput!"
]
}
@@ -10085,7 +10097,7 @@ export default {
324,
{
"input": [
- 551,
+ 552,
"CreateAppMessageChannelInput!"
]
}
@@ -10094,7 +10106,7 @@ export default {
324,
{
"input": [
- 552,
+ 553,
"UpdateAppMessageChannelInput!"
]
}
@@ -10112,7 +10124,7 @@ export default {
333,
{
"input": [
- 553,
+ 554,
"IngestAppMessagesInput!"
]
}
@@ -10121,7 +10133,7 @@ export default {
320,
{
"input": [
- 557,
+ 558,
"CreateEmailingDomainInput!"
]
}
@@ -10148,7 +10160,7 @@ export default {
356,
{
"input": [
- 558,
+ 559,
"RunAgentInput!"
]
}
@@ -10157,7 +10169,7 @@ export default {
353,
{
"input": [
- 562,
+ 563,
"CreateWebhookInput!"
]
}
@@ -10166,7 +10178,7 @@ export default {
353,
{
"input": [
- 563,
+ 564,
"UpdateWebhookInput!"
]
}
@@ -10184,7 +10196,7 @@ export default {
397,
{
"input": [
- 565,
+ 566,
"UpdateMessageFolderInput!"
]
}
@@ -10193,7 +10205,7 @@ export default {
397,
{
"input": [
- 567,
+ 568,
"UpdateMessageFoldersInput!"
]
}
@@ -10202,7 +10214,7 @@ export default {
392,
{
"input": [
- 568,
+ 569,
"UpdateCalendarChannelInput!"
]
}
@@ -10211,7 +10223,7 @@ export default {
390,
{
"input": [
- 570,
+ 571,
"SetAppKeyValueInput!"
]
}
@@ -10232,7 +10244,7 @@ export default {
388,
{
"input": [
- 571,
+ 572,
"EnqueueJobInput!"
]
}
@@ -10241,7 +10253,7 @@ export default {
389,
{
"input": [
- 572,
+ 573,
"EnqueueJobsInput!"
]
}
@@ -10250,7 +10262,7 @@ export default {
8,
{
"input": [
- 574,
+ 575,
"ReportAppConnectionAuthFailureInput!"
]
}
@@ -10280,7 +10292,7 @@ export default {
1
],
"fileAttachments": [
- 575,
+ 576,
"[FileAttachmentInput!]"
]
}
@@ -10309,14 +10321,14 @@ export default {
"UUID!"
],
"answers": [
- 576,
+ 577,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 575,
+ 576,
"[FileAttachmentInput!]"
]
}
@@ -10394,7 +10406,7 @@ export default {
374,
{
"input": [
- 577,
+ 578,
"CreateSkillInput!"
]
}
@@ -10403,7 +10415,7 @@ export default {
374,
{
"input": [
- 578,
+ 579,
"UpdateSkillInput!"
]
}
@@ -10461,7 +10473,7 @@ export default {
403,
{
"input": [
- 579,
+ 580,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -10479,7 +10491,7 @@ export default {
287,
{
"input": [
- 580,
+ 581,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -10645,7 +10657,7 @@ export default {
290,
{
"input": [
- 581
+ 582
]
}
],
@@ -10823,7 +10835,7 @@ export default {
8,
{
"input": [
- 582,
+ 583,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -10857,7 +10869,7 @@ export default {
238,
{
"input": [
- 583,
+ 584,
"SetupOIDCSsoInput!"
]
}
@@ -10866,7 +10878,7 @@ export default {
238,
{
"input": [
- 584,
+ 585,
"SetupSAMLSsoInput!"
]
}
@@ -10875,7 +10887,7 @@ export default {
234,
{
"input": [
- 585,
+ 586,
"DeleteSsoInput!"
]
}
@@ -10884,7 +10896,7 @@ export default {
235,
{
"input": [
- 586,
+ 587,
"EditSsoInput!"
]
}
@@ -10913,7 +10925,7 @@ export default {
368,
{
"type": [
- 587,
+ 588,
"AnalyticsType!"
],
"name": [
@@ -10956,7 +10968,7 @@ export default {
358,
{
"input": [
- 588,
+ 589,
"CreateCalendarEventInput!"
]
}
@@ -10965,7 +10977,7 @@ export default {
367,
{
"input": [
- 589,
+ 590,
"SendEmailInput!"
]
}
@@ -10987,7 +10999,7 @@ export default {
"String!"
],
"connectionParameters": [
- 591,
+ 592,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10999,7 +11011,7 @@ export default {
197,
{
"input": [
- 593,
+ 594,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -11092,7 +11104,7 @@ export default {
"String!"
],
"files": [
- 594,
+ 595,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -12771,6 +12783,17 @@ export default {
1
]
},
+ "UpdateWorkspaceAllowedIframeOriginsInput": {
+ "operation": [
+ 1
+ ],
+ "origin": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateApplicationRegistrationInput": {
"name": [
1
@@ -12793,7 +12816,7 @@ export default {
1
],
"update": [
- 511
+ 512
],
"__typename": [
1
@@ -12838,7 +12861,7 @@ export default {
1
],
"update": [
- 514
+ 515
],
"__typename": [
1
@@ -12895,7 +12918,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 520
+ 521
],
"__typename": [
1
@@ -12974,7 +12997,7 @@ export default {
3
],
"update": [
- 522
+ 523
],
"__typename": [
1
@@ -13078,7 +13101,7 @@ export default {
3
],
"update": [
- 526
+ 527
],
"__typename": [
1
@@ -13163,7 +13186,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 531
+ 532
],
"id": [
3
@@ -13218,7 +13241,7 @@ export default {
3
],
"objectPermissions": [
- 533
+ 534
],
"__typename": [
1
@@ -13260,7 +13283,7 @@ export default {
3
],
"fieldPermissions": [
- 536
+ 537
],
"__typename": [
1
@@ -13291,10 +13314,10 @@ export default {
3
],
"predicates": [
- 538
+ 539
],
"predicateGroups": [
- 539
+ 540
],
"__typename": [
1
@@ -13470,7 +13493,7 @@ export default {
3
],
"update": [
- 548
+ 549
],
"__typename": [
1
@@ -13563,7 +13586,7 @@ export default {
3
],
"messages": [
- 554
+ 555
],
"__typename": [
1
@@ -13586,7 +13609,7 @@ export default {
4
],
"participants": [
- 555
+ 556
],
"__typename": [
1
@@ -13594,7 +13617,7 @@ export default {
},
"AppMessageParticipantInput": {
"role": [
- 556
+ 557
],
"handle": [
1
@@ -13632,7 +13655,7 @@ export default {
3
],
"messages": [
- 559
+ 560
],
"__typename": [
1
@@ -13640,13 +13663,13 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 560
+ 561
],
"content": [
1
],
"attachments": [
- 561
+ 562
],
"__typename": [
1
@@ -13689,7 +13712,7 @@ export default {
3
],
"update": [
- 564
+ 565
],
"__typename": [
1
@@ -13717,7 +13740,7 @@ export default {
3
],
"update": [
- 566
+ 567
],
"__typename": [
1
@@ -13736,7 +13759,7 @@ export default {
3
],
"update": [
- 566
+ 567
],
"__typename": [
1
@@ -13747,7 +13770,7 @@ export default {
3
],
"update": [
- 569
+ 570
],
"__typename": [
1
@@ -13812,7 +13835,7 @@ export default {
9
],
"jobs": [
- 573
+ 574
],
"retryLimit": [
30
@@ -14100,7 +14123,7 @@ export default {
1
],
"files": [
- 590
+ 591
],
"__typename": [
1
@@ -14122,13 +14145,13 @@ export default {
1
],
"IMAP": [
- 592
+ 593
],
"SMTP": [
- 592
+ 593
],
"CALDAV": [
- 592
+ 593
],
"__typename": [
1
@@ -14193,7 +14216,7 @@ export default {
279,
{
"input": [
- 596,
+ 597,
"LogicFunctionLogsInput!"
]
}
@@ -14220,7 +14243,7 @@ export default {
372,
{
"input": [
- 597,
+ 598,
"CreateRecordExportInput!"
]
}
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 2245ba035f5..cd313183efd 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -3264,6 +3264,7 @@ export type Mutation = {
updateViewSort: ViewSort;
updateWebhook: Webhook;
updateWorkspace: Workspace;
+ updateWorkspaceAllowedIframeOrigins: Workspace;
updateWorkspaceMemberRole: WorkspaceMember;
updateWorkspaceMemberSettings: Scalars['Boolean']['output'];
upgradeApplication: Scalars['Boolean']['output'];
@@ -4476,6 +4477,11 @@ export type MutationUpdateWorkspaceArgs = {
};
+export type MutationUpdateWorkspaceAllowedIframeOriginsArgs = {
+ data: UpdateWorkspaceAllowedIframeOriginsInput;
+};
+
+
export type MutationUpdateWorkspaceMemberRoleArgs = {
roleId: Scalars['UUID']['input'];
workspaceMemberId: Scalars['UUID']['input'];
@@ -6790,6 +6796,11 @@ export type UpdateWebhookInputUpdates = {
targetUrl?: InputMaybe<Scalars['String']['input']>;
};
+export type UpdateWorkspaceAllowedIframeOriginsInput = {
+ operation: Scalars['String']['input'];
+ origin: Scalars['String']['input'];
+};
+
export type UpdateWorkspaceInput = {
aiAdditionalInstructions?: InputMaybe<Scalars['String']['input']>;
aiAgentModelTier?: InputMaybe<AiModelTier>;
@@ -7474,6 +7485,7 @@ export type Workspace = {
aiEvaluationModelId?: Maybe<Scalars['String']['output']>;
aiModelIdByTier: Scalars['JSON']['output'];
allowImpersonation: Scalars['Boolean']['output'];
+ allowedIframeOrigins?: Maybe<Array<Scalars['String']['output']>>;
billingCustomer?: Maybe<BillingCustomer>;
billingEntitlements: Array<BillingEntitlement>;
billingSubscriptions: Array<BillingSubscription>;
@@ -10190,6 +10202,13 @@ export type UpdateWorkspaceMutationVariables = Exact<{
export type UpdateWorkspaceMutation = { __typename?: 'Mutation', updateWorkspace: { __typename?: 'Workspace', id: string, customDomain?: string | null, subdomain: string, displayName?: string | null, logo?: string | null, allowImpersonation: boolean, isPublicInviteLinkEnabled: boolean, workspaceDiscoverability: WorkspaceDiscoverability, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isTwoFactorAuthenticationEnforced: boolean, isInternalMessagesImportEnabled: boolean, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } };
+export type UpdateWorkspaceAllowedIframeOriginsMutationVariables = Exact<{
+ input: UpdateWorkspaceAllowedIframeOriginsInput;
+}>;
+
+
+export type UpdateWorkspaceAllowedIframeOriginsMutation = { __typename?: 'Mutation', updateWorkspaceAllowedIframeOrigins: { __typename?: 'Workspace', id: string, allowedIframeOrigins?: Array<string> | null } };
+
export type UploadWorkspaceLogoMutationVariables = Exact<{
file: Scalars['Upload']['input'];
}>;
@@ -10221,6 +10240,11 @@ export type GetWorkspaceFromInviteHashQueryVariables = Exact<{
export type GetWorkspaceFromInviteHashQuery = { __typename?: 'Query', findWorkspaceFromInviteHash: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, allowImpersonation: boolean } };
+export type GetWorkspaceIframeOriginsQueryVariables = Exact<{ [key: string]: never; }>;
+
+
+export type GetWorkspaceIframeOriginsQuery = { __typename?: 'Query', currentWorkspace: { __typename?: 'Workspace', id: string, allowedIframeOrigins?: Array<string> | null } };
+
export type FindManyApplicationsForToolTableQueryVariables = Exact<{ [key: string]: never; }>;
@@ -10579,10 +10603,12 @@ export const GetWorkspaceInvitationsDocument = {"kind":"Document","definitions":
export const ActivateWorkspaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateWorkspace"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ActivateWorkspaceInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activateWorkspace"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"data"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<ActivateWorkspaceMutation, ActivateWorkspaceMutationVariables>;
export const DeleteCurrentWorkspaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteCurrentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteCurrentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<DeleteCurrentWorkspaceMutation, DeleteCurrentWorkspaceMutationVariables>;
export const UpdateWorkspaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkspace"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkspaceInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkspace"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"data"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"customDomain"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"isPublicInviteLinkEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDiscoverability"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isTwoFactorAuthenticationEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"isInternalMessagesImportEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRole"},"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":"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"}}]}}]} as unknown as DocumentNode<UpdateWorkspaceMutation, UpdateWorkspaceMutationVariables>;
+export const UpdateWorkspaceAllowedIframeOriginsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkspaceAllowedIframeOrigins"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkspaceAllowedIframeOriginsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkspaceAllowedIframeOrigins"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"data"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"allowedIframeOrigins"}}]}}]}}]} as unknown as DocumentNode<UpdateWorkspaceAllowedIframeOriginsMutation, UpdateWorkspaceAllowedIframeOriginsMutationVariables>;
export const UploadWorkspaceLogoDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UploadWorkspaceLogo"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"file"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Upload"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"uploadWorkspaceLogo"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"file"},"value":{"kind":"Variable","name":{"kind":"Name","value":"file"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<UploadWorkspaceLogoMutation, UploadWorkspaceLogoMutationVariables>;
export const CheckCustomDomainValidRecordsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CheckCustomDomainValidRecords"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"checkCustomDomainValidRecords"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"domain"}},{"kind":"Field","name":{"kind":"Name","value":"isCustomDomainEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"records"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"validationType"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}}]}}]} as unknown as DocumentNode<CheckCustomDomainValidRecordsMutation, CheckCustomDomainValidRecordsMutationVariables>;
export const GetAiSystemPromptPreviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAiSystemPromptPreview"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAiSystemPromptPreview"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sections"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"estimatedTokenCount"}}]}},{"kind":"Field","name":{"kind":"Name","value":"estimatedTokenCount"}}]}}]}}]} as unknown as DocumentNode<GetAiSystemPromptPreviewQuery, GetAiSystemPromptPreviewQueryVariables>;
export const GetPublicWorkspaceDataByIdDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetPublicWorkspaceDataById"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getPublicWorkspaceDataById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}}]}}]}}]} as unknown as DocumentNode<GetPublicWorkspaceDataByIdQuery, GetPublicWorkspaceDataByIdQueryVariables>;
export const GetWorkspaceFromInviteHashDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetWorkspaceFromInviteHash"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"inviteHash"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findWorkspaceFromInviteHash"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"inviteHash"},"value":{"kind":"Variable","name":{"kind":"Name","value":"inviteHash"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}}]}}]}}]} as unknown as DocumentNode<GetWorkspaceFromInviteHashQuery, GetWorkspaceFromInviteHashQueryVariables>;
+export const GetWorkspaceIframeOriginsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetWorkspaceIframeOrigins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"allowedIframeOrigins"}}]}}]}}]} as unknown as DocumentNode<GetWorkspaceIframeOriginsQuery, GetWorkspaceIframeOriginsQueryVariables>;
export const FindManyApplicationsForToolTableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyApplicationsForToolTable"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}}]}}]}}]} as unknown as DocumentNode<FindManyApplicationsForToolTableQuery, FindManyApplicationsForToolTableQueryVariables>;
export const FindManyMarketplaceAppsForToolTableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyMarketplaceAppsForToolTable"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyMarketplaceApps"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}}]}}]}}]} as unknown as DocumentNode<FindManyMarketplaceAppsForToolTableQuery, FindManyMarketplaceAppsForToolTableQueryVariables>;
\ No newline at end of file
diff --git a/packages/twenty-front/src/modules/client-config/components/ClientConfigProviderEffect.tsx b/packages/twenty-front/src/modules/client-config/components/ClientConfigProviderEffect.tsx
index 378165296a4..1c1c82a06dd 100644
--- a/packages/twenty-front/src/modules/client-config/components/ClientConfigProviderEffect.tsx
+++ b/packages/twenty-front/src/modules/client-config/components/ClientConfigProviderEffect.tsx
@@ -1,27 +1,31 @@
import { useClientConfig } from '@/client-config/hooks/useClientConfig';
import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
import { isDefined } from 'twenty-shared/utils';
export const ClientConfigProviderEffect = () => {
+ // oxlint-disable-next-line twenty/no-state-useref
+ const isInitializationStarted = useRef(false);
const [clientConfigApiStatus, setClientConfigApiStatus] = useAtomState(
clientConfigApiStatusState,
);
- const { data, loading, error, fetchClientConfig } = useClientConfig();
+ const { data, loading, error, initializeClientConfig } = useClientConfig();
useEffect(() => {
if (
!clientConfigApiStatus.isLoadedOnce &&
- !clientConfigApiStatus.isLoading
+ !clientConfigApiStatus.isLoading &&
+ !isInitializationStarted.current
) {
- fetchClientConfig();
+ isInitializationStarted.current = true;
+ initializeClientConfig();
}
}, [
clientConfigApiStatus.isLoadedOnce,
clientConfigApiStatus.isLoading,
- fetchClientConfig,
+ initializeClientConfig,
]);
useEffect(() => {
diff --git a/packages/twenty-front/src/modules/client-config/components/__tests__/ClientConfigProviderEffect.test.tsx b/packages/twenty-front/src/modules/client-config/components/__tests__/ClientConfigProviderEffect.test.tsx
new file mode 100644
index 00000000000..55138c584c8
--- /dev/null
+++ b/packages/twenty-front/src/modules/client-config/components/__tests__/ClientConfigProviderEffect.test.tsx
@@ -0,0 +1,24 @@
+import { StrictMode } from 'react';
+import { render } from '@testing-library/react';
+
+import { ClientConfigProviderEffect } from '@/client-config/components/ClientConfigProviderEffect';
+
+const initializeClientConfig = jest.fn();
+
+jest.mock('@/client-config/hooks/useClientConfig', () => ({
+ useClientConfig: () => ({ initializeClientConfig }),
+}));
+
+jest.mock('@/ui/utilities/state/jotai/hooks/useAtomState', () => ({
+ useAtomState: () => [{ isLoadedOnce: false, isLoading: false }, jest.fn()],
+}));
+
+it('initializes once when StrictMode replays startup effects', () => {
+ render(
+ <StrictMode>
+ <ClientConfigProviderEffect />
+ </StrictMode>,
+ );
+
+ expect(initializeClientConfig).toHaveBeenCalledTimes(1);
+});
diff --git a/packages/twenty-front/src/modules/client-config/hooks/useClientConfig.ts b/packages/twenty-front/src/modules/client-config/hooks/useClientConfig.ts
index e32c656c342..c9320abff4a 100644
--- a/packages/twenty-front/src/modules/client-config/hooks/useClientConfig.ts
+++ b/packages/twenty-front/src/modules/client-config/hooks/useClientConfig.ts
@@ -37,6 +37,7 @@ import { domainConfigurationState } from '@/domain-manager/states/domainConfigur
import { useCallback } from 'react';
import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';
import { getClientConfig } from '@/client-config/utils/getClientConfig';
+import { getInitialClientConfig } from '@/client-config/utils/getInitialClientConfig';
import { allowRequestsToTwentyIconsState } from '@/client-config/states/allowRequestsToTwentyIcons';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
@@ -46,7 +47,7 @@ type UseClientConfigResult = {
data: { clientConfig: ClientConfig } | undefined;
loading: boolean;
error: Error | undefined;
- fetchClientConfig: () => Promise<void>;
+ initializeClientConfig: () => Promise<void>;
refetch: () => Promise<void>;
};
@@ -153,160 +154,181 @@ export const useClientConfig = (): UseClientConfigResult => {
const setAppVersion = useSetAtomState(appVersionState);
- const fetchClientConfig = useCallback(async () => {
- setClientConfigApiStatus((prev) => ({
- ...prev,
- isLoading: true,
- }));
-
- try {
- const clientConfig = await getClientConfig();
+ const loadClientConfig = useCallback(
+ async (getConfiguration: () => Promise<ClientConfig>) => {
setClientConfigApiStatus((prev) => ({
...prev,
- isLoading: false,
- isLoadedOnce: true,
- isErrored: false,
- error: undefined,
- data: { clientConfig },
- }));
- setClientConfigApiStatus((currentStatus) => ({
- ...currentStatus,
- isErrored: false,
- error: undefined,
- }));
- setAppVersion(clientConfig.appVersion);
- setAuthProviders({
- google: clientConfig.authProviders.google,
- microsoft: clientConfig.authProviders.microsoft,
- password: clientConfig.authProviders.password,
- magicLink: false,
- sso: clientConfig.authProviders.sso,
- });
- setAiModels(clientConfig.aiModels ?? []);
- setAiEvaluationModels(clientConfig.aiEvaluationModels ?? []);
- setAiModelTiers(clientConfig.aiModelTiers ?? []);
- setIsAnalyticsEnabled(clientConfig.analyticsEnabled);
- setIsDeveloperDefaultSignInPrefilled(clientConfig.signInPrefilled);
- setIsMultiWorkspaceEnabled(clientConfig.isMultiWorkspaceEnabled);
- setIsEmailVerificationRequired(clientConfig.isEmailVerificationRequired);
- setBilling(clientConfig.billing);
- setSupportChat(clientConfig.support);
-
- setSentryConfig({
- dsn: clientConfig?.sentry?.dsn,
- release: clientConfig?.sentry?.release,
- environment: clientConfig?.sentry?.environment,
- tracesSampleRate: clientConfig?.sentry?.tracesSampleRate,
- });
-
- setCaptcha({
- provider: clientConfig?.captcha?.provider,
- siteKey: clientConfig?.captcha?.siteKey,
- });
-
- setApiConfig(clientConfig?.api);
- setOnboardingConfig(clientConfig?.onboarding ?? null);
- setDomainConfiguration({
- defaultSubdomain: clientConfig?.defaultSubdomain,
- frontDomain: clientConfig?.frontDomain,
- publicFunctionDomain: clientConfig?.publicFunctionDomain,
- });
- setCanManageFeatureFlags(clientConfig?.canManageFeatureFlags);
- setLabPublicFeatureFlags(clientConfig?.publicFeatureFlags);
- setIsMicrosoftMessagingEnabled(clientConfig?.isMicrosoftMessagingEnabled);
- setIsMicrosoftCalendarEnabled(clientConfig?.isMicrosoftCalendarEnabled);
- setIsGoogleMessagingEnabled(clientConfig?.isGoogleMessagingEnabled);
- setIsGoogleCalendarEnabled(clientConfig?.isGoogleCalendarEnabled);
- setIsAttachmentPreviewEnabled(clientConfig?.isAttachmentPreviewEnabled);
- setIsConfigVariablesInDbEnabled(
- clientConfig?.isConfigVariablesInDbEnabled,
- );
- setClientConfigApiStatus((currentStatus) => ({
- ...currentStatus,
- isSaved: true,
+ isLoading: true,
}));
- setCalendarBookingPageId(clientConfig?.calendarBookingPageId ?? null);
- setIsBookCallOnboardingStepEnabled(
- clientConfig?.isBookCallOnboardingStepEnabled ?? false,
- );
- setIsCompanyEnrichmentEnabled(
- clientConfig?.isCompanyEnrichmentEnabled ?? false,
- );
- setIsImapSmtpCaldavEnabled(clientConfig?.isImapSmtpCaldavEnabled);
- setIsEmailingDomainInDemoMode(
- clientConfig?.isEmailingDomainInDemoMode ?? false,
- );
- setAllowRequestsToTwentyIcons(clientConfig?.allowRequestsToTwentyIcons);
- setIsCloudflareIntegrationEnabled(
- clientConfig?.isCloudflareIntegrationEnabled,
- );
- setIsClickHouseConfigured(clientConfig?.isClickHouseConfigured ?? false);
- setIsDDLLocked(clientConfig?.isWorkspaceSchemaDDLLocked ?? false);
- setIsOnboardingAiChatEnabled(
- clientConfig?.isOnboardingAiChatEnabled ?? false,
- );
- setMaintenanceMode(clientConfig?.maintenance ?? null);
- setEnterpriseInstanceType(
- clientConfig?.enterpriseInstanceType ??
- ENTERPRISE_INSTANCE_TYPE.PRODUCTION,
- );
- } catch (err) {
- const error =
- err instanceof Error ? err : new Error('Failed to fetch client config');
- setClientConfigApiStatus((prev) => ({
- ...prev,
- isLoading: false,
- isLoadedOnce: true,
- isErrored: true,
- error,
- }));
- }
- }, [
- setAiModels,
- setAiEvaluationModels,
- setAiModelTiers,
- setApiConfig,
- setOnboardingConfig,
- setAppVersion,
- setAuthProviders,
- setBilling,
- setCalendarBookingPageId,
- setCanManageFeatureFlags,
- setCaptcha,
- setClientConfigApiStatus,
- setDomainConfiguration,
- setIsGoogleCalendarEnabled,
- setIsGoogleMessagingEnabled,
- setIsAnalyticsEnabled,
- setIsAttachmentPreviewEnabled,
- setIsBookCallOnboardingStepEnabled,
- setIsCompanyEnrichmentEnabled,
- setIsConfigVariablesInDbEnabled,
- setIsDeveloperDefaultSignInPrefilled,
- setIsEmailVerificationRequired,
- setIsImapSmtpCaldavEnabled,
- setIsMultiWorkspaceEnabled,
- setIsEmailingDomainInDemoMode,
- setIsClickHouseConfigured,
- setIsCloudflareIntegrationEnabled,
- setIsDDLLocked,
- setIsOnboardingAiChatEnabled,
- setLabPublicFeatureFlags,
- setMaintenanceMode,
- setEnterpriseInstanceType,
- setIsMicrosoftCalendarEnabled,
- setIsMicrosoftMessagingEnabled,
- setSentryConfig,
- setSupportChat,
- setAllowRequestsToTwentyIcons,
- ]);
+ try {
+ const clientConfig = await getConfiguration();
+ setClientConfigApiStatus((prev) => ({
+ ...prev,
+ isLoading: false,
+ isLoadedOnce: true,
+ isErrored: false,
+ error: undefined,
+ data: { clientConfig },
+ }));
+ setClientConfigApiStatus((currentStatus) => ({
+ ...currentStatus,
+ isErrored: false,
+ error: undefined,
+ }));
+ setAppVersion(clientConfig.appVersion);
+ setAuthProviders({
+ google: clientConfig.authProviders.google,
+ microsoft: clientConfig.authProviders.microsoft,
+ password: clientConfig.authProviders.password,
+ magicLink: false,
+ sso: clientConfig.authProviders.sso,
+ });
+ setAiModels(clientConfig.aiModels ?? []);
+ setAiEvaluationModels(clientConfig.aiEvaluationModels ?? []);
+ setAiModelTiers(clientConfig.aiModelTiers ?? []);
+ setIsAnalyticsEnabled(clientConfig.analyticsEnabled);
+ setIsDeveloperDefaultSignInPrefilled(clientConfig.signInPrefilled);
+ setIsMultiWorkspaceEnabled(clientConfig.isMultiWorkspaceEnabled);
+ setIsEmailVerificationRequired(
+ clientConfig.isEmailVerificationRequired,
+ );
+ setBilling(clientConfig.billing);
+ setSupportChat(clientConfig.support);
+
+ setSentryConfig({
+ dsn: clientConfig?.sentry?.dsn,
+ release: clientConfig?.sentry?.release,
+ environment: clientConfig?.sentry?.environment,
+ tracesSampleRate: clientConfig?.sentry?.tracesSampleRate,
+ });
+
+ setCaptcha({
+ provider: clientConfig?.captcha?.provider,
+ siteKey: clientConfig?.captcha?.siteKey,
+ });
+
+ setApiConfig(clientConfig?.api);
+ setOnboardingConfig(clientConfig?.onboarding ?? null);
+ setDomainConfiguration({
+ defaultSubdomain: clientConfig?.defaultSubdomain,
+ frontDomain: clientConfig?.frontDomain,
+ publicFunctionDomain: clientConfig?.publicFunctionDomain,
+ });
+ setCanManageFeatureFlags(clientConfig?.canManageFeatureFlags);
+ setLabPublicFeatureFlags(clientConfig?.publicFeatureFlags);
+ setIsMicrosoftMessagingEnabled(
+ clientConfig?.isMicrosoftMessagingEnabled,
+ );
+ setIsMicrosoftCalendarEnabled(clientConfig?.isMicrosoftCalendarEnabled);
+ setIsGoogleMessagingEnabled(clientConfig?.isGoogleMessagingEnabled);
+ setIsGoogleCalendarEnabled(clientConfig?.isGoogleCalendarEnabled);
+ setIsAttachmentPreviewEnabled(clientConfig?.isAttachmentPreviewEnabled);
+ setIsConfigVariablesInDbEnabled(
+ clientConfig?.isConfigVariablesInDbEnabled,
+ );
+ setClientConfigApiStatus((currentStatus) => ({
+ ...currentStatus,
+ isSaved: true,
+ }));
+
+ setCalendarBookingPageId(clientConfig?.calendarBookingPageId ?? null);
+ setIsBookCallOnboardingStepEnabled(
+ clientConfig?.isBookCallOnboardingStepEnabled ?? false,
+ );
+ setIsCompanyEnrichmentEnabled(
+ clientConfig?.isCompanyEnrichmentEnabled ?? false,
+ );
+ setIsImapSmtpCaldavEnabled(clientConfig?.isImapSmtpCaldavEnabled);
+ setIsEmailingDomainInDemoMode(
+ clientConfig?.isEmailingDomainInDemoMode ?? false,
+ );
+ setAllowRequestsToTwentyIcons(clientConfig?.allowRequestsToTwentyIcons);
+ setIsCloudflareIntegrationEnabled(
+ clientConfig?.isCloudflareIntegrationEnabled,
+ );
+ setIsClickHouseConfigured(
+ clientConfig?.isClickHouseConfigured ?? false,
+ );
+ setIsDDLLocked(clientConfig?.isWorkspaceSchemaDDLLocked ?? false);
+ setIsOnboardingAiChatEnabled(
+ clientConfig?.isOnboardingAiChatEnabled ?? false,
+ );
+ setMaintenanceMode(clientConfig?.maintenance ?? null);
+ setEnterpriseInstanceType(
+ clientConfig?.enterpriseInstanceType ??
+ ENTERPRISE_INSTANCE_TYPE.PRODUCTION,
+ );
+ } catch (err) {
+ const error =
+ err instanceof Error
+ ? err
+ : new Error('Failed to fetch client config');
+ setClientConfigApiStatus((prev) => ({
+ ...prev,
+ isLoading: false,
+ isLoadedOnce: true,
+ isErrored: true,
+ error,
+ }));
+ }
+ },
+ [
+ setAiModels,
+ setAiEvaluationModels,
+ setAiModelTiers,
+ setApiConfig,
+ setOnboardingConfig,
+ setAppVersion,
+ setAuthProviders,
+ setBilling,
+ setCalendarBookingPageId,
+ setCanManageFeatureFlags,
+ setCaptcha,
+ setClientConfigApiStatus,
+ setDomainConfiguration,
+ setIsGoogleCalendarEnabled,
+ setIsGoogleMessagingEnabled,
+ setIsAnalyticsEnabled,
+ setIsAttachmentPreviewEnabled,
+ setIsBookCallOnboardingStepEnabled,
+ setIsCompanyEnrichmentEnabled,
+ setIsConfigVariablesInDbEnabled,
+ setIsDeveloperDefaultSignInPrefilled,
+ setIsEmailVerificationRequired,
+ setIsImapSmtpCaldavEnabled,
+ setIsMultiWorkspaceEnabled,
+ setIsEmailingDomainInDemoMode,
+ setIsClickHouseConfigured,
+ setIsCloudflareIntegrationEnabled,
+ setIsDDLLocked,
+ setIsOnboardingAiChatEnabled,
+ setLabPublicFeatureFlags,
+ setMaintenanceMode,
+ setEnterpriseInstanceType,
+ setIsMicrosoftCalendarEnabled,
+ setIsMicrosoftMessagingEnabled,
+ setSentryConfig,
+ setSupportChat,
+ setAllowRequestsToTwentyIcons,
+ ],
+ );
+
+ const refetch = useCallback(
+ () => loadClientConfig(getClientConfig),
+ [loadClientConfig],
+ );
+
+ const initializeClientConfig = useCallback(
+ () => loadClientConfig(getInitialClientConfig),
+ [loadClientConfig],
+ );
return {
data: clientConfigApiStatus.data,
loading: clientConfigApiStatus.isLoading || false,
error: clientConfigApiStatus.error,
- fetchClientConfig,
- refetch: fetchClientConfig,
+ initializeClientConfig,
+ refetch,
};
};
diff --git a/packages/twenty-front/src/modules/client-config/utils/__tests__/getInitialClientConfig.test.ts b/packages/twenty-front/src/modules/client-config/utils/__tests__/getInitialClientConfig.test.ts
new file mode 100644
index 00000000000..fa017fc75e5
--- /dev/null
+++ b/packages/twenty-front/src/modules/client-config/utils/__tests__/getInitialClientConfig.test.ts
@@ -0,0 +1,61 @@
+import { getInitialClientConfig } from '@/client-config/utils/getInitialClientConfig';
+import { getClientConfig } from '@/client-config/utils/getClientConfig';
+
+jest.mock('@/client-config/utils/getClientConfig', () => ({
+ getClientConfig: jest.fn(),
+}));
+
+const config = {
+ isMultiWorkspaceEnabled: true,
+ authProviders: { password: true },
+};
+
+describe('getInitialClientConfig', () => {
+ beforeEach(() => {
+ document.head.innerHTML = '';
+ jest.clearAllMocks();
+ });
+
+ const addBootstrap = (content: string) => {
+ const element = document.createElement('script');
+ element.id = 'twenty-client-config';
+ element.type = 'application/json';
+ element.textContent = content;
+ document.head.appendChild(element);
+ };
+
+ it('starts from the HTML configuration without an API request', async () => {
+ addBootstrap(JSON.stringify(config));
+
+ expect(await getInitialClientConfig()).toEqual(config);
+ expect(getClientConfig).not.toHaveBeenCalled();
+ expect(document.getElementById('twenty-client-config')).toBeNull();
+ });
+
+ it('uses the compatibility endpoint for static HTML and Vite', async () => {
+ jest
+ .mocked(getClientConfig)
+ .mockResolvedValueOnce(
+ config as Awaited<ReturnType<typeof getClientConfig>>,
+ );
+
+ expect(await getInitialClientConfig()).toEqual(config);
+ expect(getClientConfig).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['not JSON', 'null', '{}', '[]'])(
+ 'falls back for malformed bootstrap %s',
+ async (content) => {
+ addBootstrap(content);
+ await getInitialClientConfig();
+ expect(getClientConfig).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('does not reuse bootstrap configuration on a later initialization', async () => {
+ addBootstrap(JSON.stringify(config));
+ await getInitialClientConfig();
+ await getInitialClientConfig();
+ expect(getClientConfig).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/twenty-front/src/modules/client-config/utils/getInitialClientConfig.ts b/packages/twenty-front/src/modules/client-config/utils/getInitialClientConfig.ts
new file mode 100644
index 00000000000..c3427ef3cd2
--- /dev/null
+++ b/packages/twenty-front/src/modules/client-config/utils/getInitialClientConfig.ts
@@ -0,0 +1,32 @@
+import { isBoolean, isObject } from '@sniptt/guards';
+import { CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ClientConfig } from '@/client-config/types/ClientConfig';
+import { getClientConfig } from '@/client-config/utils/getClientConfig';
+
+export const getInitialClientConfig = async (): Promise<ClientConfig> => {
+ const element = document.getElementById(CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID);
+
+ if (isDefined(element)) {
+ const serializedConfig = element.textContent;
+
+ element.remove();
+
+ try {
+ const config: unknown = JSON.parse(serializedConfig ?? 'null');
+
+ if (
+ isObject(config) &&
+ 'isMultiWorkspaceEnabled' in config &&
+ isBoolean(config.isMultiWorkspaceEnabled) &&
+ 'authProviders' in config &&
+ isObject(config.authProviders)
+ ) {
+ return config as ClientConfig;
+ }
+ } catch {}
+ }
+
+ return getClientConfig();
+};
diff --git a/packages/twenty-front/src/modules/settings/security/components/SettingsSecurityIframeOrigins.tsx b/packages/twenty-front/src/modules/settings/security/components/SettingsSecurityIframeOrigins.tsx
new file mode 100644
index 00000000000..76a5e0e0204
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/security/components/SettingsSecurityIframeOrigins.tsx
@@ -0,0 +1,146 @@
+import { useState } from 'react';
+import { useMutation, useQuery } from '@apollo/client/react';
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isDefined, normalizeAllowedIframeOrigin } from 'twenty-shared/utils';
+import { Section, useToast } from 'twenty-ui/components';
+import { IconPlus, IconTrash } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
+import {
+ GetWorkspaceIframeOriginsDocument,
+ UpdateWorkspaceAllowedIframeOriginsDocument,
+} from '~/generated-metadata/graphql';
+
+const StyledList = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[3]};
+`;
+
+const StyledRow = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+ justify-content: space-between;
+`;
+
+const StyledOrigin = styled.span`
+ overflow-wrap: anywhere;
+`;
+
+export const SettingsSecurityIframeOrigins = () => {
+ const { t } = useLingui();
+ const { enqueueToast } = useToast();
+ const [originInput, setOriginInput] = useState('');
+ const [error, setError] = useState<string>();
+ const {
+ data,
+ loading: isLoadingPolicy,
+ error: policyError,
+ refetch,
+ } = useQuery(GetWorkspaceIframeOriginsDocument, {
+ fetchPolicy: 'network-only',
+ });
+ const [updateOrigins, { loading }] = useMutation(
+ UpdateWorkspaceAllowedIframeOriginsDocument,
+ );
+ const origins = data?.currentWorkspace.allowedIframeOrigins ?? [];
+ const isPolicyLoaded = isDefined(data?.currentWorkspace.allowedIframeOrigins);
+ const isDisabled = loading || isLoadingPolicy || !isPolicyLoaded;
+
+ const saveOrigin = async (
+ operation: 'add' | 'remove',
+ origin: string,
+ ): Promise<boolean> => {
+ if (isDisabled) {
+ return false;
+ }
+
+ try {
+ const { data } = await updateOrigins({
+ variables: { input: { operation, origin } },
+ });
+ return isDefined(data?.updateWorkspaceAllowedIframeOrigins);
+ } catch (error) {
+ enqueueToast(getToastOptionsFromError({ error }));
+ return false;
+ }
+ };
+
+ const handleAddOrigin = async () => {
+ const origin = normalizeAllowedIframeOrigin(originInput.trim());
+
+ if (!isDefined(origin)) {
+ setError(
+ t`Enter an HTTP or HTTPS origin without a path or wildcard, such as https://portal.example.com.`,
+ );
+
+ return;
+ }
+
+ if (await saveOrigin('add', origin)) {
+ setOriginInput('');
+ setError(undefined);
+ }
+ };
+
+ return (
+ <Section.Root>
+ <Section.Header
+ title={t`Iframe embedding`}
+ description={t`Allow trusted websites to display this workspace in an iframe. Users who are already signed in may see their workspace inside those websites, so only add origins you fully trust. Leave the list empty to block external embedding.`}
+ />
+ <StyledList>
+ {isDefined(policyError) && (
+ <>
+ <StyledOrigin role="alert">{t`Unable to load embedding settings.`}</StyledOrigin>
+ <Button onClick={() => refetch()}>{t`Retry`}</Button>
+ </>
+ )}
+ {origins.map((origin) => (
+ <StyledRow key={origin}>
+ <StyledOrigin>{origin}</StyledOrigin>
+ <Button
+ aria-label={t`Remove ${origin}`}
+ startIcon={<IconTrash size={16} />}
+ variant="outline"
+ size="sm"
+ disabled={isDisabled}
+ onClick={() => saveOrigin('remove', origin)}
+ >
+ {t`Remove`}
+ </Button>
+ </StyledRow>
+ ))}
+ <SettingsTextInput
+ instanceId="allowed-iframe-origin"
+ label={t`Allowed origin`}
+ placeholder="https://portal.example.com"
+ value={originInput}
+ disabled={isDisabled}
+ onChange={(value) => {
+ setOriginInput(value);
+ setError(undefined);
+ }}
+ onInputEnter={handleAddOrigin}
+ error={error}
+ />
+ <StyledRow>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={isDisabled || originInput.trim() === ''}
+ startIcon={<IconPlus size={16} />}
+ onClick={handleAddOrigin}
+ >
+ {t`Add origin`}
+ </Button>
+ </StyledRow>
+ </StyledList>
+ </Section.Root>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/security/components/SettingsSecuritySettings.tsx b/packages/twenty-front/src/modules/settings/security/components/SettingsSecuritySettings.tsx
index 4723ac95362..451ebac5da9 100644
--- a/packages/twenty-front/src/modules/settings/security/components/SettingsSecuritySettings.tsx
+++ b/packages/twenty-front/src/modules/settings/security/components/SettingsSecuritySettings.tsx
@@ -11,6 +11,7 @@ import { useSettingsAllRoles } from '@/settings/roles/hooks/useSettingsAllRoles'
import { SettingsSecurityAuthBypassOptionsList } from '@/settings/security/components/SettingsSecurityAuthBypassOptionsList';
import { SettingsSecurityAuthProvidersOptionsList } from '@/settings/security/components/SettingsSecurityAuthProvidersOptionsList';
import { SettingsSecurityEditableProfileFields } from '@/settings/security/components/SettingsSecurityEditableProfileFields';
+import { SettingsSecurityIframeOrigins } from '@/settings/security/components/SettingsSecurityIframeOrigins';
import { SettingsSsoIdentitiesProvidersListCard } from '@/settings/security/components/sso/SettingsSsoIdentitiesProvidersListCard';
import { ssoIdentitiesProvidersState } from '@/settings/security/states/ssoIdentitiesProvidersState';
import { ImpersonationSwitch } from '@/settings/workspace/components/ImpersonationSwitch';
@@ -175,6 +176,7 @@ export const SettingsSecuritySettings = () => {
</StyledContainer>
</Section.Root>
<SettingsRoleDefaultRole roles={roles} />
+ <SettingsSecurityIframeOrigins />
{shouldShowBypassSection && (
<Section.Root>
<StyledContainer>
diff --git a/packages/twenty-front/src/modules/settings/security/components/__tests__/SettingsSecurityIframeOrigins.test.tsx b/packages/twenty-front/src/modules/settings/security/components/__tests__/SettingsSecurityIframeOrigins.test.tsx
new file mode 100644
index 00000000000..3956e85710d
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/security/components/__tests__/SettingsSecurityIframeOrigins.test.tsx
@@ -0,0 +1,230 @@
+import { type MockedResponse } from '@apollo/client/testing';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createStore, Provider } from 'jotai';
+import { MAX_ALLOWED_IFRAME_ORIGINS } from 'twenty-shared/constants';
+
+import { SettingsSecurityIframeOrigins } from '@/settings/security/components/SettingsSecurityIframeOrigins';
+import {
+ GetWorkspaceIframeOriginsDocument,
+ UpdateWorkspaceAllowedIframeOriginsDocument,
+} from '~/generated-metadata/graphql';
+
+const enqueueToast = jest.fn();
+
+jest.mock('twenty-ui/components', () => ({
+ ...jest.requireActual('twenty-ui/components'),
+ useToast: () => ({ enqueueToast }),
+}));
+
+const workspace = (origins: string[]) => ({
+ __typename: 'Workspace' as const,
+ id: 'workspace-id',
+ allowedIframeOrigins: origins,
+});
+
+const renderSettings = (
+ origins: string[] = [],
+ mutations: MockedResponse[] = [],
+) =>
+ render(
+ <Provider store={createStore()}>
+ <MockedProvider
+ mocks={[
+ {
+ request: { query: GetWorkspaceIframeOriginsDocument },
+ result: { data: { currentWorkspace: workspace(origins) } },
+ },
+ ...mutations,
+ ]}
+ >
+ <I18nProvider i18n={i18n}>
+ <SettingsSecurityIframeOrigins />
+ </I18nProvider>
+ </MockedProvider>
+ </Provider>,
+ );
+
+const editableInput = async () => {
+ const input = screen.getByRole('textbox', { name: 'Allowed origin' });
+ await waitFor(() => expect(input).toBeEnabled());
+ return input;
+};
+
+beforeEach(() => jest.clearAllMocks());
+
+it.each(['button', 'Enter'])(
+ 'adds normalized origins with %s and removes the last origin',
+ async (method) => {
+ const added = jest.fn(() => ({
+ data: {
+ updateWorkspaceAllowedIframeOrigins: workspace([
+ 'https://portal.example.com',
+ ]),
+ },
+ }));
+ const removed = jest.fn(() => ({
+ data: { updateWorkspaceAllowedIframeOrigins: workspace([]) },
+ }));
+ renderSettings(
+ [],
+ [
+ {
+ request: {
+ query: UpdateWorkspaceAllowedIframeOriginsDocument,
+ variables: {
+ input: { operation: 'add', origin: 'https://portal.example.com' },
+ },
+ },
+ result: added,
+ },
+ {
+ request: {
+ query: UpdateWorkspaceAllowedIframeOriginsDocument,
+ variables: {
+ input: {
+ operation: 'remove',
+ origin: 'https://portal.example.com',
+ },
+ },
+ },
+ result: removed,
+ },
+ ],
+ );
+ const user = userEvent.setup();
+ await user.type(await editableInput(), 'https://PORTAL.example.com:443/');
+ if (method === 'Enter') await user.keyboard('{Enter}');
+ else await user.click(screen.getByRole('button', { name: 'Add origin' }));
+ await user.click(
+ await screen.findByRole('button', {
+ name: 'Remove https://portal.example.com',
+ }),
+ );
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: /Remove/ }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(added).toHaveBeenCalledTimes(1);
+ expect(removed).toHaveBeenCalledTimes(1);
+ },
+);
+
+it('explains invalid origins without sending a mutation', async () => {
+ renderSettings();
+ const user = userEvent.setup();
+ await user.type(await editableInput(), 'https://portal.example.com/path');
+ await user.click(screen.getByRole('button', { name: 'Add origin' }));
+ expect(
+ await screen.findByText(/without a path or wildcard/),
+ ).toBeInTheDocument();
+ expect(enqueueToast).not.toHaveBeenCalled();
+});
+
+it('keeps saved origins when the server rejects an update', async () => {
+ renderSettings(
+ ['https://portal.example.com'],
+ [
+ {
+ request: {
+ query: UpdateWorkspaceAllowedIframeOriginsDocument,
+ variables: {
+ input: {
+ operation: 'remove',
+ origin: 'https://portal.example.com',
+ },
+ },
+ },
+ error: new Error('Permission denied'),
+ },
+ ],
+ );
+ const user = userEvent.setup();
+ await user.click(
+ await screen.findByRole('button', {
+ name: 'Remove https://portal.example.com',
+ }),
+ );
+ await waitFor(() => expect(enqueueToast).toHaveBeenCalled());
+ expect(
+ screen.getByRole('button', { name: 'Remove https://portal.example.com' }),
+ ).toBeInTheDocument();
+});
+
+it('allows an addition when another administrator frees a slot in a full list', async () => {
+ const staleOrigins = Array.from(
+ { length: MAX_ALLOWED_IFRAME_ORIGINS },
+ (_, index) => `https://portal${index}.example.com`,
+ );
+ const newOrigin = 'https://new.example.com';
+ const updatedOrigins = [...staleOrigins.slice(1), newOrigin];
+ const saved = jest.fn(() => ({
+ data: { updateWorkspaceAllowedIframeOrigins: workspace(updatedOrigins) },
+ }));
+ renderSettings(staleOrigins, [
+ {
+ request: {
+ query: UpdateWorkspaceAllowedIframeOriginsDocument,
+ variables: { input: { operation: 'add', origin: newOrigin } },
+ },
+ result: saved,
+ },
+ ]);
+ const user = userEvent.setup();
+ await user.type(await editableInput(), newOrigin);
+ await user.click(screen.getByRole('button', { name: 'Add origin' }));
+ expect(
+ await screen.findByRole('button', { name: `Remove ${newOrigin}` }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: `Remove ${staleOrigins[0]}` }),
+ ).not.toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: /^Remove / })).toHaveLength(
+ MAX_ALLOWED_IFRAME_ORIGINS,
+ );
+ expect(saved).toHaveBeenCalledTimes(1);
+});
+
+it('keeps the saved list and input when the server rejects an addition at the limit', async () => {
+ const origins = Array.from(
+ { length: MAX_ALLOWED_IFRAME_ORIGINS },
+ (_, index) => `https://portal${index}.example.com`,
+ );
+ const newOrigin = 'https://new.example.com';
+ renderSettings(origins, [
+ {
+ request: {
+ query: UpdateWorkspaceAllowedIframeOriginsDocument,
+ variables: { input: { operation: 'add', origin: newOrigin } },
+ },
+ error: new Error(
+ `You can allow up to ${MAX_ALLOWED_IFRAME_ORIGINS} origins.`,
+ ),
+ },
+ ]);
+ const user = userEvent.setup();
+ const input = await editableInput();
+ await user.type(input, newOrigin);
+ await user.click(screen.getByRole('button', { name: 'Add origin' }));
+ await waitFor(() => expect(enqueueToast).toHaveBeenCalled());
+ expect(input).toHaveValue(newOrigin);
+ expect(input).toBeEnabled();
+ expect(screen.getAllByRole('button', { name: /^Remove / })).toHaveLength(
+ MAX_ALLOWED_IFRAME_ORIGINS,
+ );
+ expect(
+ screen.queryByRole('button', { name: `Remove ${newOrigin}` }),
+ ).not.toBeInTheDocument();
+});
+
+it('disables edits while the saved policy is unknown', () => {
+ renderSettings();
+ expect(
+ screen.getByRole('textbox', { name: 'Allowed origin' }),
+ ).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Add origin' })).toBeDisabled();
+});
diff --git a/packages/twenty-front/src/modules/workspace/graphql/mutations/updateWorkspaceAllowedIframeOrigins.ts b/packages/twenty-front/src/modules/workspace/graphql/mutations/updateWorkspaceAllowedIframeOrigins.ts
new file mode 100644
index 00000000000..fce2d81a551
--- /dev/null
+++ b/packages/twenty-front/src/modules/workspace/graphql/mutations/updateWorkspaceAllowedIframeOrigins.ts
@@ -0,0 +1,12 @@
+import { gql } from '@apollo/client';
+
+export const UPDATE_WORKSPACE_ALLOWED_IFRAME_ORIGINS = gql`
+ mutation UpdateWorkspaceAllowedIframeOrigins(
+ $input: UpdateWorkspaceAllowedIframeOriginsInput!
+ ) {
+ updateWorkspaceAllowedIframeOrigins(data: $input) {
+ id
+ allowedIframeOrigins
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/workspace/graphql/queries/getWorkspaceIframeOrigins.ts b/packages/twenty-front/src/modules/workspace/graphql/queries/getWorkspaceIframeOrigins.ts
new file mode 100644
index 00000000000..8a8027122fd
--- /dev/null
+++ b/packages/twenty-front/src/modules/workspace/graphql/queries/getWorkspaceIframeOrigins.ts
@@ -0,0 +1,10 @@
+import { gql } from '@apollo/client';
+
+export const GET_WORKSPACE_IFRAME_ORIGINS = gql`
+ query GetWorkspaceIframeOrigins {
+ currentWorkspace {
+ id
+ allowedIframeOrigins
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/pages/not-found/__stories__/NotFound.stories.tsx b/packages/twenty-front/src/pages/not-found/__stories__/NotFound.stories.tsx
index 36281ed0771..27a5f487a02 100644
--- a/packages/twenty-front/src/pages/not-found/__stories__/NotFound.stories.tsx
+++ b/packages/twenty-front/src/pages/not-found/__stories__/NotFound.stories.tsx
@@ -28,5 +28,6 @@ export const Default: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByText('Off the beaten path');
+ await canvas.findByRole('button', { name: 'New Company' });
},
};
diff --git a/packages/twenty-server/package.json b/packages/twenty-server/package.json
index e54c0d8c435..2bf85fa814e 100644
--- a/packages/twenty-server/package.json
+++ b/packages/twenty-server/package.json
@@ -63,7 +63,6 @@
"@nestjs/passport": "11.0.5",
"@nestjs/platform-express": "11.2.1",
"@nestjs/schedule": "^6.0.1",
- "@nestjs/serve-static": "5.0.5",
"@nestjs/terminus": "11.0.0",
"@nestjs/typeorm": "11.0.0",
"@node-saml/node-saml": "5.1.0",
diff --git a/packages/twenty-server/src/app.module.ts b/packages/twenty-server/src/app.module.ts
index 8357359e446..f4d340e919b 100644
--- a/packages/twenty-server/src/app.module.ts
+++ b/packages/twenty-server/src/app.module.ts
@@ -1,15 +1,6 @@
-import {
- type DynamicModule,
- type MiddlewareConsumer,
- Module,
- RequestMethod,
-} from '@nestjs/common';
+import { type MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { APP_FILTER, APP_GUARD } 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';
@@ -24,6 +15,7 @@ import { McpMethodGuardMiddleware } from 'src/engine/api/mcp/middlewares/mcp-met
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 { FrontendModule } from 'src/engine/core-modules/frontend/frontend.module';
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';
@@ -79,7 +71,7 @@ const MIGRATED_REST_METHODS = [
UserSessionModule,
WorkspaceMetadataVersionModule,
I18nModule,
- ...AppModule.getConditionalModules(),
+ FrontendModule,
],
providers: [
{
@@ -93,25 +85,6 @@ const MIGRATED_REST_METHODS = [
],
})
export class AppModule {
- private static getConditionalModules(): DynamicModule[] {
- const modules: DynamicModule[] = [];
- const frontPath = join(__dirname, 'front');
-
- 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
-
- return modules;
- }
-
configure(consumer: MiddlewareConsumer) {
const loggedApiPaths = Object.values(ApiPath).filter(
(apiPath) => apiPath !== ApiPath.Health,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-instance-command-fast-1790232481570-add-workspace-allowed-iframe-origins.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-instance-command-fast-1790232481570-add-workspace-allowed-iframe-origins.ts
new file mode 100644
index 00000000000..4e5ae44ea16
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-43/2-43-instance-command-fast-1790232481570-add-workspace-allowed-iframe-origins.ts
@@ -0,0 +1,15 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.43.0', 1790232481570)
+export class AddWorkspaceAllowedIframeOriginsFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."workspace" ADD "allowedIframeOrigins" character varying array NOT NULL DEFAULT \'{}\'');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."workspace" DROP COLUMN "allowedIframeOrigins"');
+ }
+}
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.ts
index cb48530651b..316ca4d01b7 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
@@ -206,6 +206,7 @@ import { AddViewGroupLoadLimitFastInstanceCommand } from 'src/database/commands/
import { AddSettingsMenuItemFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1790165860000-add-settings-menu-item';
import { BackfillSettingsMenuItemSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-slow-1790165870000-backfill-settings-menu-item';
import { AddChatMessageSenderFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-instance-command-fast-1790171503074-add-chat-message-sender';
+import { AddWorkspaceAllowedIframeOriginsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-instance-command-fast-1790232481570-add-workspace-allowed-iframe-origins';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -414,4 +415,5 @@ export const INSTANCE_COMMANDS = [
AddSettingsMenuItemFastInstanceCommand,
BackfillSettingsMenuItemSlowInstanceCommand,
AddChatMessageSenderFastInstanceCommand,
+ AddWorkspaceAllowedIframeOriginsFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/client-config/client-config.module.ts b/packages/twenty-server/src/engine/core-modules/client-config/client-config.module.ts
index 9c1ed19fe99..da1756327a5 100644
--- a/packages/twenty-server/src/engine/core-modules/client-config/client-config.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/client-config/client-config.module.ts
@@ -12,5 +12,6 @@ import { ClientConfigService } from './services/client-config.service';
imports: [DomainServerConfigModule, AdminPanelModule],
controllers: [ClientConfigController],
providers: [ClientConfigResolver, ClientConfigService],
+ exports: [ClientConfigService],
})
export class ClientConfigModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/domain/custom-domain-manager/services/custom-domain-manager.service.ts b/packages/twenty-server/src/engine/core-modules/domain/custom-domain-manager/services/custom-domain-manager.service.ts
index d9433a7d4d6..bfa319df9c4 100644
--- a/packages/twenty-server/src/engine/core-modules/domain/custom-domain-manager/services/custom-domain-manager.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/domain/custom-domain-manager/services/custom-domain-manager.service.ts
@@ -110,7 +110,9 @@ export class CustomDomainManagerService {
if (workspace.isCustomDomainEnabled !== isCustomDomainWorking) {
workspace.isCustomDomainEnabled = isCustomDomainWorking;
- await this.workspaceRepository.save(workspace);
+ await this.workspaceRepository.update(workspace.id, {
+ isCustomDomainEnabled: isCustomDomainWorking,
+ });
const eventLogContext = this.eventLogEmitterService.createContext({
workspaceId: workspace.id,
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts b/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts
new file mode 100644
index 00000000000..13e41209cb9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts
@@ -0,0 +1,332 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { Controller, Get, type INestApplication } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+import { HttpAdapterHost } from '@nestjs/core';
+
+import { FrontendModule } from 'src/engine/core-modules/frontend/frontend.module';
+import request from 'supertest';
+
+import { type ClientConfigService } from 'src/engine/core-modules/client-config/services/client-config.service';
+import { type WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { FrontendService } from 'src/engine/core-modules/frontend/frontend.service';
+import { WorkspaceNotFoundDefaultError } from 'src/engine/core-modules/workspace/workspace.exception';
+
+jest.mock(
+ 'src/engine/core-modules/client-config/services/client-config.service',
+ () => ({ ClientConfigService: class {} }),
+);
+jest.mock(
+ 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service',
+ () => ({ WorkspaceDomainsService: class {} }),
+);
+
+jest.mock('src/engine/core-modules/client-config/client-config.module', () => ({
+ ClientConfigModule: class {},
+}));
+jest.mock(
+ 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module',
+ () => ({ WorkspaceDomainsModule: class {} }),
+);
+
+@Controller('healthz')
+class HealthController {
+ // oxlint-disable-next-line twenty/rest-api-methods-should-be-guarded
+ @Get()
+ health() {
+ return { status: 'ok' };
+ }
+}
+
+describe('frontend HTML delivery', () => {
+ const config = {
+ isMultiWorkspaceEnabled: true,
+ frontDomain: 'twenty.test',
+ authProviders: { password: true },
+ };
+ const getClientConfig = jest.fn();
+ const resolveWorkspaceAndPublicDomain = jest.fn();
+ let directory: string;
+ let app: INestApplication;
+
+ beforeEach(async () => {
+ jest.useRealTimers();
+ getClientConfig.mockReset().mockResolvedValue(config);
+ resolveWorkspaceAndPublicDomain
+ .mockReset()
+ .mockImplementation(async (origin: string) => ({
+ workspace: {
+ allowedIframeOrigins:
+ origin === 'https://customer.twenty.test'
+ ? ['https://portal.customer.com']
+ : [],
+ },
+ isIsolatedOrigin: false,
+ }));
+ directory = mkdtempSync(join(tmpdir(), 'twenty-frontend-'));
+ writeFileSync(
+ join(directory, 'index.html'),
+ '<html><head><!-- BEGIN: Twenty Config --><script>window._env_={REACT_APP_SERVER_BASE_URL:"wrong"}</script><!-- END: Twenty Config --></head><body><div id="root"></div></body></html>',
+ );
+ const service = new FrontendService(
+ { getClientConfig } as unknown as ClientConfigService,
+ { resolveWorkspaceAndPublicDomain } as unknown as WorkspaceDomainsService,
+ directory,
+ );
+ const module = await Test.createTestingModule({
+ imports: [FrontendModule],
+ controllers: [HealthController],
+ })
+ .overrideProvider(FrontendService)
+ .useValue(service)
+ .compile();
+
+ app = module.createNestApplication();
+ app.getHttpAdapter().getInstance().set('trust proxy', 'loopback');
+ await app.init();
+ });
+
+ afterEach(async () => {
+ await app.close();
+ rmSync(directory, { recursive: true, force: true });
+ });
+
+ it('initializes CLI application contexts with bundled HTML and no HTTP adapter', async () => {
+ const module = await Test.createTestingModule({ imports: [FrontendModule] })
+ .overrideProvider(FrontendService)
+ .useValue(
+ new FrontendService(
+ { getClientConfig } as unknown as ClientConfigService,
+ {
+ resolveWorkspaceAndPublicDomain,
+ } as unknown as WorkspaceDomainsService,
+ directory,
+ ),
+ )
+ .compile();
+ expect(module.get(HttpAdapterHost).httpAdapter).toBeUndefined();
+ await expect(module.init()).resolves.toBeDefined();
+ await module.close();
+ });
+
+ it.each(['/', '/index.html', '/objects/people'])(
+ 'bootstraps configuration and applies the hostname policy on %s',
+ async (pathname) => {
+ const response = await request(app.getHttpServer())
+ .get(pathname)
+ .set('Accept', 'text/html')
+ .set('Host', 'customer.twenty.test')
+ .set('X-Forwarded-Proto', 'https')
+ .expect(200);
+ expect(response.headers['content-security-policy']).toContain(
+ "frame-ancestors 'self' https://portal.customer.com;",
+ );
+ expect(response.headers['x-frame-options']).toBeUndefined();
+ expect(response.headers['cache-control']).toBe('no-store');
+ expect(response.headers['cdn-cache-control']).toBe('no-store');
+ expect(response.text).toContain(
+ `type="application/json">${JSON.stringify(config)}</script>`,
+ );
+ expect(response.text).toContain('window._env_ = {};');
+ expect(response.text).not.toContain('wrong');
+ },
+ );
+
+ it('does not borrow a policy from another workspace or a supplied Origin header', async () => {
+ const response = await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .set('Host', 'other.twenty.test')
+ .set('Origin', 'https://customer.twenty.test')
+ .expect(200);
+ expect(response.headers['content-security-policy']).toBe(
+ "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
+ );
+ expect(response.headers['x-frame-options']).toBe('SAMEORIGIN');
+ });
+
+ it('reads fresh policy and configuration on subsequent documents, even with a conditional request', async () => {
+ const initial = await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .set('Host', 'customer.twenty.test')
+ .set('X-Forwarded-Proto', 'https');
+ expect(initial.headers['content-security-policy']).toContain(
+ 'https://portal.customer.com',
+ );
+ resolveWorkspaceAndPublicDomain.mockResolvedValue({
+ workspace: { allowedIframeOrigins: [] },
+ isIsolatedOrigin: false,
+ });
+ const response = await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .set('Host', 'customer.twenty.test')
+ .set('X-Forwarded-Proto', 'https')
+ .set('If-None-Match', '*')
+ .expect(200);
+ expect(response.headers['content-security-policy']).not.toContain(
+ 'portal.customer.com',
+ );
+ expect(getClientConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('escapes script terminators and preserves literal replacement tokens in configuration', async () => {
+ getClientConfig.mockResolvedValue({
+ ...config,
+ frontDomain: "</script><script>alert(1)</script>$&$'",
+ });
+ const response = await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(response.text).not.toContain('<script>alert(1)');
+ const serializedConfig = response.text.match(
+ /type="application\/json">(.*?)<\/script>/,
+ )?.[1];
+ expect(JSON.parse(serializedConfig!)).toEqual(await getClientConfig());
+ });
+
+ it('serves signup on an installation with no workspace', async () => {
+ resolveWorkspaceAndPublicDomain.mockRejectedValue(
+ WorkspaceNotFoundDefaultError,
+ );
+ await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .expect(200);
+ });
+
+ it('fails closed when policy resolution fails', async () => {
+ resolveWorkspaceAndPublicDomain.mockRejectedValue(
+ new Error('Database unavailable'),
+ );
+ const response = await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .expect(503);
+ expect(response.headers['content-security-policy']).toContain(
+ "frame-ancestors 'self'",
+ );
+ });
+
+ it('does not serve the CRM on a public application domain', async () => {
+ resolveWorkspaceAndPublicDomain.mockResolvedValue({
+ workspace: undefined,
+ isIsolatedOrigin: true,
+ });
+ await request(app.getHttpServer())
+ .get('/')
+ .set('Accept', 'text/html')
+ .expect(404);
+ });
+
+ it.each([
+ '/graphql/missing',
+ '/rest/missing',
+ '/auth/missing',
+ '/assets/missing.js',
+ '/.well-known/missing',
+ ])('does not turn %s into a successful HTML response', async (pathname) => {
+ await request(app.getHttpServer())
+ .get(pathname)
+ .set('Accept', 'text/html')
+ .expect(404);
+ expect(getClientConfig).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ '*/*',
+ 'application/json',
+ 'image/avif,image/webp,*/*',
+ 'text/html;q=0',
+ ])('does not serve a document for Accept: %s', async (accept) => {
+ await request(app.getHttpServer())
+ .get('/new-asset-directory/missing')
+ .set('Accept', accept)
+ .expect(404);
+ expect(getClientConfig).not.toHaveBeenCalled();
+ });
+
+ it.each(['script', 'style', 'image', 'font', 'empty'])(
+ 'does not serve a document for Sec-Fetch-Dest: %s',
+ async (destination) => {
+ await request(app.getHttpServer())
+ .get('/new-asset-directory/missing')
+ .set('Accept', 'text/html')
+ .set('Sec-Fetch-Dest', destination)
+ .expect(404);
+ expect(getClientConfig).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['document', 'iframe', 'frame'])(
+ 'serves HTML navigation with Sec-Fetch-Dest: %s',
+ async (destination) => {
+ await request(app.getHttpServer())
+ .get('/objects/people')
+ .set('Accept', 'text/html,application/xhtml+xml,*/*;q=0.8')
+ .set('Sec-Fetch-Dest', destination)
+ .expect(200);
+ expect(getClientConfig).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('serves extensionless static files in arbitrary directories before the SPA fallback', async () => {
+ mkdirSync(join(directory, 'new-asset-directory'));
+ writeFileSync(
+ join(directory, 'new-asset-directory', 'example'),
+ 'static content',
+ );
+ const response = await request(app.getHttpServer())
+ .get('/new-asset-directory/example')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(response.body.toString()).toBe('static content');
+ expect(getClientConfig).not.toHaveBeenCalled();
+ });
+
+ it('preserves API controller routing', async () => {
+ const response = await request(app.getHttpServer())
+ .get('/healthz')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(response.body).toEqual({ status: 'ok' });
+ expect(getClientConfig).not.toHaveBeenCalled();
+ });
+
+ it('serves static assets and blocks framing of alternate HTML paths', async () => {
+ writeFileSync(join(directory, 'example.js'), 'console.log(1);');
+ const asset = await request(app.getHttpServer())
+ .get('/example.js')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(asset.text).toBe('console.log(1);');
+ const html = await request(app.getHttpServer())
+ .get('/%69ndex.html')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(html.headers['content-security-policy']).toBe(
+ "frame-ancestors 'none'",
+ );
+ expect(html.headers['cache-control']).toBe('no-store');
+ expect(getClientConfig).not.toHaveBeenCalled();
+ });
+
+ it('does not serve HTML for POST requests', async () => {
+ await request(app.getHttpServer()).post('/objects/people').expect(404);
+ });
+
+ it('returns the policy for HEAD requests without a response body', async () => {
+ const response = await request(app.getHttpServer())
+ .head('/')
+ .set('Accept', 'text/html')
+ .expect(200);
+ expect(response.headers['content-security-policy']).toContain(
+ "frame-ancestors 'self'",
+ );
+ expect(response.text).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/frontend.module.ts b/packages/twenty-server/src/engine/core-modules/frontend/frontend.module.ts
new file mode 100644
index 00000000000..d0ed6f1245a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/frontend/frontend.module.ts
@@ -0,0 +1,64 @@
+import { Module, type OnModuleInit } from '@nestjs/common';
+import { HttpAdapterHost } from '@nestjs/core';
+
+import express, {
+ type Request,
+ type Response,
+ type NextFunction,
+} from 'express';
+import { join } from 'path';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ClientConfigModule } from 'src/engine/core-modules/client-config/client-config.module';
+import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
+import { FrontendService } from 'src/engine/core-modules/frontend/frontend.service';
+
+@Module({
+ imports: [ClientConfigModule, WorkspaceDomainsModule],
+ providers: [
+ FrontendService,
+ { provide: 'FRONTEND_PATH', useValue: join(__dirname, '../../../front') },
+ ],
+})
+export class FrontendModule implements OnModuleInit {
+ constructor(
+ private readonly httpAdapterHost: HttpAdapterHost,
+ private readonly frontendService: FrontendService,
+ ) {}
+
+ onModuleInit() {
+ const adapter = this.httpAdapterHost.httpAdapter;
+
+ if (!this.frontendService.isEnabled || !isDefined(adapter)) {
+ return;
+ }
+
+ const serveStatic = express.static(this.frontendService.frontPath, {
+ index: false,
+ redirect: false,
+ setHeaders: (response, filePath) => {
+ if (filePath.toLowerCase().endsWith('.html')) {
+ response.setHeader('Cache-Control', 'no-store');
+ response.setHeader('CDN-Cache-Control', 'no-store');
+ response.setHeader('Cloudflare-CDN-Cache-Control', 'no-store');
+ response.setHeader(
+ 'Content-Security-Policy',
+ "frame-ancestors 'none'",
+ );
+ response.setHeader('X-Frame-Options', 'DENY');
+ }
+ },
+ });
+
+ adapter.use((request: Request, response: Response, next: NextFunction) => {
+ if (request.path === '/index.html') {
+ next();
+
+ return;
+ }
+
+ serveStatic(request, response, next);
+ });
+ adapter.use(this.frontendService.serveDocument.bind(this.frontendService));
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts b/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts
new file mode 100644
index 00000000000..3d9f1fd23a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/frontend/frontend.service.ts
@@ -0,0 +1,107 @@
+import { Inject, Injectable, Logger } from '@nestjs/common';
+
+import { existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+
+import { type NextFunction, type Request, type Response } from 'express';
+import { isDefined, normalizeAllowedIframeOrigin } from 'twenty-shared/utils';
+
+import { ClientConfigService } from 'src/engine/core-modules/client-config/services/client-config.service';
+import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { isFrontendDocumentRequest } from 'src/engine/core-modules/frontend/utils/is-frontend-document-request.util';
+import { renderFrontendHtml } from 'src/engine/core-modules/frontend/utils/render-frontend-html.util';
+import { WorkspaceNotFoundDefaultError } from 'src/engine/core-modules/workspace/workspace.exception';
+import { getRequestBaseUrl } from 'src/utils/get-request-base-url.util';
+
+@Injectable()
+export class FrontendService {
+ private readonly logger = new Logger(FrontendService.name);
+ private readonly template: string | undefined;
+
+ constructor(
+ private readonly clientConfigService: ClientConfigService,
+ private readonly workspaceDomainsService: WorkspaceDomainsService,
+ @Inject('FRONTEND_PATH') readonly frontPath: string,
+ ) {
+ const indexPath = join(this.frontPath, 'index.html');
+
+ if (existsSync(indexPath)) {
+ this.template = readFileSync(indexPath, 'utf8');
+
+ if (!this.template.includes('</head>')) {
+ throw new Error('Frontend index.html must contain a closing head tag');
+ }
+ }
+ }
+
+ get isEnabled(): boolean {
+ return isDefined(this.template);
+ }
+
+ async serveDocument(
+ request: Request,
+ response: Response,
+ next: NextFunction,
+ ): Promise<void> {
+ if (!isDefined(this.template) || !isFrontendDocumentRequest(request)) {
+ next();
+
+ return;
+ }
+
+ response.setHeader('Cache-Control', 'no-store');
+ response.setHeader('CDN-Cache-Control', 'no-store');
+ response.setHeader('Cloudflare-CDN-Cache-Control', 'no-store');
+ response.setHeader('X-Content-Type-Options', 'nosniff');
+ response.setHeader('X-Frame-Options', 'SAMEORIGIN');
+ response.setHeader(
+ 'Content-Security-Policy',
+ "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
+ );
+
+ try {
+ const [clientConfig, { workspace, isIsolatedOrigin }] = await Promise.all(
+ [
+ this.clientConfigService.getClientConfig(),
+ this.workspaceDomainsService
+ .resolveWorkspaceAndPublicDomain(getRequestBaseUrl(request))
+ .catch((error: unknown) => {
+ if (error === WorkspaceNotFoundDefaultError) {
+ return { workspace: undefined, isIsolatedOrigin: false };
+ }
+
+ throw error;
+ }),
+ ],
+ );
+
+ if (isIsolatedOrigin) {
+ response.status(404).end();
+
+ return;
+ }
+
+ const allowedOrigins = (workspace?.allowedIframeOrigins ?? [])
+ .map(normalizeAllowedIframeOrigin)
+ .filter(isDefined);
+
+ if (allowedOrigins.length > 0) {
+ response.setHeader(
+ 'Content-Security-Policy',
+ `frame-ancestors 'self' ${[...new Set(allowedOrigins)].join(' ')}; object-src 'none'; base-uri 'self'`,
+ );
+ response.removeHeader('X-Frame-Options');
+ }
+
+ response
+ .type('html')
+ .end(renderFrontendHtml(this.template, clientConfig));
+ } catch (error) {
+ this.logger.error('Unable to serve frontend document', error);
+ response
+ .status(503)
+ .type('text')
+ .send('Unable to load Twenty. Please try again.');
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/utils/is-frontend-document-request.util.ts b/packages/twenty-server/src/engine/core-modules/frontend/utils/is-frontend-document-request.util.ts
new file mode 100644
index 00000000000..6e8fb89ad5c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/frontend/utils/is-frontend-document-request.util.ts
@@ -0,0 +1,26 @@
+import { extname } from 'path';
+
+import { type Request } from 'express';
+import { isDefined } from 'twenty-shared/utils';
+import { ApiPath } from 'twenty-shared/types';
+
+export const isFrontendDocumentRequest = (request: Request): boolean => {
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
+ return false;
+ }
+
+ const pathname = request.path;
+ const isApiPath = Object.values(ApiPath).some(
+ (prefix) => pathname === `/${prefix}` || pathname.startsWith(`/${prefix}/`),
+ );
+
+ const destination = request.get('Sec-Fetch-Dest');
+
+ return (
+ !isApiPath &&
+ (pathname === '/index.html' || extname(pathname) === '') &&
+ request.accepts().includes('text/html') &&
+ (!isDefined(destination) ||
+ ['document', 'iframe', 'frame'].includes(destination))
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/utils/render-frontend-html.util.ts b/packages/twenty-server/src/engine/core-modules/frontend/utils/render-frontend-html.util.ts
new file mode 100644
index 00000000000..45065b32041
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/frontend/utils/render-frontend-html.util.ts
@@ -0,0 +1,26 @@
+import { CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID } from 'twenty-shared/constants';
+
+import { type ClientConfig } from 'src/engine/core-modules/client-config/client-config.entity';
+
+export const renderFrontendHtml = (
+ template: string,
+ clientConfig: ClientConfig,
+): string => {
+ const serializedConfig = JSON.stringify(clientConfig)
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/&/g, '\\u0026')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029');
+
+ return template
+ .replace(
+ /<!-- BEGIN: Twenty Config -->[\s\S]*?<!-- END: Twenty Config -->/,
+ '<script id="twenty-env-config">window._env_ = {};</script>',
+ )
+ .replace(
+ '</head>',
+ () =>
+ `<script id="${CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID}" type="application/json">${serializedConfig}</script></head>`,
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/dtos/__tests__/update-workspace-allowed-iframe-origins.input.spec.ts b/packages/twenty-server/src/engine/core-modules/workspace/dtos/__tests__/update-workspace-allowed-iframe-origins.input.spec.ts
new file mode 100644
index 00000000000..eceab399b9b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workspace/dtos/__tests__/update-workspace-allowed-iframe-origins.input.spec.ts
@@ -0,0 +1,44 @@
+import { validate } from 'class-validator';
+import { UpdateWorkspaceAllowedIframeOriginsInput } from 'src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input';
+
+describe('workspace embedding origin edits', () => {
+ it.each([
+ 'https://portal.example.com',
+ 'http://portal.corp.lan',
+ 'https://PORTAL.example.com:443/',
+ ])('accepts an explicit origin: %s', async (origin) => {
+ const input = Object.assign(
+ new UpdateWorkspaceAllowedIframeOriginsInput(),
+ { operation: 'add', origin },
+ );
+ expect(await validate(input)).toEqual([]);
+ });
+ it.each([
+ '*',
+ 'https://*.example.com',
+ 'https://example.com/path',
+ 'https://user:[email protected]',
+ 'javascript:alert(1)',
+ null,
+ undefined,
+ ])('rejects an invalid origin: %s', async (origin) => {
+ const input = Object.assign(
+ new UpdateWorkspaceAllowedIframeOriginsInput(),
+ { operation: 'add', origin },
+ );
+ expect(await validate(input)).toEqual(
+ expect.arrayContaining([expect.objectContaining({ property: 'origin' })]),
+ );
+ });
+ it('rejects replacing the whole list', async () => {
+ const input = Object.assign(
+ new UpdateWorkspaceAllowedIframeOriginsInput(),
+ { operation: 'replace', origin: 'https://portal.example.com' },
+ );
+ expect(await validate(input)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ property: 'operation' }),
+ ]),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input.ts b/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input.ts
new file mode 100644
index 00000000000..303295aff9f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input.ts
@@ -0,0 +1,23 @@
+import { Field, InputType } from '@nestjs/graphql';
+import { isString } from '@sniptt/guards';
+import { IsIn, ValidateBy } from 'class-validator';
+import { isDefined, normalizeAllowedIframeOrigin } from 'twenty-shared/utils';
+
+@InputType()
+export class UpdateWorkspaceAllowedIframeOriginsInput {
+ @Field(() => String)
+ @IsIn(['add', 'remove'])
+ operation: 'add' | 'remove';
+
+ @Field()
+ @ValidateBy({
+ name: 'allowedIframeOrigin',
+ validator: {
+ validate: (value: unknown) =>
+ isString(value) && isDefined(normalizeAllowedIframeOrigin(value)),
+ defaultMessage: () =>
+ 'Enter an HTTP or HTTPS origin without a path or wildcard',
+ },
+ })
+ origin: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
index 548b6bbacdc..f4121d64aca 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
@@ -8,11 +8,15 @@ import { isNonEmptyString } from '@sniptt/guards';
import { msg } from '@lingui/core/macro';
import { isAiModelTier, type AiModelTier } from 'twenty-shared/ai';
-import { PermissionFlagType } from 'twenty-shared/constants';
+import {
+ MAX_ALLOWED_IFRAME_ORIGINS,
+ PermissionFlagType,
+} from 'twenty-shared/constants';
import {
assertIsDefinedOrThrow,
isAutoSelectModelId,
isDefined,
+ normalizeAllowedIframeOrigin,
} from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
import {
@@ -61,6 +65,8 @@ import { UpgradeSequenceReaderService } from 'src/engine/core-modules/upgrade/se
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
+import { type UpdateWorkspaceInput } from 'src/engine/core-modules/workspace/dtos/update-workspace-input';
+import { type UpdateWorkspaceAllowedIframeOriginsInput } from 'src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input';
import { WORKSPACE_FIELDS_UPDATABLE_BEFORE_ACTIVATION } from 'src/engine/core-modules/workspace/constants/workspace-fields-updatable-before-activation.constant';
import {
WorkspaceDeletionApplicationUninstallJob,
@@ -280,13 +286,52 @@ export class WorkspaceService {
}
}
+ async updateWorkspaceAllowedIframeOrigins(
+ workspaceId: string,
+ input: UpdateWorkspaceAllowedIframeOriginsInput,
+ ): Promise<WorkspaceEntity> {
+ const updatedWorkspace = await this.workspaceRepository.manager.transaction(
+ async (manager) => {
+ const repository = manager.getRepository(WorkspaceEntity);
+ const workspace = await repository.findOne({
+ where: { id: workspaceId },
+ lock: { mode: 'pessimistic_write' },
+ });
+ assertIsDefinedOrThrow(workspace, WorkspaceNotFoundDefaultError);
+ const origin = normalizeAllowedIframeOrigin(input.origin);
+ assertIsDefinedOrThrow(origin);
+ const origins = workspace.allowedIframeOrigins ?? [];
+ const allowedIframeOrigins =
+ input.operation === 'add'
+ ? [...new Set([...origins, origin])]
+ : origins.filter((existingOrigin) => existingOrigin !== origin);
+
+ if (allowedIframeOrigins.length > MAX_ALLOWED_IFRAME_ORIGINS) {
+ throw new WorkspaceException(
+ 'Too many embedding origins',
+ WorkspaceExceptionCode.IFRAME_ORIGIN_LIMIT_EXCEEDED,
+ );
+ }
+
+ await repository.update(workspaceId, { allowedIframeOrigins });
+ return { ...workspace, allowedIframeOrigins };
+ },
+ );
+
+ await this.coreEntityCacheService.invalidate(
+ 'workspaceEntity',
+ workspaceId,
+ );
+ return updatedWorkspace;
+ }
+
async updateWorkspaceById({
payload,
userWorkspaceId,
apiKey,
application,
}: {
- payload: Partial<WorkspaceEntity> & { id: string };
+ payload: UpdateWorkspaceInput & { id: string };
userWorkspaceId?: string;
apiKey: ApiKeyEntity | undefined;
application?: FlatApplication;
@@ -401,11 +446,16 @@ export class WorkspaceService {
let updatedWorkspace: WorkspaceEntity;
try {
- updatedWorkspace = await this.workspaceRepository.save({
- ...workspace,
+ await this.workspaceRepository.update(workspace.id, {
...payload,
+ ...(payload.customDomain === null
+ ? { isCustomDomainEnabled: false }
+ : {}),
...(payload.logo === null ? { logoFileId: null } : {}),
});
+ updatedWorkspace = await this.workspaceRepository.findOneByOrFail({
+ id: workspace.id,
+ });
} catch (error) {
if (payload.customDomain && customDomainRegistered) {
this.dnsManagerService
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util.ts b/packages/twenty-server/src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util.ts
index d1d2f8d685a..b473ea3de51 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util.ts
@@ -27,6 +27,7 @@ export const fromWorkspaceEntityToFlat = (
isMicrosoftAuthEnabled: entity.isMicrosoftAuthEnabled,
isMicrosoftAuthBypassEnabled: entity.isMicrosoftAuthBypassEnabled,
isCustomDomainEnabled: entity.isCustomDomainEnabled,
+ allowedIframeOrigins: entity.allowedIframeOrigins,
editableProfileFields: entity.editableProfileFields,
defaultRoleId: entity.defaultRoleId,
aiChatModelTier: entity.aiChatModelTier,
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/utils/workspace-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/workspace/utils/workspace-graphql-api-exception-handler.util.ts
index 976c9242197..a992b659793 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/utils/workspace-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/utils/workspace-graphql-api-exception-handler.util.ts
@@ -26,6 +26,7 @@ export const workspaceGraphqlApiExceptionHandler = (error: Error) => {
case WorkspaceExceptionCode.ENVIRONMENT_VAR_NOT_ENABLED:
case WorkspaceExceptionCode.WORKSPACE_CUSTOM_DOMAIN_DISABLED:
throw new ForbiddenError(error);
+ case WorkspaceExceptionCode.IFRAME_ORIGIN_LIMIT_EXCEEDED:
case WorkspaceExceptionCode.AI_MODEL_PIN_NOT_VALID:
throw new UserInputError(error);
default: {
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
index 5bc9579c907..e7e7e2c9a10 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
@@ -300,6 +300,14 @@ export class WorkspaceEntity {
@Column({ default: false })
isInternalMessagesImportEnabled: boolean;
+ @Field(() => [String], { nullable: true })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.43.0_AddWorkspaceAllowedIframeOriginsFastInstanceCommand_1790232481570',
+ })
+ @Column({ type: 'varchar', array: true, default: '{}' })
+ allowedIframeOrigins: string[];
+
@Field(() => [String], { nullable: true })
@Column({
type: 'varchar',
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.exception.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.exception.ts
index 44e61438e14..508b194c95e 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.exception.ts
@@ -1,10 +1,12 @@
import { type MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
+import { MAX_ALLOWED_IFRAME_ORIGINS } from 'twenty-shared/constants';
import { assertUnreachable } from 'twenty-shared/utils';
import { CustomException } from 'src/utils/custom-exception';
export enum WorkspaceExceptionCode {
+ IFRAME_ORIGIN_LIMIT_EXCEEDED = 'IFRAME_ORIGIN_LIMIT_EXCEEDED',
SUBDOMAIN_NOT_FOUND = 'SUBDOMAIN_NOT_FOUND',
SUBDOMAIN_ALREADY_TAKEN = 'SUBDOMAIN_ALREADY_TAKEN',
SUBDOMAIN_NOT_VALID = 'SUBDOMAIN_NOT_VALID',
@@ -21,6 +23,8 @@ const getWorkspaceExceptionUserFriendlyMessage = (
code: WorkspaceExceptionCode,
) => {
switch (code) {
+ case WorkspaceExceptionCode.IFRAME_ORIGIN_LIMIT_EXCEEDED:
+ return msg`You can allow up to ${MAX_ALLOWED_IFRAME_ORIGINS} origins.`;
case WorkspaceExceptionCode.SUBDOMAIN_NOT_FOUND:
return msg`Subdomain not found.`;
case WorkspaceExceptionCode.SUBDOMAIN_ALREADY_TAKEN:
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
index e264781e7c5..5e99cccb00c 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
@@ -44,6 +44,7 @@ import {
PublicWorkspaceDataDTO,
PublicWorkspaceDataSummaryDTO,
} from 'src/engine/core-modules/workspace/dtos/public-workspace-data.dto';
+import { UpdateWorkspaceAllowedIframeOriginsInput } from 'src/engine/core-modules/workspace/dtos/update-workspace-allowed-iframe-origins.input';
import { UpdateWorkspaceInput } from 'src/engine/core-modules/workspace/dtos/update-workspace-input';
import { WorkspaceUrlsDTO } from 'src/engine/core-modules/workspace/dtos/workspace-urls.dto';
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';
@@ -160,6 +161,25 @@ export class WorkspaceResolver {
}
}
+ @Mutation(() => WorkspaceEntity)
+ @UseGuards(
+ WorkspaceAuthGuard,
+ SettingsPermissionGuard(PermissionFlagType.SECURITY),
+ )
+ async updateWorkspaceAllowedIframeOrigins(
+ @Args('data') data: UpdateWorkspaceAllowedIframeOriginsInput,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ) {
+ try {
+ return await this.workspaceService.updateWorkspaceAllowedIframeOrigins(
+ workspace.id,
+ data,
+ );
+ } catch (error) {
+ workspaceGraphqlApiExceptionHandler(error);
+ }
+ }
+
@ResolveField(() => [FeatureFlagDTO], { nullable: true })
async featureFlags(
@Parent() workspace: WorkspaceEntity,
diff --git a/packages/twenty-server/src/main.ts b/packages/twenty-server/src/main.ts
index 270b92b1839..039b5424b73 100644
--- a/packages/twenty-server/src/main.ts
+++ b/packages/twenty-server/src/main.ts
@@ -27,7 +27,6 @@ import './instrument';
import { settings } from './engine/constants/settings';
import { enableValidationMetadataCache } from './utils/enable-validation-metadata-cache.util';
-import { generateFrontConfig } from './utils/generate-front-config';
const bootstrap = async () => {
enableValidationMetadataCache();
@@ -102,8 +101,6 @@ const bootstrap = async () => {
}),
);
- generateFrontConfig();
-
const keepAliveTimeout = twentyConfigService.get(
'SERVER_KEEP_ALIVE_TIMEOUT_MS',
);
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.ts
deleted file mode 100644
index d28665c1c64..00000000000
--- a/packages/twenty-server/src/utils/__test__/generate-front-config.spec.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import * as fs from 'fs';
-
-import { generateFrontConfig } from 'src/utils/generate-front-config';
-
-// dotenv runs at import time with override: true, which would clobber the
-// per-test process.env we set below. Neutralize it so each test controls env.
-jest.mock('dotenv', () => ({ config: jest.fn() }));
-jest.mock('fs');
-
-const mockedFs = fs as jest.Mocked<typeof fs>;
-
-const INDEX_TEMPLATE = `<html>
- <head>
- <!-- BEGIN: Twenty Config -->
- <script id="twenty-env-config">
- window._env_ = {"REACT_APP_SERVER_BASE_URL":"http://stale-value"};
- </script>
- <!-- END: Twenty Config -->
- </head>
-</html>`;
-
-// Pull the injected _env_ object back out of the written index.html and
-// 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]*?\});/);
-
- return match ? match[1].replace(/\s+/g, '') : '';
-};
-
-describe('generateFrontConfig', () => {
- const ORIGINAL_ENV = process.env;
-
- beforeEach(() => {
- jest.clearAllMocks();
- process.env = { ...ORIGINAL_ENV };
- mockedFs.readFileSync.mockReturnValue(INDEX_TEMPLATE);
- });
-
- afterAll(() => {
- process.env = ORIGINAL_ENV;
- });
-
- it('should clear any baked value so the front resolves the API origin from the page origin', () => {
- process.env.SERVER_URL = 'http://x.com';
-
- generateFrontConfig();
-
- expect(getInjectedEnv()).toBe('{}');
- });
-});
diff --git a/packages/twenty-server/src/utils/generate-front-config.ts b/packages/twenty-server/src/utils/generate-front-config.ts
deleted file mode 100644
index 03413d3047c..00000000000
--- a/packages/twenty-server/src/utils/generate-front-config.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import * as fs from 'fs';
-import * as path from 'path';
-
-import { config } from 'dotenv';
-config({
- path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env',
- override: true,
-});
-
-export function generateFrontConfig(): void {
- // 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_ = {};
- </script>
- <!-- END: Twenty Config -->`;
-
- const distPath = path.join(__dirname, '..', 'front');
- const indexPath = path.join(distPath, 'index.html');
-
- try {
- let indexContent = fs.readFileSync(indexPath, 'utf8');
-
- indexContent = indexContent.replace(
- /<!-- BEGIN: Twenty Config -->[\s\S]*?<!-- END: Twenty Config -->/,
- configString,
- );
-
- fs.writeFileSync(indexPath, indexContent, 'utf8');
- } catch {
- // oxlint-disable-next-line no-console
- console.log(
- 'Frontend build not found or not writable, assuming it is served independently',
- );
- }
-}
diff --git a/packages/twenty-server/test/integration/graphql/suites/settings-permissions/security.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/settings-permissions/security.integration-spec.ts
index 0bbabb9da81..deaf9c4a6dd 100644
--- a/packages/twenty-server/test/integration/graphql/suites/settings-permissions/security.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/settings-permissions/security.integration-spec.ts
@@ -1,5 +1,6 @@
import { gql } from 'graphql-tag';
import request from 'supertest';
+import { MAX_ALLOWED_IFRAME_ORIGINS } from 'twenty-shared/constants';
import { makeMetadataAPIRequestWithFileUpload } from 'test/integration/metadata/suites/utils/make-metadata-api-request-with-file-upload.util';
import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
@@ -17,6 +18,35 @@ const uploadWorkspaceLogoMutation = gql`
const client = request(`http://localhost:${APP_PORT}`);
+const embeddingMutation = `
+ mutation UpdateEmbeddingOrigins($data: UpdateWorkspaceAllowedIframeOriginsInput!) {
+ updateWorkspaceAllowedIframeOrigins(data: $data) { id allowedIframeOrigins }
+ }
+`;
+
+const editOrigin = (
+ operation: 'add' | 'remove',
+ origin: string,
+ token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+) =>
+ client
+ .post('/metadata')
+ .set('Authorization', `Bearer ${token}`)
+ .send({
+ query: embeddingMutation,
+ variables: { data: { operation, origin } },
+ });
+
+const readOrigins = async () => {
+ const response = await client
+ .post('/metadata')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .send({ query: '{ currentWorkspace { allowedIframeOrigins } }' })
+ .expect(200);
+ expect(response.body.errors).toBeUndefined();
+ return response.body.data.currentWorkspace.allowedIframeOrigins as string[];
+};
+
describe('Security permissions', () => {
let originalWorkspaceState: Record<string, unknown>;
@@ -32,6 +62,7 @@ describe('Security permissions', () => {
isPublicInviteLinkEnabled
subdomain
isCustomDomainEnabled
+ allowedIframeOrigins
}
}
`;
@@ -59,9 +90,107 @@ describe('Security permissions', () => {
`;
await makeMetadataAPIRequest({ query: restoreQuery });
+ for (const origin of await readOrigins())
+ await editOrigin('remove', origin);
+ for (const origin of (originalWorkspaceState.allowedIframeOrigins ??
+ []) as string[])
+ await editOrigin('add', origin);
});
describe('security permissions', () => {
+ describe('iframe embedding', () => {
+ beforeEach(async () => {
+ for (const origin of await readOrigins())
+ await editOrigin('remove', origin);
+ });
+
+ it('normalizes origins, avoids duplicates and refreshes the cached workspace after revocation', async () => {
+ await editOrigin('add', 'https://PORTAL.example.com:443/').expect(200);
+ const duplicate = await editOrigin(
+ 'add',
+ 'https://portal.example.com',
+ ).expect(200);
+ expect(duplicate.body.errors).toBeUndefined();
+ expect(
+ duplicate.body.data.updateWorkspaceAllowedIframeOrigins
+ .allowedIframeOrigins,
+ ).toEqual(['https://portal.example.com']);
+ const readCached = () =>
+ client
+ .post('/metadata')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .send({
+ query:
+ '{ currentUser { currentWorkspace { allowedIframeOrigins } } }',
+ });
+ const before = await readCached().expect(200);
+ expect(
+ before.body.data.currentUser.currentWorkspace.allowedIframeOrigins,
+ ).toEqual(['https://portal.example.com']);
+ await editOrigin('remove', 'https://portal.example.com').expect(200);
+ const after = await readCached().expect(200);
+ expect(
+ after.body.data.currentUser.currentWorkspace.allowedIframeOrigins,
+ ).toEqual([]);
+ });
+
+ it('does not restore an origin revoked by another administrator', async () => {
+ await editOrigin('add', 'https://partner.example.com');
+ await readOrigins();
+ await editOrigin('remove', 'https://partner.example.com');
+ await editOrigin('add', 'https://portal.example.com');
+ expect(await readOrigins()).toEqual(['https://portal.example.com']);
+ });
+
+ it('preserves concurrent additions', async () => {
+ const origins = ['https://one.example.com', 'https://two.example.com'];
+ const responses = await Promise.all(
+ origins.map((origin) => editOrigin('add', origin)),
+ );
+ for (const response of responses)
+ expect(response.body.errors).toBeUndefined();
+ expect((await readOrigins()).sort()).toEqual(origins.sort());
+ });
+
+ it('enforces the origin limit during concurrent additions', async () => {
+ for (let index = 0; index < MAX_ALLOWED_IFRAME_ORIGINS - 1; index++) {
+ const response = await editOrigin(
+ 'add',
+ `https://portal-${index}.example.com`,
+ );
+ expect(response.body.errors).toBeUndefined();
+ }
+ const responses = await Promise.all([
+ editOrigin('add', 'https://one.example.com'),
+ editOrigin('add', 'https://two.example.com'),
+ ]);
+ expect(
+ responses.filter((response) => response.body.errors),
+ ).toHaveLength(1);
+ expect(await readOrigins()).toHaveLength(MAX_ALLOWED_IFRAME_ORIGINS);
+ });
+
+ it('supports HTTP origins for self-hosted portals', async () => {
+ const response = await editOrigin(
+ 'add',
+ 'http://portal.corp.lan',
+ ).expect(200);
+ expect(response.body.errors).toBeUndefined();
+ expect(await readOrigins()).toEqual(['http://portal.corp.lan']);
+ });
+
+ it('rejects updates without Security permission', async () => {
+ const response = await editOrigin(
+ 'add',
+ 'https://portal.example.com',
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ).expect(200);
+ expect(response.body.errors[0].extensions.code).toBe(
+ ErrorCode.FORBIDDEN,
+ );
+ });
+ });
+
describe('microsoft auth', () => {
it('should update workspace when user has permission (admin role)', async () => {
const queryData = {
diff --git a/packages/twenty-shared/src/constants/ClientConfigBootstrapElementId.ts b/packages/twenty-shared/src/constants/ClientConfigBootstrapElementId.ts
new file mode 100644
index 00000000000..e1c5e2eadc3
--- /dev/null
+++ b/packages/twenty-shared/src/constants/ClientConfigBootstrapElementId.ts
@@ -0,0 +1 @@
+export const CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID = 'twenty-client-config';
diff --git a/packages/twenty-shared/src/constants/MaxAllowedIframeOrigins.ts b/packages/twenty-shared/src/constants/MaxAllowedIframeOrigins.ts
new file mode 100644
index 00000000000..cbcc31ae30a
--- /dev/null
+++ b/packages/twenty-shared/src/constants/MaxAllowedIframeOrigins.ts
@@ -0,0 +1 @@
+export const MAX_ALLOWED_IFRAME_ORIGINS = 20;
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 13b9823ff60..03edc139593 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -12,6 +12,7 @@ export { ACCOUNT_TYPES } from './AccountTypes';
export { ALLOWED_FULL_NAME_SORT_SUBFIELDS } from './AllowedFullNameSortSubfields';
export { BACKEND_BATCH_REQUEST_MAX_COUNT } from './BackendBatchRequestMaxCount';
export { CalendarStartDay } from './CalendarStartDay';
+export { CLIENT_CONFIG_BOOTSTRAP_ELEMENT_ID } from './ClientConfigBootstrapElementId';
export { COMMAND_MENU_CONFIRMATION_MODAL_RESULT_BROWSER_EVENT_NAME } from './CommandMenuConfirmationModalResultBrowserEventName';
export { COMPOSITE_FIELD_SUB_FIELD_LABELS } from './CompositeFieldSubFieldLabels';
export { COMPOSITE_FIELD_TYPE_SUB_FIELDS_NAMES } from './CompositeFieldTypeSubFieldsNames';
@@ -53,6 +54,7 @@ export { IANA_TIME_ZONES } from './IanaTimeZones';
export { IMAGE_IDENTIFIER_FIELD_METADATA_TYPES } from './ImageIdentifierFieldMetadataTypes';
export { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from './InternalCreditsPerDisplayCredit';
export { LABEL_IDENTIFIER_FIELD_METADATA_TYPES } from './LabelIdentifierFieldMetadataTypes';
+export { MAX_ALLOWED_IFRAME_ORIGINS } from './MaxAllowedIframeOrigins';
export { MAX_CORE_WORKFLOW_FILTER_RULES } from './MaxCoreWorkflowFilterRules';
export { MAX_CUSTOM_INDEXES_PER_OBJECT } from './MaxCustomIndexesPerObject';
export { MAX_EMAIL_RECIPIENTS } from './MaxEmailRecipients';
diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.ts
index 8e535186181..08465b601df 100644
--- a/packages/twenty-shared/src/utils/index.ts
+++ b/packages/twenty-shared/src/utils/index.ts
@@ -300,6 +300,7 @@ export { isSafeUrl } from './url/isSafeUrl';
export { isValidDomain } from './url/isValidDomain';
export { isValidHostname } from './url/isValidHostname';
export { isValidUrl } from './url/isValidUrl';
+export { normalizeAllowedIframeOrigin } from './url/normalizeAllowedIframeOrigin';
export { normalizeDomain } from './url/normalizeDomain';
export { normalizeUrl } from './url/normalizeUrl';
export { normalizeUrlOrigin } from './url/normalizeUrlOrigin';
diff --git a/packages/twenty-shared/src/utils/url/__tests__/normalizeAllowedIframeOrigin.test.ts b/packages/twenty-shared/src/utils/url/__tests__/normalizeAllowedIframeOrigin.test.ts
new file mode 100644
index 00000000000..a2e0445f870
--- /dev/null
+++ b/packages/twenty-shared/src/utils/url/__tests__/normalizeAllowedIframeOrigin.test.ts
@@ -0,0 +1,43 @@
+import { normalizeAllowedIframeOrigin } from '../normalizeAllowedIframeOrigin';
+
+describe('normalizeAllowedIframeOrigin', () => {
+ it.each([
+ ['https://PORTAL.example.com/', 'https://portal.example.com'],
+ ['https://portal.example.com:443', 'https://portal.example.com'],
+ ['https://portal.example.com:8443', 'https://portal.example.com:8443'],
+ ['https://localhost', 'https://localhost'],
+ ['http://PORTAL.corp.lan:80/', 'http://portal.corp.lan'],
+ ['http://localhost:3001', 'http://localhost:3001'],
+ ])('normalizes %s', (value, expected) => {
+ expect(normalizeAllowedIframeOrigin(value)).toBe(expected);
+ });
+
+ it.each(['http://[::1]:3000', 'https://[2001:db8::1]'])(
+ 'rejects IPv6 literals unsupported by CSP host sources: %s',
+ (value) => {
+ expect(normalizeAllowedIframeOrigin(value)).toBeUndefined();
+ },
+ );
+
+ it.each([
+ '*',
+ 'null',
+ 'https://*.example.com',
+ 'https://example.com/path',
+ 'https://example.com/.',
+ 'https://example.com?',
+ 'https://example.com#',
+ 'https://@example.com',
+ 'https://example.com?query=1',
+ 'https://example.com#fragment',
+ 'https://user:[email protected]',
+ 'https://example.com;script-src',
+ 'https://example.com\r\nX-Test: yes',
+ 'https://example.com https://evil.com',
+ 'https:example.com',
+ 'https://example.com\\evil',
+ 'https://example..com',
+ ])('rejects %s', (value) => {
+ expect(normalizeAllowedIframeOrigin(value)).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-shared/src/utils/url/normalizeAllowedIframeOrigin.ts b/packages/twenty-shared/src/utils/url/normalizeAllowedIframeOrigin.ts
new file mode 100644
index 00000000000..dd29c43fb68
--- /dev/null
+++ b/packages/twenty-shared/src/utils/url/normalizeAllowedIframeOrigin.ts
@@ -0,0 +1,30 @@
+import { getUrlSafely } from '@/utils/getUrlSafely';
+import { isDefined } from '@/utils/validation';
+
+export const normalizeAllowedIframeOrigin = (
+ value: string,
+): string | undefined => {
+ if (value.length > 300 || /[\s*\\]/.test(value)) {
+ return undefined;
+ }
+
+ const url = getUrlSafely(value);
+
+ if (
+ !isDefined(url) ||
+ !['https:', 'http:'].includes(url.protocol) ||
+ !/^https?:\/\/[^/?#@]+\/?$/i.test(value) ||
+ !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(
+ url.hostname,
+ ) ||
+ url.username !== '' ||
+ url.password !== '' ||
+ url.pathname !== '/' ||
+ url.search !== '' ||
+ url.hash !== ''
+ ) {
+ return undefined;
+ }
+
+ return url.origin;
+};
diff --git a/yarn.lock b/yarn.lock
index 3c818622943..c30106fb350 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -11713,28 +11713,6 @@ __metadata:
languageName: node
linkType: hard
-"@nestjs/serve-static@npm:5.0.5":
- version: 5.0.5
- resolution: "@nestjs/serve-static@npm:5.0.5"
- dependencies:
- path-to-regexp: "npm:8.4.2"
- peerDependencies:
- "@fastify/static": ^8.0.4 || ^9.0.0
- "@nestjs/common": ^11.0.2
- "@nestjs/core": ^11.0.2
- express: ^5.0.1
- fastify: ^5.2.1
- peerDependenciesMeta:
- "@fastify/static":
- optional: true
- express:
- optional: true
- fastify:
- optional: true
- checksum: 10c0/c552b2f743b4010e3dcdaf0df26fee8a54c236d08386811f46ab204d93c4535d0e60a1b3a8cc5b5c20eb96447588ccfac9eea078c9171bf53d16292019b024a1
- languageName: node
- linkType: hard
-
"@nestjs/terminus@npm:11.0.0":
version: 11.0.0
resolution: "@nestjs/terminus@npm:11.0.0"
@@ -50358,7 +50336,6 @@ __metadata:
"@nestjs/platform-express": "npm:11.2.1"
"@nestjs/schedule": "npm:^6.0.1"
"@nestjs/schematics": "npm:^11.0.9"
- "@nestjs/serve-static": "npm:5.0.5"
"@nestjs/terminus": "npm:11.0.0"
"@nestjs/testing": "npm:11.2.1"
"@nestjs/typeorm": "npm:11.0.0"