Skip to content

The open alternative to Salesforce, designed for AI.

[2/3] Let each member set their own value of a user application variable (#26869)

nitin4f83ff5d7b61
diff --git a/packages/twenty-agent-skills/references/develop-app/layout.md b/packages/twenty-agent-skills/references/develop-app/layout.md
index df902447be7..1ede76338b5 100644
--- a/packages/twenty-agent-skills/references/develop-app/layout.md
+++ b/packages/twenty-agent-skills/references/develop-app/layout.md
@@ -60,7 +60,7 @@ To add an entry to an app's settings menu, declare it with `defineSettingsMenuIt
The menu item points at the component, not the reverse, so one component can back several items. Declare as many as the app needs. Each renders as a tab on the app's page under Settings > Apps, after the built-in General tab, in `position` order.
-`scope` is `WORKSPACE` (configured once for the whole workspace, the default) or `USER` (configured by each member for themselves). Only `WORKSPACE` items render today — a `USER` item is persisted and synced but nothing displays it until its placement under the member's own settings lands, so say so rather than declaring one for a settings entry an app needs visible now. Members cannot save their own value of an application variable yet, even one declared with `scope: 'USER'`, so a `USER` item storing something per person must persist it through the app's own objects.
+`scope` is `WORKSPACE` (configured once for the whole workspace, the default) or `USER` (configured by each member for themselves). Only `WORKSPACE` items render today — a `USER` item is persisted and synced but nothing displays it until its placement under the member's own settings lands, so say so rather than declaring one for a settings entry an app needs visible now. To store something per person, a `USER` item should use an application variable declared with `scope: 'USER'`, which `getApplicationVariable` returns with the viewing member's value unless it is secret; a component cannot save it, since `updateMyUserApplicationVariable` refuses application tokens and takes the member's own session only; a variable without that scope holds one value shared by the whole workspace.
Items sort by ascending `position`, which is a decimal so an item can be slotted between two existing ones. Two items of one app cannot share a position in the same scope, and `General` is reserved for the built-in item.
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 010225bda13..74cdef8b66b 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -21,7 +21,7 @@ Other rules:
- Return a bulk summary with per-record results for multi-record actions, including counts for success, no match, and failed records.
- Prefer idempotent behavior for jobs and repeated invocations.
- Read secrets through the application-config helper, not raw `process.env`.
-- Application variables declared with `scope: 'USER'` are never injected into `process.env`: the member who triggers a run is not always the member the run is about.
+- An application variable declared with `scope: 'USER'` is in `process.env` with the value of the member who triggered the run, or its default until they set their own; a run nobody triggered (cron, install hooks) gets no user variables. That member is not always the one the run is about: a database event runs as whoever edited the record. For example, with a user `SLACK_TOKEN`, a function on opportunity update posts with the editor's token, not the opportunity owner's. When the run is about someone else or every member, read the values with `myUserApplicationVariables` through `new MetadataApiClient({ runAs: 'application' })`.
- Twenty injects `TWENTY_API_URL`, `TWENTY_APP_ACCESS_TOKEN`, `TWENTY_APP_APPLICATION_ACCESS_TOKEN`, `TWENTY_API_KEY`, `TWENTY_FUNCTIONS_URL` and `APPLICATION_ID` into every run. Never declare an application or server variable with one of these names: the manifest is rejected on sync and publish.
- Do not hide customer-impacting side effects behind UI-only actions.
diff --git a/packages/twenty-agent-skills/references/develop-app/standalone-pages.md b/packages/twenty-agent-skills/references/develop-app/standalone-pages.md
index 4bd9247f419..e63709fd701 100644
--- a/packages/twenty-agent-skills/references/develop-app/standalone-pages.md
+++ b/packages/twenty-agent-skills/references/develop-app/standalone-pages.md
@@ -219,7 +219,7 @@ This section only calls out the fields that matter for standalone pages. Use `la
- Set a clear `name`, `icon`, `color`, and `position`.
- Use `folderUniversalIdentifier` only when the page belongs under an existing app folder.
-Public assets and non-secret workspace application variables make standalone pages richer without hardcoding environment data:
+Public assets and non-secret application variables make standalone pages richer without hardcoding environment data:
```tsx
import { defineFrontComponent, getPublicAssetUrl } from 'twenty-sdk/define';
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 6a674c50a02..269623b6fd6 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3150,6 +3150,7 @@ type Mutation {
updateMessageChannel(input: UpdateMessageChannelInput!): MessageChannel!
updateMessageFolder(input: UpdateMessageFolderInput!): MessageFolder!
updateMessageFolders(input: UpdateMessageFoldersInput!): [MessageFolder!]!
+ updateMyUserApplicationVariable(applicationUniversalIdentifier: String!, key: String!, value: String!): Boolean!
updateNavigationMenuItem(input: UpdateOneNavigationMenuItemInput!): NavigationMenuItem!
updateOneAgent(input: UpdateAgentInput!): Agent!
updateOneApplicationVariable(applicationId: UUID, key: String!, value: String!): Boolean!
@@ -3824,6 +3825,7 @@ type Query {
myConnectedAccounts: [ConnectedAccountPublicDTO!]!
myMessageChannels(connectedAccountId: UUID): [MessageChannel!]!
myMessageFolders(messageChannelId: UUID): [MessageFolder!]!
+ myUserApplicationVariables: [WorkspaceMemberApplicationVariables!]!
navigationMenuItem(id: UUID!): NavigationMenuItem
navigationMenuItems: [NavigationMenuItem!]!
object(
@@ -5345,6 +5347,18 @@ type User {
workspaces: [UserWorkspace!]!
}
+type UserApplicationVariableValue {
+ description: String!
+ isDeprecated: Boolean!
+ isRequired: Boolean!
+ isSecret: Boolean!
+ key: String!
+ label: String!
+ options: JSON
+ type: String!
+ value: String!
+}
+
type UserSession {
authProvider: String!
createdAt: DateTime!
@@ -5826,6 +5840,12 @@ type WorkspaceMember {
userWorkspaceId: UUID
}
+type WorkspaceMemberApplicationVariables {
+ userWorkspaceId: UUID!
+ variables: [UserApplicationVariableValue!]!
+ workspaceMemberId: UUID!
+}
+
"""Date format as Month first, Day first, Year first or system as default"""
enum WorkspaceMemberDateFormatEnum {
DAY_FIRST
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 74b7b07c08f..cb2d5809901 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2203,6 +2203,7 @@ export interface Mutation {
updateMessageChannel: MessageChannel
updateMessageFolder: MessageFolder
updateMessageFolders: MessageFolder[]
+ updateMyUserApplicationVariable: Scalars['Boolean']
updateNavigationMenuItem: NavigationMenuItem
updateOneAgent: Agent
updateOneApplicationVariable: Scalars['Boolean']
@@ -2790,6 +2791,7 @@ export interface Query {
myConnectedAccounts: ConnectedAccountPublicDTO[]
myMessageChannels: MessageChannel[]
myMessageFolders: MessageFolder[]
+ myUserApplicationVariables: WorkspaceMemberApplicationVariables[]
navigationMenuItem?: NavigationMenuItem
navigationMenuItems: NavigationMenuItem[]
object: Object
@@ -3419,6 +3421,19 @@ export interface User {
__typename: 'User'
}
+export interface UserApplicationVariableValue {
+ description: Scalars['String']
+ isDeprecated: Scalars['Boolean']
+ isRequired: Scalars['Boolean']
+ isSecret: Scalars['Boolean']
+ key: Scalars['String']
+ label: Scalars['String']
+ options?: Scalars['JSON']
+ type: Scalars['String']
+ value: Scalars['String']
+ __typename: 'UserApplicationVariableValue'
+}
+
export interface UserSession {
authProvider: Scalars['String']
createdAt: Scalars['DateTime']
@@ -3808,6 +3823,13 @@ export interface WorkspaceMember {
__typename: 'WorkspaceMember'
}
+export interface WorkspaceMemberApplicationVariables {
+ userWorkspaceId: Scalars['UUID']
+ variables: UserApplicationVariableValue[]
+ workspaceMemberId: Scalars['UUID']
+ __typename: 'WorkspaceMemberApplicationVariables'
+}
+
/** Date format as Month first, Day first, Year first or system as default */
export type WorkspaceMemberDateFormatEnum = 'DAY_FIRST' | 'MONTH_FIRST' | 'SYSTEM' | 'YEAR_FIRST'
@@ -6315,6 +6337,7 @@ export interface MutationGenqlSelection{
updateMessageChannel?: (MessageChannelGenqlSelection & { __args: {input: UpdateMessageChannelInput} })
updateMessageFolder?: (MessageFolderGenqlSelection & { __args: {input: UpdateMessageFolderInput} })
updateMessageFolders?: (MessageFolderGenqlSelection & { __args: {input: UpdateMessageFoldersInput} })
+ updateMyUserApplicationVariable?: { __args: {applicationUniversalIdentifier: Scalars['String'], key: Scalars['String'], value: Scalars['String']} }
updateNavigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {input: UpdateOneNavigationMenuItemInput} })
updateOneAgent?: (AgentGenqlSelection & { __args: {input: UpdateAgentInput} })
updateOneApplicationVariable?: { __args: {applicationId?: (Scalars['UUID'] | null), key: Scalars['String'], value: Scalars['String']} }
@@ -6943,6 +6966,7 @@ export interface QueryGenqlSelection{
myConnectedAccounts?: ConnectedAccountPublicDTOGenqlSelection
myMessageChannels?: (MessageChannelGenqlSelection & { __args?: {connectedAccountId?: (Scalars['UUID'] | null)} })
myMessageFolders?: (MessageFolderGenqlSelection & { __args?: {messageChannelId?: (Scalars['UUID'] | null)} })
+ myUserApplicationVariables?: WorkspaceMemberApplicationVariablesGenqlSelection
navigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })
navigationMenuItems?: NavigationMenuItemGenqlSelection
object?: (ObjectGenqlSelection & { __args: {
@@ -7872,6 +7896,20 @@ export interface UserGenqlSelection{
__scalar?: boolean | number
}
+export interface UserApplicationVariableValueGenqlSelection{
+ description?: boolean | number
+ isDeprecated?: boolean | number
+ isRequired?: boolean | number
+ isSecret?: boolean | number
+ key?: boolean | number
+ label?: boolean | number
+ options?: boolean | number
+ type?: boolean | number
+ value?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface UserSessionGenqlSelection{
authProvider?: boolean | number
createdAt?: boolean | number
@@ -8295,6 +8333,14 @@ export interface WorkspaceMemberGenqlSelection{
__scalar?: boolean | number
}
+export interface WorkspaceMemberApplicationVariablesGenqlSelection{
+ userWorkspaceId?: boolean | number
+ variables?: UserApplicationVariableValueGenqlSelection
+ workspaceMemberId?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface WorkspaceMigrationGenqlSelection{
actions?: boolean | number
applicationUniversalIdentifier?: boolean | number
@@ -10612,6 +10658,14 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const UserApplicationVariableValue_possibleTypes: string[] = ['UserApplicationVariableValue']
+ export const isUserApplicationVariableValue = (obj?: { __typename?: any } | null): obj is UserApplicationVariableValue => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUserApplicationVariableValue"')
+ return UserApplicationVariableValue_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const UserSession_possibleTypes: string[] = ['UserSession']
export const isUserSession = (obj?: { __typename?: any } | null): obj is UserSession => {
if (!obj?.__typename) throw new Error('__typename is missing in "isUserSession"')
@@ -10836,6 +10890,14 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const WorkspaceMemberApplicationVariables_possibleTypes: string[] = ['WorkspaceMemberApplicationVariables']
+ export const isWorkspaceMemberApplicationVariables = (obj?: { __typename?: any } | null): obj is WorkspaceMemberApplicationVariables => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isWorkspaceMemberApplicationVariables"')
+ return WorkspaceMemberApplicationVariables_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const WorkspaceMigration_possibleTypes: string[] = ['WorkspaceMigration']
export const isWorkspaceMigration = (obj?: { __typename?: any } | null): obj is WorkspaceMigration => {
if (!obj?.__typename) throw new Error('__typename is missing in "isWorkspaceMigration"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index e8f38e9207e..de37e4b014c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -97,24 +97,24 @@ export default {
561,
568,
570,
- 583,
- 589,
+ 584,
590,
- 592,
+ 591,
593,
- 595,
+ 594,
596,
597,
- 600,
+ 598,
601,
- 606,
- 608,
- 611,
- 615,
- 616,
+ 602,
+ 607,
+ 609,
+ 612,
617,
- 620,
- 621
+ 618,
+ 619,
+ 622,
+ 623
],
"types": {
"ActivateWorkspaceInput": {
@@ -469,7 +469,7 @@ export default {
17
],
"configurationType": [
- 600
+ 601
],
"description": [
1
@@ -1167,7 +1167,7 @@ export default {
7
],
"versionDistribution": [
- 581
+ 582
],
"__typename": [
1
@@ -1404,7 +1404,7 @@ export default {
430
],
"workspaceUrls": [
- 622
+ 624
],
"__typename": [
1
@@ -1447,7 +1447,7 @@ export default {
1
],
"configurationType": [
- 600
+ 601
],
"description": [
1
@@ -2036,7 +2036,7 @@ export default {
"CalendarChannelVisibility": {},
"CalendarConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -2044,7 +2044,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -2052,7 +2052,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -2129,7 +2129,7 @@ export default {
"ChartNumberFormat": {},
"ChatConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -2162,7 +2162,7 @@ export default {
},
"ChatThreadsConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -3266,7 +3266,7 @@ export default {
1
],
"type": [
- 601
+ 602
],
"__typename": [
1
@@ -3488,7 +3488,7 @@ export default {
477
],
"logicalOperator": [
- 589
+ 590
],
"parentViewFilterGroupId": [
477
@@ -3511,7 +3511,7 @@ export default {
477
],
"operand": [
- 590
+ 591
],
"positionInViewFilterGroup": [
9
@@ -3566,7 +3566,7 @@ export default {
477
],
"calendarLayout": [
- 583
+ 584
],
"groupLoadLimit": [
7
@@ -3590,7 +3590,7 @@ export default {
7
],
"key": [
- 592
+ 593
],
"mainGroupByFieldMetadataId": [
477
@@ -3602,7 +3602,7 @@ export default {
477
],
"openRecordIn": [
- 593
+ 594
],
"position": [
9
@@ -3611,10 +3611,10 @@ export default {
4
],
"type": [
- 596
+ 597
],
"visibility": [
- 597
+ 598
],
"__typename": [
1
@@ -3622,7 +3622,7 @@ export default {
},
"CreateViewSortInput": {
"direction": [
- 595
+ 596
],
"fieldMetadataId": [
477
@@ -3991,7 +3991,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -4020,7 +4020,7 @@ export default {
184
],
"verificationRecords": [
- 578
+ 579
],
"verifiedAt": [
184
@@ -4033,7 +4033,7 @@ export default {
"EmailingDomainTenantStatus": {},
"EmailsConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -4411,7 +4411,7 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 600
+ 601
],
"fieldDisplayMode": [
242
@@ -4527,7 +4527,7 @@ export default {
},
"FieldRichTextConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -4535,7 +4535,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 600
+ 601
],
"newFieldDefaultVisibility": [
4
@@ -4618,7 +4618,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -4641,7 +4641,7 @@ export default {
268
],
"workspace": [
- 619
+ 621
],
"__typename": [
1
@@ -4669,7 +4669,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 600
+ 601
],
"fieldMetadataId": [
1
@@ -4739,7 +4739,7 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 600
+ 601
],
"frontComponentId": [
477
@@ -4827,7 +4827,7 @@ export default {
"IdentityProviderType": {},
"IframeConfiguration": {
"configurationType": [
- 600
+ 601
],
"url": [
1
@@ -4886,7 +4886,7 @@ export default {
63
],
"workspace": [
- 623
+ 625
],
"__typename": [
1
@@ -5082,7 +5082,7 @@ export default {
1
],
"configurationType": [
- 600
+ 601
],
"description": [
1
@@ -5581,7 +5581,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -5589,7 +5589,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -5884,13 +5884,13 @@ export default {
477
],
"key": [
- 592
+ 593
],
"objectMetadataId": [
477
],
"type": [
- 596
+ 597
],
"__typename": [
1
@@ -5908,7 +5908,7 @@ export default {
}
],
"activateWorkspace": [
- 605,
+ 606,
{
"data": [
0,
@@ -6278,7 +6278,7 @@ export default {
}
],
"createManyViewFieldGroups": [
- 586,
+ 587,
{
"inputs": [
174,
@@ -6287,7 +6287,7 @@ export default {
}
],
"createManyViewFields": [
- 585,
+ 586,
{
"inputs": [
175,
@@ -6296,7 +6296,7 @@ export default {
}
],
"createManyViewGroups": [
- 591,
+ 592,
{
"inputs": [
178,
@@ -6523,7 +6523,7 @@ export default {
}
],
"createValidationRule": [
- 577,
+ 578,
{
"input": [
173,
@@ -6532,7 +6532,7 @@ export default {
}
],
"createView": [
- 582,
+ 583,
{
"input": [
179,
@@ -6541,7 +6541,7 @@ export default {
}
],
"createViewField": [
- 585,
+ 586,
{
"input": [
175,
@@ -6550,7 +6550,7 @@ export default {
}
],
"createViewFieldGroup": [
- 586,
+ 587,
{
"input": [
174,
@@ -6559,7 +6559,7 @@ export default {
}
],
"createViewFilter": [
- 587,
+ 588,
{
"input": [
177,
@@ -6568,7 +6568,7 @@ export default {
}
],
"createViewFilterGroup": [
- 588,
+ 589,
{
"input": [
176,
@@ -6577,7 +6577,7 @@ export default {
}
],
"createViewGroup": [
- 591,
+ 592,
{
"input": [
178,
@@ -6586,7 +6586,7 @@ export default {
}
],
"createViewSort": [
- 594,
+ 595,
{
"input": [
180,
@@ -6595,7 +6595,7 @@ export default {
}
],
"createWebhook": [
- 598,
+ 599,
{
"input": [
181,
@@ -6670,7 +6670,7 @@ export default {
}
],
"deleteCurrentWorkspace": [
- 605
+ 606
],
"deleteEmailGroupChannel": [
312,
@@ -6847,7 +6847,7 @@ export default {
572
],
"deleteUserFromWorkspace": [
- 574,
+ 575,
{
"workspaceMemberIdToDelete": [
1,
@@ -6856,7 +6856,7 @@ export default {
}
],
"deleteValidationRule": [
- 577,
+ 578,
{
"id": [
477,
@@ -6874,7 +6874,7 @@ export default {
}
],
"deleteViewField": [
- 585,
+ 586,
{
"input": [
193,
@@ -6883,7 +6883,7 @@ export default {
}
],
"deleteViewFieldGroup": [
- 586,
+ 587,
{
"input": [
192,
@@ -6892,7 +6892,7 @@ export default {
}
],
"deleteViewFilter": [
- 587,
+ 588,
{
"input": [
194,
@@ -6910,7 +6910,7 @@ export default {
}
],
"deleteViewGroup": [
- 591,
+ 592,
{
"input": [
195,
@@ -6928,7 +6928,7 @@ export default {
}
],
"deleteWebhook": [
- 598,
+ 599,
{
"id": [
477,
@@ -6982,7 +6982,7 @@ export default {
}
],
"destroyViewField": [
- 585,
+ 586,
{
"input": [
199,
@@ -6991,7 +6991,7 @@ export default {
}
],
"destroyViewFieldGroup": [
- 586,
+ 587,
{
"input": [
198,
@@ -7000,7 +7000,7 @@ export default {
}
],
"destroyViewFilter": [
- 587,
+ 588,
{
"input": [
200,
@@ -7018,7 +7018,7 @@ export default {
}
],
"destroyViewGroup": [
- 591,
+ 592,
{
"input": [
201,
@@ -7108,7 +7108,7 @@ export default {
}
],
"enrichWorkspaceCompany": [
- 609
+ 610
],
"executeOneLogicFunction": [
299,
@@ -7838,7 +7838,7 @@ export default {
103
],
"syncApplication": [
- 618,
+ 620,
{
"dryRun": [
4
@@ -8035,7 +8035,7 @@ export default {
}
],
"updateManyViewGroups": [
- 591,
+ 592,
{
"inputs": [
531,
@@ -8070,6 +8070,23 @@ export default {
]
}
],
+ "updateMyUserApplicationVariable": [
+ 4,
+ {
+ "applicationUniversalIdentifier": [
+ 1,
+ "String!"
+ ],
+ "key": [
+ 1,
+ "String!"
+ ],
+ "value": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
"updateNavigationMenuItem": [
341,
{
@@ -8254,7 +8271,7 @@ export default {
}
],
"updateValidationRule": [
- 577,
+ 578,
{
"input": [
522,
@@ -8263,7 +8280,7 @@ export default {
}
],
"updateView": [
- 582,
+ 583,
{
"id": [
1,
@@ -8276,7 +8293,7 @@ export default {
}
],
"updateViewField": [
- 585,
+ 586,
{
"input": [
526,
@@ -8285,7 +8302,7 @@ export default {
}
],
"updateViewFieldGroup": [
- 586,
+ 587,
{
"input": [
524,
@@ -8294,7 +8311,7 @@ export default {
}
],
"updateViewFilter": [
- 587,
+ 588,
{
"input": [
529,
@@ -8303,7 +8320,7 @@ export default {
}
],
"updateViewFilterGroup": [
- 588,
+ 589,
{
"id": [
1,
@@ -8316,7 +8333,7 @@ export default {
}
],
"updateViewGroup": [
- 591,
+ 592,
{
"input": [
531,
@@ -8325,7 +8342,7 @@ export default {
}
],
"updateViewSort": [
- 594,
+ 595,
{
"input": [
534,
@@ -8334,7 +8351,7 @@ export default {
}
],
"updateWebhook": [
- 598,
+ 599,
{
"input": [
536,
@@ -8343,7 +8360,7 @@ export default {
}
],
"updateWorkspace": [
- 605,
+ 606,
{
"data": [
539,
@@ -8352,7 +8369,7 @@ export default {
}
],
"updateWorkspaceAllowedIframeOrigins": [
- 605,
+ 606,
{
"data": [
538,
@@ -8361,7 +8378,7 @@ export default {
}
],
"updateWorkspaceMemberRole": [
- 614,
+ 615,
{
"roleId": [
477,
@@ -8482,7 +8499,7 @@ export default {
}
],
"upsertFieldsWidget": [
- 582,
+ 583,
{
"input": [
545,
@@ -8518,7 +8535,7 @@ export default {
}
],
"upsertViewWidget": [
- 582,
+ 583,
{
"input": [
550,
@@ -8530,13 +8547,13 @@ export default {
60,
{
"input": [
- 575,
+ 576,
"ValidateApprovedAccessDomainInput!"
]
}
],
"verifyEmailAndGetLoginToken": [
- 579,
+ 580,
{
"captchaToken": [
1
@@ -8581,7 +8598,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 580,
+ 581,
{
"otp": [
1,
@@ -8663,7 +8680,7 @@ export default {
"NavigationMenuItemType": {},
"NotesConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -9145,7 +9162,7 @@ export default {
285
],
"configuration": [
- 599
+ 600
],
"createdAt": [
184
@@ -9181,7 +9198,7 @@ export default {
1
],
"type": [
- 601
+ 602
],
"universalIdentifier": [
477
@@ -9305,7 +9322,7 @@ export default {
1
],
"configurationType": [
- 600
+ 601
],
"dateGranularity": [
358
@@ -9551,7 +9568,7 @@ export default {
1
],
"workspaceUrls": [
- 622
+ 624
],
"__typename": [
1
@@ -9751,7 +9768,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 613,
+ 614,
{
"inviteHash": [
1,
@@ -9787,10 +9804,10 @@ export default {
35
],
"currentUserSessions": [
- 573
+ 574
],
"currentWorkspace": [
- 605
+ 606
],
"enterpriseCheckoutSession": [
1,
@@ -9988,10 +10005,10 @@ export default {
}
],
"findWorkspaceAiStats": [
- 607
+ 608
],
"findWorkspaceFromInviteHash": [
- 605,
+ 606,
{
"inviteHash": [
1,
@@ -10000,7 +10017,7 @@ export default {
}
],
"findWorkspaceInvitations": [
- 612
+ 613
],
"frontComponent": [
259,
@@ -10212,7 +10229,7 @@ export default {
}
],
"getView": [
- 582,
+ 583,
{
"id": [
1,
@@ -10221,7 +10238,7 @@ export default {
}
],
"getViewField": [
- 585,
+ 586,
{
"id": [
1,
@@ -10230,7 +10247,7 @@ export default {
}
],
"getViewFieldGroup": [
- 586,
+ 587,
{
"id": [
1,
@@ -10239,7 +10256,7 @@ export default {
}
],
"getViewFieldGroups": [
- 586,
+ 587,
{
"viewId": [
1,
@@ -10248,7 +10265,7 @@ export default {
}
],
"getViewFields": [
- 585,
+ 586,
{
"viewId": [
1,
@@ -10257,7 +10274,7 @@ export default {
}
],
"getViewFilter": [
- 587,
+ 588,
{
"id": [
1,
@@ -10266,7 +10283,7 @@ export default {
}
],
"getViewFilterGroup": [
- 588,
+ 589,
{
"id": [
1,
@@ -10275,7 +10292,7 @@ export default {
}
],
"getViewFilterGroups": [
- 588,
+ 589,
{
"viewId": [
1
@@ -10283,7 +10300,7 @@ export default {
}
],
"getViewFilters": [
- 587,
+ 588,
{
"viewId": [
1
@@ -10291,7 +10308,7 @@ export default {
}
],
"getViewGroup": [
- 591,
+ 592,
{
"id": [
1,
@@ -10300,7 +10317,7 @@ export default {
}
],
"getViewGroups": [
- 591,
+ 592,
{
"viewId": [
1
@@ -10308,7 +10325,7 @@ export default {
}
],
"getViewSort": [
- 594,
+ 595,
{
"id": [
1,
@@ -10317,7 +10334,7 @@ export default {
}
],
"getViewSorts": [
- 594,
+ 595,
{
"viewId": [
1
@@ -10325,19 +10342,19 @@ export default {
}
],
"getViews": [
- 582,
+ 583,
{
"objectMetadataId": [
1
],
"viewTypes": [
- 596,
+ 597,
"[ViewType!]"
]
}
],
"getWorkspaceCreationDefaults": [
- 610
+ 611
],
"githubClaimAuthorizationUrl": [
1,
@@ -10426,6 +10443,9 @@ export default {
]
}
],
+ "myUserApplicationVariables": [
+ 616
+ ],
"navigationMenuItem": [
341,
{
@@ -10554,7 +10574,7 @@ export default {
567
],
"validatePasswordResetToken": [
- 576,
+ 577,
{
"passwordResetToken": [
1,
@@ -10563,7 +10583,7 @@ export default {
}
],
"validationRules": [
- 577,
+ 578,
{
"objectMetadataId": [
477,
@@ -10572,7 +10592,7 @@ export default {
}
],
"webhook": [
- 598,
+ 599,
{
"id": [
477,
@@ -10581,7 +10601,7 @@ export default {
}
],
"webhooks": [
- 598
+ 599
],
"__typename": [
1
@@ -10749,7 +10769,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 600
+ 601
],
"isUIEditable": [
4
@@ -10913,7 +10933,7 @@ export default {
477
],
"workspaceMembers": [
- 614
+ 615
],
"__typename": [
1
@@ -11335,7 +11355,7 @@ export default {
1
],
"result": [
- 612
+ 613
],
"success": [
4
@@ -11521,7 +11541,7 @@ export default {
63
],
"workspace": [
- 623
+ 625
],
"__typename": [
1
@@ -11584,7 +11604,7 @@ export default {
414
],
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -11592,7 +11612,7 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 621
+ 623
],
"thread": [
6
@@ -11696,7 +11716,7 @@ export default {
"SupportDriver": {},
"TasksConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -11779,7 +11799,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -12560,7 +12580,7 @@ export default {
1
],
"type": [
- 601
+ 602
],
"__typename": [
1
@@ -12592,7 +12612,7 @@ export default {
1
],
"type": [
- 601
+ 602
],
"__typename": [
1
@@ -12845,7 +12865,7 @@ export default {
477
],
"logicalOperator": [
- 589
+ 590
],
"parentViewFilterGroupId": [
477
@@ -12876,7 +12896,7 @@ export default {
477
],
"operand": [
- 590
+ 591
],
"positionInViewFilterGroup": [
9
@@ -12936,7 +12956,7 @@ export default {
477
],
"calendarLayout": [
- 583
+ 584
],
"groupLoadLimit": [
7
@@ -12966,7 +12986,7 @@ export default {
1
],
"openRecordIn": [
- 593
+ 594
],
"position": [
9
@@ -12975,10 +12995,10 @@ export default {
4
],
"type": [
- 596
+ 597
],
"visibility": [
- 597
+ 598
],
"__typename": [
1
@@ -12997,7 +13017,7 @@ export default {
},
"UpdateViewSortInputUpdates": {
"direction": [
- 595
+ 596
],
"subFieldName": [
1
@@ -13125,7 +13145,7 @@ export default {
9
],
"workspaceDiscoverability": [
- 611
+ 612
],
"__typename": [
1
@@ -13306,7 +13326,7 @@ export default {
477
],
"logicalOperator": [
- 589
+ 590
],
"parentViewFilterGroupId": [
477
@@ -13326,7 +13346,7 @@ export default {
477
],
"operand": [
- 590
+ 591
],
"positionInViewFilterGroup": [
9
@@ -13355,7 +13375,7 @@ export default {
477
],
"calendarLayout": [
- 583
+ 584
],
"kanbanAggregateOperation": [
17
@@ -13370,13 +13390,13 @@ export default {
477
],
"openRecordIn": [
- 593
+ 594
],
"shouldHideEmptyGroups": [
4
],
"type": [
- 596
+ 597
],
"__typename": [
1
@@ -13384,7 +13404,7 @@ export default {
},
"UpsertViewWidgetViewSortInput": {
"direction": [
- 595
+ 596
],
"fieldMetadataId": [
477
@@ -13685,10 +13705,10 @@ export default {
184
],
"currentUserWorkspace": [
- 574
+ 575
],
"currentWorkspace": [
- 605
+ 606
],
"deletedAt": [
184
@@ -13739,16 +13759,48 @@ export default {
286
],
"userWorkspaces": [
- 574
+ 575
],
"workspaceMember": [
- 614
+ 615
],
"workspaceMembers": [
- 614
+ 615
],
"workspaces": [
- 574
+ 575
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UserApplicationVariableValue": {
+ "description": [
+ 1
+ ],
+ "isDeprecated": [
+ 4
+ ],
+ "isRequired": [
+ 4
+ ],
+ "isSecret": [
+ 4
+ ],
+ "key": [
+ 1
+ ],
+ "label": [
+ 1
+ ],
+ "options": [
+ 285
+ ],
+ "type": [
+ 1
+ ],
+ "value": [
+ 1
],
"__typename": [
1
@@ -13912,7 +13964,7 @@ export default {
63
],
"workspaceUrls": [
- 622
+ 624
],
"__typename": [
1
@@ -13951,7 +14003,7 @@ export default {
477
],
"calendarLayout": [
- 583
+ 584
],
"createdAt": [
184
@@ -13993,7 +14045,7 @@ export default {
7
],
"key": [
- 592
+ 593
],
"mainGroupByFieldMetadataId": [
477
@@ -14005,7 +14057,7 @@ export default {
477
],
"openRecordIn": [
- 593
+ 594
],
"position": [
9
@@ -14014,7 +14066,7 @@ export default {
4
],
"type": [
- 596
+ 597
],
"universalIdentifier": [
477
@@ -14023,25 +14075,25 @@ export default {
184
],
"viewFieldGroups": [
- 586
+ 587
],
"viewFields": [
- 585
+ 586
],
"viewFilterGroups": [
- 588
+ 589
],
"viewFilters": [
- 587
+ 588
],
"viewGroups": [
- 591
+ 592
],
"viewSorts": [
- 594
+ 595
],
"visibility": [
- 597
+ 598
],
"workspaceId": [
477
@@ -14053,7 +14105,7 @@ export default {
"ViewCalendarLayout": {},
"ViewConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -14144,7 +14196,7 @@ export default {
184
],
"viewFields": [
- 585
+ 586
],
"viewId": [
477
@@ -14170,7 +14222,7 @@ export default {
477
],
"operand": [
- 590
+ 591
],
"positionInViewFilterGroup": [
9
@@ -14211,7 +14263,7 @@ export default {
477
],
"logicalOperator": [
- 589
+ 590
],
"parentViewFilterGroupId": [
477
@@ -14276,7 +14328,7 @@ export default {
184
],
"direction": [
- 595
+ 596
],
"fieldMetadataId": [
477
@@ -14412,16 +14464,16 @@ export default {
469
],
"on_ViewConfiguration": [
- 584
+ 585
],
"on_WorkflowConfiguration": [
- 602
+ 603
],
"on_WorkflowRunConfiguration": [
- 603
+ 604
],
"on_WorkflowVersionConfiguration": [
- 604
+ 605
],
"__typename": [
1
@@ -14431,7 +14483,7 @@ export default {
"WidgetType": {},
"WorkflowConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -14439,7 +14491,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -14447,7 +14499,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 600
+ 601
],
"__typename": [
1
@@ -14455,7 +14507,7 @@ export default {
},
"Workspace": {
"activationStatus": [
- 606
+ 607
],
"aiAdditionalInstructions": [
1
@@ -14590,22 +14642,22 @@ export default {
184
],
"viewFields": [
- 585
+ 586
],
"viewFilterGroups": [
- 588
+ 589
],
"viewFilters": [
- 587
+ 588
],
"viewGroups": [
- 591
+ 592
],
"viewSorts": [
- 594
+ 595
],
"views": [
- 582
+ 583
],
"workspaceCustomApplication": [
34
@@ -14614,13 +14666,13 @@ export default {
1
],
"workspaceDiscoverability": [
- 611
+ 612
],
"workspaceMembersCount": [
9
],
"workspaceUrls": [
- 622
+ 624
],
"__typename": [
1
@@ -14650,13 +14702,13 @@ export default {
4
],
"outcome": [
- 608
+ 609
],
"personEnrichment": [
285
],
"personOutcome": [
- 620
+ 622
],
"__typename": [
1
@@ -14710,7 +14762,7 @@ export default {
1
],
"dateFormat": [
- 615
+ 617
],
"id": [
477
@@ -14722,7 +14774,7 @@ export default {
261
],
"numberFormat": [
- 616
+ 618
],
"openRecordIn": [
363
@@ -14731,7 +14783,7 @@ export default {
415
],
"timeFormat": [
- 617
+ 619
],
"timeZone": [
1
@@ -14752,6 +14804,20 @@ export default {
1
]
},
+ "WorkspaceMemberApplicationVariables": {
+ "userWorkspaceId": [
+ 477
+ ],
+ "variables": [
+ 573
+ ],
+ "workspaceMemberId": [
+ 477
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"WorkspaceMemberDateFormatEnum": {},
"WorkspaceMemberNumberFormatEnum": {},
"WorkspaceMemberTimeFormatEnum": {},
@@ -14795,7 +14861,7 @@ export default {
477
],
"workspaceUrls": [
- 622
+ 624
],
"__typename": [
1
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index 03e3f5ee9c3..9423fde2eaf 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -42,7 +42,7 @@ export default defineApplication({
Notes:
- `universalIdentifier` fields are UUIDs you generate once and own. Keep them stable across syncs. The application's own `universalIdentifier` must be a valid UUID: the server rejects a manifest whose identifier is not one. It is unique across the whole instance and is bound to the workspace that owns its registration, so only that workspace can sync the app — see [Registration ownership](/developers/extend/apps/operations/publishing#registration-ownership).
- `applicationVariables` accept an optional `label` — a user-friendly name displayed in the app's settings page instead of the raw variable key.
-- `applicationVariables` become environment variables for your functions and front components. In logic functions (server-side), they are available as `process.env.VARIABLE_NAME`. In front components, use `getApplicationVariable('VARIABLE_NAME')` from `twenty-sdk/front-component`. Variables marked with `isSecret: true` are only injected into logic functions. Front components receive only non-secret variables. Variables with `scope: 'USER'` are not injected at all: see [Workspace and user variables](#workspace-and-user-variables).
+- `applicationVariables` become environment variables for your functions and front components. In logic functions (server-side), they are available as `process.env.VARIABLE_NAME`. In front components, use `getApplicationVariable('VARIABLE_NAME')` from `twenty-sdk/front-component`. Variables marked with `isSecret: true` are only injected into logic functions. Front components receive only non-secret variables. A variable with `scope: 'USER'` holds the value of the member the code runs for: see [Workspace and user variables](#workspace-and-user-variables).
- Your app can also read and update its own variable values at runtime, which is how a custom settings component saves what the user typed: see [Reading and updating variables at runtime](/developers/extend/apps/layout/front-components#reading-and-updating-variables-at-runtime). An application only ever reaches its own variables, in its own workspace.
- The default role is detected automatically from the role file marked with [`defineApplicationRole()`](/developers/extend/apps/config/roles) — you do not need to reference it from `defineApplication()`.
- Pre-install, post-install, and uninstall functions, and the health check, are detected automatically during the manifest build — you do not need to reference them in `defineApplication()`.
@@ -135,10 +135,6 @@ Each application variable has a `scope`:
- **`WORKSPACE`** (default): one value for the whole workspace, set by a member who can manage apps.
- **`USER`**: each member keeps their own value.
-<Note>
-Members cannot save or read their own value of a user variable yet. Until per-member values land, a user variable is declared and synced, but nothing reads it.
-</Note>
-
```ts src/application-config.ts
import { defineApplication, FieldType } from 'twenty-sdk/define';
@@ -156,17 +152,40 @@ export default defineApplication({
});
```
-A user variable's `value` is its default: a member who has not set their own gets it, and a new version of your app can change it. A secret variable cannot have a default. Without one, a member who has not set theirs has no value, so your app decides what an unset value means.
+A user variable's `value` is its default: a member who has not set their own reads it, and a new version of your app can change it. A secret variable cannot have a default. Without one, a member who has not set theirs reads an empty string, so your app decides what an unset value means.
A workspace admin cannot set a value for a user variable: its values belong to each member.
-A variable's scope is set when it is created and cannot change. To change it, declare the variable with a new `universalIdentifier`: the sync deletes the old variable and creates the new one.
+A variable's scope is set when it is created and cannot change. To change it, declare the variable with a new `universalIdentifier`: the sync deletes the old variable, with its members' values, and creates the new one.
-User variables can be `isSecret`, `isRequired`, or both. For example, a personal API key can declare `scope: 'USER', isSecret: true, isRequired: true`.
+User variables can be `isSecret`, `isRequired`, or both. For example, a personal API key can declare `scope: 'USER', isSecret: true, isRequired: true`. Values are encrypted at rest.
For user variables, `isRequired` describes a per-member requirement. It does not affect the workspace configuration warning. Personal configuration warnings and enforcement are not available yet.
-User variables are never injected into `process.env` or returned by `getApplicationVariable`, because the person who triggered a run is not always the person the run is about.
+A user variable is injected with the value of the member your code runs for, or its default until they set their own:
+
+- In a logic function, `process.env` holds the values of the member who triggered the run, the same member `TWENTY_APP_ACCESS_TOKEN` acts as. A run with nobody behind it, such as a cron job or an install hook, gets no user variables at all.
+- In a front component, `getApplicationVariable` returns the values of the member viewing it. Secret user variables are left out, like secret workspace variables.
+
+The member who triggered a run is not always the member it is about: a database event runs as whoever edited the record. When a run is about someone else, or about every member, read the values with `myUserApplicationVariables` through `MetadataApiClient`. It lists every member with their values of your app's user variables, and works in every logic function run, including cron jobs and webhooks. Each entry carries the member's `userWorkspaceId`, `workspaceMemberId` and `variables`: each user variable's declaration (`label`, `description`, `type`, `options`, `isSecret`, `isRequired`, `isDeprecated`) and the member's value, or the default until they set their own. Query it as the application to get real values: with a token that has a person behind it, it only returns that person's entry, with secrets masked.
+
+```ts
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+// In a logic function, for example a cron job
+const client = new MetadataApiClient({ runAs: 'application' });
+
+const { myUserApplicationVariables } = await client.query({
+ myUserApplicationVariables: {
+ workspaceMemberId: true,
+ variables: { key: true, value: true },
+ },
+});
+```
+
+Values are strings, in the same format as `process.env` (see [Variable types](#variable-types)).
+
+A member saves their own value with `updateMyUserApplicationVariable`, which takes your app's `applicationUniversalIdentifier` and needs no `APPLICATIONS` permission. It takes the member's own session only: an application token is refused, your app's included, so only the member changes their settings.
## Default function role
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
index 583632a0863..f3db6fc2b8d 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -133,12 +133,12 @@ Declare as many as you need. Twenty's own **General** item — auto-upgrade, App
- **`USER`** — configured by each member for themselves, under their own user settings.
<Note>
- `USER` items are not displayed yet. Their placement under the user's own
- settings lands with per-member variable values; until then a `USER` item is
- persisted and synced but nothing renders it.
+ `USER` items are not displayed yet. Until their placement under the member's
+ own settings lands, a `USER` item is persisted and synced but nothing renders
+ it.
</Note>
-A `USER` item runs as the member viewing it. Members cannot save their own value of an application variable yet, even one declared with `scope: 'USER'` (see [Workspace and user variables](/developers/extend/apps/config/application#workspace-and-user-variables)). Until they can, an item that stores something per person should persist it through the app's own objects: a workspace variable holds one value shared by everyone, so one member's save would overwrite another's.
+A `USER` item runs as the member viewing it. To store something per person, declare the variable with `scope: 'USER'`: `getApplicationVariable` returns the viewing member's value. Your component cannot save it: `updateMyUserApplicationVariable` refuses application tokens, so each member sets their own value through their session, as described in [Workspace and user variables](/developers/extend/apps/config/application#workspace-and-user-variables). A workspace variable holds one value shared by everyone, so one member's save would overwrite another's.
<Note>
`defineSettingsFrontComponent()` is deprecated in favor of
@@ -502,7 +502,7 @@ Object metadata can be available even when no records are selected. It belongs t
## Application variables
-Workspace application variables defined in [`defineApplication()`](/developers/extend/apps/config/application) with `isSecret: false` are available inside front components via the `getApplicationVariable` utility:
+Application variables defined in [`defineApplication()`](/developers/extend/apps/config/application) with `isSecret: false` are available inside front components via the `getApplicationVariable` utility:
```tsx src/front-components/greeting.tsx
import { defineFrontComponent } from 'twenty-sdk/define';
@@ -567,6 +567,7 @@ Notes:
- The key must be one your app declares in [`defineApplication()`](/developers/extend/apps/config/application). Writing a key that is not declared is a not found.
- Secret variables read back masked, never as the stored value. Writing them works normally.
- Reading a variable's `value`, and writing it, need the `APPLICATIONS` settings permission on both your app's role and the signed-in person's role, since the component's token is the intersection of the two. Add `SystemPermissionFlag.APPLICATIONS` to `permissionFlagUniversalIdentifiers` in your [application role](/developers/extend/apps/config/roles).
+- A user variable (`scope: 'USER'`) is injected with the viewing member's value, unless it is secret, and is not set this way. Your component cannot write it: `updateMyUserApplicationVariable` refuses application tokens and takes the member's own session only. See [Workspace and user variables](/developers/extend/apps/config/application#workspace-and-user-variables).
### System variables
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 4bc079bd8cb..4bd97d74345 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -1034,6 +1034,8 @@ setCompany(result.company);
It is also how an app reads and updates its own [application variables](/developers/extend/apps/layout/front-components#reading-and-updating-variables-at-runtime), in a logic function as in a front component. An application token only ever reaches its own application, in its own workspace.
+A [user variable](/developers/extend/apps/config/application#workspace-and-user-variables) is in `process.env` with the value of the member who triggered the run, or its default until they set their own. A run nobody triggered gets no user variables. To read every member's value of your app's user variables, for example in a cron job, query `myUserApplicationVariables` with `runAs: 'application'`.
+
```ts
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 0138f8f0ec2..fc9933c0f04 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -3312,6 +3312,7 @@ export type Mutation = {
updateMessageChannel: MessageChannel;
updateMessageFolder: MessageFolder;
updateMessageFolders: Array<MessageFolder>;
+ updateMyUserApplicationVariable: Scalars['Boolean']['output'];
updateNavigationMenuItem: NavigationMenuItem;
updateOneAgent: Agent;
updateOneApplicationVariable: Scalars['Boolean']['output'];
@@ -4460,6 +4461,13 @@ export type MutationUpdateMessageFoldersArgs = {
};
+export type MutationUpdateMyUserApplicationVariableArgs = {
+ applicationUniversalIdentifier: Scalars['String']['input'];
+ key: Scalars['String']['input'];
+ value: Scalars['String']['input'];
+};
+
+
export type MutationUpdateNavigationMenuItemArgs = {
input: UpdateOneNavigationMenuItemInput;
};
@@ -5370,6 +5378,7 @@ export type Query = {
myConnectedAccounts: Array<ConnectedAccountPublicDto>;
myMessageChannels: Array<MessageChannel>;
myMessageFolders: Array<MessageFolder>;
+ myUserApplicationVariables: Array<WorkspaceMemberApplicationVariables>;
navigationMenuItem?: Maybe<NavigationMenuItem>;
navigationMenuItems: Array<NavigationMenuItem>;
object: Object;
@@ -7416,6 +7425,19 @@ export type User = {
workspaces: Array<UserWorkspace>;
};
+export type UserApplicationVariableValue = {
+ __typename?: 'UserApplicationVariableValue';
+ description: Scalars['String']['output'];
+ isDeprecated: Scalars['Boolean']['output'];
+ isRequired: Scalars['Boolean']['output'];
+ isSecret: Scalars['Boolean']['output'];
+ key: Scalars['String']['output'];
+ label: Scalars['String']['output'];
+ options?: Maybe<Scalars['JSON']['output']>;
+ type: Scalars['String']['output'];
+ value: Scalars['String']['output'];
+};
+
export type UserSession = {
__typename?: 'UserSession';
authProvider: Scalars['String']['output'];
@@ -7928,6 +7950,13 @@ export type WorkspaceMember = {
userWorkspaceId?: Maybe<Scalars['UUID']['output']>;
};
+export type WorkspaceMemberApplicationVariables = {
+ __typename?: 'WorkspaceMemberApplicationVariables';
+ userWorkspaceId: Scalars['UUID']['output'];
+ variables: Array<UserApplicationVariableValue>;
+ workspaceMemberId: Scalars['UUID']['output'];
+};
+
/** Date format as Month first, Day first, Year first or system as default */
export enum WorkspaceMemberDateFormatEnum {
DAY_FIRST = 'DAY_FIRST',
diff --git a/packages/twenty-server/src/database/commands/secret-encryption-rotation/constants/secret-encryption-rotation-site-entries.constant.ts b/packages/twenty-server/src/database/commands/secret-encryption-rotation/constants/secret-encryption-rotation-site-entries.constant.ts
index 7dc404c310d..22beb36638a 100644
--- a/packages/twenty-server/src/database/commands/secret-encryption-rotation/constants/secret-encryption-rotation-site-entries.constant.ts
+++ b/packages/twenty-server/src/database/commands/secret-encryption-rotation/constants/secret-encryption-rotation-site-entries.constant.ts
@@ -5,6 +5,7 @@ import { SensitiveConfigStorageRotationHandler } from 'src/database/commands/sec
import { type SecretEncryptionRotationHandler } from 'src/database/commands/secret-encryption-rotation/interfaces/secret-encryption-rotation-handler.interface';
import { ApplicationRegistrationVariableEntity } from 'src/engine/core-modules/application/application-registration-variable/application-registration-variable.entity';
import { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
+import { UserApplicationVariableValueEntity } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.entity';
import { SigningKeyEntity } from 'src/engine/core-modules/jwt/entities/signing-key.entity';
import { type ExtractEncryptedColumns } from 'src/engine/core-modules/secret-encryption/branded-strings/extract-encrypted-columns.type';
import { TwoFactorAuthenticationMethodEntity } from 'src/engine/core-modules/two-factor-authentication/entities/two-factor-authentication-method.entity';
@@ -106,6 +107,17 @@ export const SECRET_ENCRYPTION_ROTATION_SITE_ENTRIES = defineRotationRegistry({
},
},
},
+ UserApplicationVariableValueEntity: {
+ entity: UserApplicationVariableValueEntity,
+ columnSiteNames: {
+ value: {
+ siteName: 'user-application-variable-value',
+ customHandler: undefined,
+ isWorkspaceScoped: true,
+ extraWhere: undefined,
+ },
+ },
+ },
});
// Sites whose encrypted-ness is per-row conditional and lives outside
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791328043361-add-user-application-variable-value.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791328043361-add-user-application-variable-value.ts
new file mode 100644
index 00000000000..1fe0fca3c89
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791328043361-add-user-application-variable-value.ts
@@ -0,0 +1,55 @@
+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.46.0', 1791328043361)
+export class AddUserApplicationVariableValueFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `CREATE TABLE "core"."userApplicationVariableValue" ("workspaceId" uuid NOT NULL, "id" uuid NOT NULL DEFAULT uuid_generate_v4(), "applicationVariableId" uuid NOT NULL, "scope" "core"."applicationVariable_scope_enum" NOT NULL DEFAULT 'USER', "userWorkspaceId" uuid NOT NULL, "value" text NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "IDX_USER_APPLICATION_VARIABLE_VALUE_VARIABLE_USER_UNIQUE" UNIQUE ("applicationVariableId", "userWorkspaceId"), CONSTRAINT "CHK_userApplicationVariableValue_scope_user" CHECK ("scope" = 'USER'), CONSTRAINT "CHK_userApplicationVariableValue_value_encrypted" CHECK ("value" LIKE 'enc:v2:%'), CONSTRAINT "PK_51df8f8b24eb8c05e07a3542f92" PRIMARY KEY ("id"))`,
+ );
+ await queryRunner.query(
+ `CREATE INDEX "IDX_USER_APPLICATION_VARIABLE_VALUE_WORKSPACE_ID" ON "core"."userApplicationVariableValue" ("workspaceId") `,
+ );
+ await queryRunner.query(
+ `CREATE INDEX "IDX_USER_APPLICATION_VARIABLE_VALUE_USER_WORKSPACE_ID" ON "core"."userApplicationVariableValue" ("userWorkspaceId") `,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."applicationVariable" ADD CONSTRAINT "IDX_APPLICATION_VARIABLE_ID_SCOPE_UNIQUE" UNIQUE ("id", "scope")`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" ADD CONSTRAINT "FK_71281400f08a8466962c3f067e0" FOREIGN KEY ("workspaceId") REFERENCES "core"."workspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" ADD CONSTRAINT "FK_ef9ee4ba7549728c956374e77eb" FOREIGN KEY ("applicationVariableId", "scope") REFERENCES "core"."applicationVariable"("id","scope") ON DELETE CASCADE ON UPDATE NO ACTION`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" ADD CONSTRAINT "FK_5b5a27417740e6bb8f1cb4b8fce" FOREIGN KEY ("userWorkspaceId") REFERENCES "core"."userWorkspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" DROP CONSTRAINT "FK_5b5a27417740e6bb8f1cb4b8fce"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" DROP CONSTRAINT "FK_ef9ee4ba7549728c956374e77eb"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."userApplicationVariableValue" DROP CONSTRAINT "FK_71281400f08a8466962c3f067e0"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."applicationVariable" DROP CONSTRAINT "IDX_APPLICATION_VARIABLE_ID_SCOPE_UNIQUE"`,
+ );
+ await queryRunner.query(
+ `DROP INDEX "core"."IDX_USER_APPLICATION_VARIABLE_VALUE_USER_WORKSPACE_ID"`,
+ );
+ await queryRunner.query(
+ `DROP INDEX "core"."IDX_USER_APPLICATION_VARIABLE_VALUE_WORKSPACE_ID"`,
+ );
+ await queryRunner.query(`DROP TABLE "core"."userApplicationVariableValue"`);
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/add-user-application-variable-value-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/add-user-application-variable-value-upgrade-command-name.constant.ts
new file mode 100644
index 00000000000..80ed7af5938
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/add-user-application-variable-value-upgrade-command-name.constant.ts
@@ -0,0 +1,2 @@
+export const ADD_USER_APPLICATION_VARIABLE_VALUE_UPGRADE_COMMAND_NAME =
+ '2.46.0_AddUserApplicationVariableValueFastInstanceCommand_1791328043361';
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 7ca7e801302..57205367f07 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
@@ -228,6 +228,7 @@ import { AddTriggersToAgentFastInstanceCommand } from 'src/database/commands/upg
import { AddScopeAndDefaultValueToApplicationVariablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791274238040-add-scope-and-default-value-to-application-variables';
import { CreatePendingWakeUpTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791299810581-create-pending-wake-up-table';
import { CreateAgentRunSuspensionTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791301683545-create-agent-run-suspension-table';
+import { AddUserApplicationVariableValueFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791328043361-add-user-application-variable-value';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -458,4 +459,5 @@ export const INSTANCE_COMMANDS = [
AddScopeAndDefaultValueToApplicationVariablesFastInstanceCommand,
CreatePendingWakeUpTableFastInstanceCommand,
CreateAgentRunSuspensionTableFastInstanceCommand,
+ AddUserApplicationVariableValueFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/__tests__/user-application-variable-value.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/__tests__/user-application-variable-value.service.spec.ts
new file mode 100644
index 00000000000..667f0213960
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/__tests__/user-application-variable-value.service.spec.ts
@@ -0,0 +1,131 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { UserApplicationVariableValueEntity } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.entity';
+import { UserApplicationVariableValueService } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.service';
+import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
+import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { type FlatApplicationVariable } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable.type';
+import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const WORKSPACE_ID = 'workspace-id';
+const APPLICATION_ID = 'application-id';
+const USER_WORKSPACE_ID = 'user-workspace-id';
+
+const buildFlatApplicationVariable = (
+ overrides: Pick<FlatApplicationVariable, 'id' | 'key' | 'scope'> &
+ Partial<FlatApplicationVariable>,
+) =>
+ ({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ isSecret: false,
+ defaultValue: null,
+ value: null,
+ ...overrides,
+ }) as FlatApplicationVariable;
+
+const FLAT_APPLICATION_VARIABLES = [
+ buildFlatApplicationVariable({
+ id: 'workspace-variable-id',
+ key: 'API_BASE_URL',
+ scope: 'WORKSPACE',
+ }),
+ buildFlatApplicationVariable({
+ id: 'record-my-meetings-id',
+ key: 'RECORD_MY_MEETINGS',
+ scope: 'USER',
+ defaultValue: 'off',
+ }),
+ buildFlatApplicationVariable({
+ id: 'personal-api-key-id',
+ key: 'PERSONAL_API_KEY',
+ scope: 'USER',
+ isSecret: true,
+ }),
+ buildFlatApplicationVariable({
+ id: 'language-id',
+ key: 'LANGUAGE',
+ scope: 'USER',
+ defaultValue: 'en',
+ }),
+];
+
+describe('UserApplicationVariableValueService', () => {
+ let service: UserApplicationVariableValueService;
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ UserApplicationVariableValueService,
+ {
+ provide: getWorkspaceScopedRepositoryToken(
+ UserApplicationVariableValueEntity,
+ ),
+ useValue: {
+ find: jest.fn().mockResolvedValue([
+ {
+ applicationVariableId: 'record-my-meetings-id',
+ value: 'enc:on',
+ },
+ {
+ applicationVariableId: 'personal-api-key-id',
+ value: 'enc:key',
+ },
+ ]),
+ },
+ },
+ {
+ provide: getWorkspaceScopedRepositoryToken(UserWorkspaceEntity),
+ useValue: {},
+ },
+ {
+ provide: ApplicationVariableEntityService,
+ useValue: {
+ findFlatApplicationVariables: jest
+ .fn()
+ .mockResolvedValue(FLAT_APPLICATION_VARIABLES),
+ getDisplayValue: ({
+ value,
+ isSecret,
+ }: {
+ value: string;
+ isSecret: boolean;
+ }) => (isSecret ? '********' : `plaintext of ${value}`),
+ },
+ },
+ { provide: WorkspaceCacheService, useValue: {} },
+ { provide: SecretEncryptionService, useValue: {} },
+ ],
+ }).compile();
+
+ service = module.get(UserApplicationVariableValueService);
+ });
+
+ describe('getServerEnvVariables', () => {
+ it('should give a run the values of the member behind it, secrets unmasked, and the defaults they did not set', async () => {
+ const envVariables = await service.getServerEnvVariables({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ userWorkspaceId: USER_WORKSPACE_ID,
+ });
+
+ expect(envVariables).toEqual({
+ RECORD_MY_MEETINGS: 'plaintext of enc:on',
+ PERSONAL_API_KEY: 'plaintext of enc:key',
+ LANGUAGE: 'en',
+ });
+ });
+
+ it('should leave user variables out of a run with nobody behind it', async () => {
+ const envVariables = await service.getServerEnvVariables({
+ workspaceId: WORKSPACE_ID,
+ applicationId: APPLICATION_ID,
+ userWorkspaceId: undefined,
+ });
+
+ expect(envVariables).toEqual({});
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.entity.ts
index ac81101e2bc..a2c58679148 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.entity.ts
@@ -5,6 +5,7 @@ import {
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
+ Unique,
UpdateDateColumn,
} from 'typeorm';
@@ -32,6 +33,9 @@ import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-enti
schema: 'core',
})
@ObjectType('ApplicationVariable')
+// userApplicationVariableValue's foreign key references (id, scope), and
+// Postgres needs a unique constraint on exactly the referenced columns.
+@Unique('IDX_APPLICATION_VARIABLE_ID_SCOPE_UNIQUE', ['id', 'scope'])
// All values are always encrypted regardless of `isSecret`. The
// `isSecret` flag only controls display behavior (masked vs plaintext).
@Check('CHK_applicationVariable_value_encrypted', `"value" LIKE 'enc:v2:%'`)
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.module.ts
index aeb262e2da6..475bcfefcf5 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.module.ts
@@ -1,28 +1,49 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { ApplicationLookupModule } from 'src/engine/core-modules/application/application-lookup/application-lookup.module';
+import { ApplicationRegistrationLookupModule } from 'src/engine/core-modules/application/application-registration/application-registration-lookup/application-registration-lookup.module';
+import { UserApplicationVariableValueEntity } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.entity';
+import { UserApplicationVariableValueResolver } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.resolver';
+import { UserApplicationVariableValueService } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.service';
import { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
import { ApplicationVariableEntityResolver } from 'src/engine/core-modules/application/application-variable/application-variable.resolver';
import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { FlatApplicationVariableModule } from 'src/engine/metadata-modules/flat-application-variable/flat-application-variable.module';
+import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
imports: [
- TypeOrmModule.forFeature([ApplicationVariableEntity]),
+ TypeOrmModule.forFeature([
+ ApplicationVariableEntity,
+ UserApplicationVariableValueEntity,
+ UserWorkspaceEntity,
+ ]),
+ ApplicationLookupModule,
+ ApplicationRegistrationLookupModule,
PermissionsModule,
WorkspaceCacheModule,
SecretEncryptionModule,
FlatApplicationVariableModule,
+ WorkspaceManyOrAllFlatEntityMapsCacheModule,
],
providers: [
provideWorkspaceScopedRepository(ApplicationVariableEntity),
+ provideWorkspaceScopedRepository(UserApplicationVariableValueEntity),
+ provideWorkspaceScopedRepository(UserWorkspaceEntity),
ApplicationVariableEntityService,
ApplicationVariableEntityResolver,
+ UserApplicationVariableValueService,
+ UserApplicationVariableValueResolver,
+ ],
+ exports: [
+ ApplicationVariableEntityService,
+ UserApplicationVariableValueService,
],
- exports: [ApplicationVariableEntityService],
})
export class ApplicationVariableEntityModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.service.ts
index 188aec155ec..4de87710498 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.service.ts
@@ -31,7 +31,12 @@ export class ApplicationVariableEntityService {
private readonly secretEncryptionService: SecretEncryptionService,
) {}
- getDisplayValue(applicationVariable: ApplicationVariableEntity): string {
+ getDisplayValue(
+ applicationVariable: Pick<
+ ApplicationVariableEntity,
+ 'value' | 'workspaceId' | 'isSecret'
+ >,
+ ): string {
const plaintextValue = this.decryptValue(applicationVariable);
if (plaintextValue === '') {
@@ -68,7 +73,7 @@ export class ApplicationVariableEntityService {
);
}
- private async findFlatApplicationVariables({
+ async findFlatApplicationVariables({
workspaceId,
applicationId,
flatApplicationVariableMaps: preloadedFlatApplicationVariableMaps,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-my-user-application-variable.input.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-my-user-application-variable.input.ts
new file mode 100644
index 00000000000..03b888ce3e5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-my-user-application-variable.input.ts
@@ -0,0 +1,15 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+
+@ArgsType()
+export class UpdateMyUserApplicationVariableInput {
+ @Field(() => String)
+ applicationUniversalIdentifier: string;
+
+ @Field(() => String)
+ key: string;
+
+ @Field(() => String)
+ value: PlaintextString;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/user-application-variable-value.dto.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/user-application-variable-value.dto.ts
new file mode 100644
index 00000000000..ab0df036737
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/user-application-variable-value.dto.ts
@@ -0,0 +1,9 @@
+import { ObjectType, OmitType } from '@nestjs/graphql';
+
+import { ApplicationVariableEntityDTO } from 'src/engine/core-modules/application/application-variable/dtos/application-variable.dto';
+
+@ObjectType('UserApplicationVariableValue')
+export class UserApplicationVariableValueDTO extends OmitType(
+ ApplicationVariableEntityDTO,
+ ['id', 'scope'] as const,
+) {}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto.ts
new file mode 100644
index 00000000000..11284307886
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto.ts
@@ -0,0 +1,20 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { UserApplicationVariableValueDTO } from 'src/engine/core-modules/application/application-variable/dtos/user-application-variable-value.dto';
+
+@ObjectType('WorkspaceMemberApplicationVariables')
+export class WorkspaceMemberApplicationVariablesDTO {
+ @IsUUID()
+ @Field(() => UUIDScalarType)
+ userWorkspaceId: string;
+
+ @IsUUID()
+ @Field(() => UUIDScalarType)
+ workspaceMemberId: string;
+
+ @Field(() => [UserApplicationVariableValueDTO])
+ variables: UserApplicationVariableValueDTO[];
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.entity.ts
new file mode 100644
index 00000000000..037891ecc5d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.entity.ts
@@ -0,0 +1,84 @@
+import {
+ Check,
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ JoinColumn,
+ ManyToOne,
+ PrimaryGeneratedColumn,
+ type Relation,
+ Unique,
+ UpdateDateColumn,
+} from 'typeorm';
+
+import {
+ APPLICATION_VARIABLE_SCOPES,
+ type ApplicationVariableScope,
+} from 'twenty-shared/application';
+
+import { ADD_USER_APPLICATION_VARIABLE_VALUE_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-46/add-user-application-variable-value-upgrade-command-name.constant';
+import { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
+import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
+
+@Entity({ name: 'userApplicationVariableValue', schema: 'core' })
+@WasIntroducedInUpgrade({
+ upgradeCommandName: ADD_USER_APPLICATION_VARIABLE_VALUE_UPGRADE_COMMAND_NAME,
+})
+@Unique('IDX_USER_APPLICATION_VARIABLE_VALUE_VARIABLE_USER_UNIQUE', [
+ 'applicationVariableId',
+ 'userWorkspaceId',
+])
+@Index('IDX_USER_APPLICATION_VARIABLE_VALUE_WORKSPACE_ID', ['workspaceId'])
+@Index('IDX_USER_APPLICATION_VARIABLE_VALUE_USER_WORKSPACE_ID', [
+ 'userWorkspaceId',
+])
+@Check(
+ 'CHK_userApplicationVariableValue_value_encrypted',
+ `"value" LIKE 'enc:v2:%'`,
+)
+@Check('CHK_userApplicationVariableValue_scope_user', `"scope" = 'USER'`)
+export class UserApplicationVariableValueEntity extends WorkspaceRelatedEntity {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({ nullable: false, type: 'uuid' })
+ applicationVariableId: string;
+
+ // Always USER: the foreign key on (applicationVariableId, scope) then lets
+ // the database refuse a member value on a WORKSPACE variable.
+ @Column({
+ nullable: false,
+ type: 'enum',
+ enum: APPLICATION_VARIABLE_SCOPES,
+ enumName: 'applicationVariable_scope_enum',
+ default: 'USER',
+ })
+ scope: ApplicationVariableScope;
+
+ @ManyToOne(() => ApplicationVariableEntity, { onDelete: 'CASCADE' })
+ @JoinColumn([
+ { name: 'applicationVariableId', referencedColumnName: 'id' },
+ { name: 'scope', referencedColumnName: 'scope' },
+ ])
+ applicationVariable: Relation<ApplicationVariableEntity>;
+
+ @Column({ nullable: false, type: 'uuid' })
+ userWorkspaceId: string;
+
+ @ManyToOne(() => UserWorkspaceEntity, { onDelete: 'CASCADE' })
+ @JoinColumn({ name: 'userWorkspaceId' })
+ userWorkspace: Relation<UserWorkspaceEntity>;
+
+ @Column({ nullable: false, type: 'text' })
+ value: EncryptedString;
+
+ @CreateDateColumn({ type: 'timestamptz' })
+ createdAt: Date;
+
+ @UpdateDateColumn({ type: 'timestamptz' })
+ updatedAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.resolver.ts
new file mode 100644
index 00000000000..406fac197a6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.resolver.ts
@@ -0,0 +1,103 @@
+import { UseFilters, UseGuards } from '@nestjs/common';
+import { Mutation, Query } from '@nestjs/graphql';
+
+import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { ApplicationExceptionFilter } from 'src/engine/core-modules/application/application-exception-filter';
+import { ApplicationVariableEntityExceptionFilter } from 'src/engine/core-modules/application/application-variable/application-variable-exception-filter';
+import { UserApplicationVariableValueService } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.service';
+import { UpdateMyUserApplicationVariableInput } from 'src/engine/core-modules/application/application-variable/dtos/update-my-user-application-variable.input';
+import { WorkspaceMemberApplicationVariablesDTO } from 'src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { ApplicationTargetArgs } from 'src/engine/decorators/auth/application-target-args.decorator';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { ApplicationTargetGuard } from 'src/engine/guards/application-target.guard';
+
+@UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: true,
+ workspaceAgnostic: false,
+ },
+ apiKey: true,
+ oauthClient: true,
+ application: true,
+ }),
+ NoPermissionGuard,
+)
+@MetadataResolver()
+@UseFilters(
+ ApplicationVariableEntityExceptionFilter,
+ ApplicationExceptionFilter,
+ AuthGraphqlApiExceptionFilter,
+)
+export class UserApplicationVariableValueResolver {
+ constructor(
+ private readonly userApplicationVariableValueService: UserApplicationVariableValueService,
+ ) {}
+
+ @Mutation(() => Boolean)
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: true,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ ApplicationTargetGuard,
+ )
+ async updateMyUserApplicationVariable(
+ @ApplicationTargetArgs<UpdateMyUserApplicationVariableInput>({
+ kind: 'applicationUniversalIdentifier',
+ idKey: 'applicationUniversalIdentifier',
+ requireApplicationRegistrationOwnership: false,
+ })
+ {
+ applicationUniversalIdentifier,
+ key,
+ value,
+ }: UpdateMyUserApplicationVariableInput,
+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ ): Promise<boolean> {
+ await this.userApplicationVariableValueService.updateMyUserApplicationVariable(
+ {
+ workspaceId,
+ applicationUniversalIdentifier,
+ userWorkspaceId,
+ key,
+ plainTextValue: value,
+ },
+ );
+
+ return true;
+ }
+
+ @Query(() => [WorkspaceMemberApplicationVariablesDTO])
+ async myUserApplicationVariables(
+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthApplication() callingApplication: FlatApplication,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ requestUserWorkspaceId: string | undefined,
+ ): Promise<WorkspaceMemberApplicationVariablesDTO[]> {
+ return this.userApplicationVariableValueService.findUserApplicationVariableValues(
+ {
+ workspaceId,
+ applicationId: callingApplication.id,
+ requestUserWorkspaceId,
+ },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.service.ts
new file mode 100644
index 00000000000..7f00acb0788
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/user-application-variable-value.service.ts
@@ -0,0 +1,343 @@
+import { Injectable } from '@nestjs/common';
+
+import groupBy from 'lodash.groupby';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { In } from 'typeorm';
+
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import {
+ ApplicationVariableEntityException,
+ ApplicationVariableEntityExceptionCode,
+} from 'src/engine/core-modules/application/application-variable/application-variable.exception';
+import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
+import { type WorkspaceMemberApplicationVariablesDTO } from 'src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto';
+import { UserApplicationVariableValueEntity } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.entity';
+import { toUserApplicationVariableValues } from 'src/engine/core-modules/application/application-variable/utils/to-user-application-variable-values.util';
+import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
+import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util';
+import { type FlatApplicationVariableMaps } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable-maps.type';
+import { type FlatApplicationVariable } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable.type';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+type ApplicationVariableTarget = {
+ workspaceId: string;
+ applicationId: string;
+};
+
+type GetEnvVariablesArgs = ApplicationVariableTarget & {
+ userWorkspaceId: string | undefined;
+ flatApplicationVariableMaps?: FlatApplicationVariableMaps;
+};
+
+@Injectable()
+export class UserApplicationVariableValueService {
+ constructor(
+ @InjectWorkspaceScopedRepository(UserApplicationVariableValueEntity)
+ private readonly userApplicationVariableValueRepository: WorkspaceScopedRepository<UserApplicationVariableValueEntity>,
+ @InjectWorkspaceScopedRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: WorkspaceScopedRepository<UserWorkspaceEntity>,
+ private readonly applicationVariableService: ApplicationVariableEntityService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly secretEncryptionService: SecretEncryptionService,
+ ) {}
+
+ async getServerEnvVariables({
+ workspaceId,
+ applicationId,
+ userWorkspaceId,
+ flatApplicationVariableMaps,
+ }: GetEnvVariablesArgs): Promise<Record<string, string>> {
+ const flatUserApplicationVariables =
+ await this.findFlatUserApplicationVariables({
+ workspaceId,
+ applicationId,
+ flatApplicationVariableMaps,
+ });
+
+ return this.toEnvVariables({
+ workspaceId,
+ userWorkspaceId,
+ flatUserApplicationVariables,
+ });
+ }
+
+ async getPublicEnvVariables({
+ workspaceId,
+ applicationId,
+ userWorkspaceId,
+ flatApplicationVariableMaps,
+ }: GetEnvVariablesArgs): Promise<Record<string, string>> {
+ const flatUserApplicationVariables = (
+ await this.findFlatUserApplicationVariables({
+ workspaceId,
+ applicationId,
+ flatApplicationVariableMaps,
+ })
+ ).filter(({ isSecret }) => !isSecret);
+
+ return this.toEnvVariables({
+ workspaceId,
+ userWorkspaceId,
+ flatUserApplicationVariables,
+ });
+ }
+
+ async findUserApplicationVariableValues({
+ workspaceId,
+ applicationId,
+ requestUserWorkspaceId,
+ }: ApplicationVariableTarget & {
+ requestUserWorkspaceId: string | undefined;
+ }): Promise<WorkspaceMemberApplicationVariablesDTO[]> {
+ const flatUserApplicationVariables =
+ await this.findFlatUserApplicationVariables({
+ workspaceId,
+ applicationId,
+ });
+
+ if (!isNonEmptyArray(flatUserApplicationVariables)) {
+ return [];
+ }
+
+ const [userWorkspaces, userValues, { flatWorkspaceMemberMaps }] =
+ await Promise.all([
+ this.userWorkspaceRepository.find(workspaceId, {
+ select: { id: true, userId: true },
+ where: isDefined(requestUserWorkspaceId)
+ ? { id: requestUserWorkspaceId }
+ : undefined,
+ }),
+ this.userApplicationVariableValueRepository.find(workspaceId, {
+ select: {
+ userWorkspaceId: true,
+ applicationVariableId: true,
+ value: true,
+ },
+ where: {
+ applicationVariableId: In(
+ flatUserApplicationVariables.map(({ id }) => id),
+ ),
+ ...(isDefined(requestUserWorkspaceId)
+ ? { userWorkspaceId: requestUserWorkspaceId }
+ : {}),
+ },
+ }),
+ this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatWorkspaceMemberMaps',
+ ]),
+ ]);
+
+ const userValuesByUserWorkspaceId = groupBy(userValues, 'userWorkspaceId');
+
+ return userWorkspaces.flatMap(({ id: userWorkspaceId, userId }) => {
+ const workspaceMemberId = resolveWorkspaceMemberIdForUser({
+ userId,
+ flatWorkspaceMemberMaps,
+ });
+
+ if (!isDefined(workspaceMemberId)) {
+ return [];
+ }
+
+ return [
+ {
+ userWorkspaceId,
+ workspaceMemberId,
+ variables: toUserApplicationVariableValues({
+ flatUserApplicationVariables,
+ userValues: userValuesByUserWorkspaceId[userWorkspaceId] ?? [],
+ shouldMaskSecret: isDefined(requestUserWorkspaceId),
+ getDisplayValue: ({ value, isSecret }) =>
+ this.applicationVariableService.getDisplayValue({
+ value,
+ workspaceId,
+ isSecret,
+ }),
+ }),
+ },
+ ];
+ });
+ }
+
+ async updateMyUserApplicationVariable({
+ workspaceId,
+ applicationUniversalIdentifier,
+ userWorkspaceId,
+ key,
+ plainTextValue,
+ }: {
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ userWorkspaceId: string;
+ key: string;
+ plainTextValue: PlaintextString;
+ }): Promise<void> {
+ const applicationId = await this.findApplicationIdOrThrow({
+ workspaceId,
+ applicationUniversalIdentifier,
+ });
+
+ const flatApplicationVariable =
+ await this.findFlatUserApplicationVariableOrThrow({
+ workspaceId,
+ applicationId,
+ key,
+ });
+
+ await this.userApplicationVariableValueRepository.upsert(
+ workspaceId,
+ {
+ applicationVariableId: flatApplicationVariable.id,
+ userWorkspaceId,
+ value: this.secretEncryptionService.encryptVersioned(plainTextValue, {
+ workspaceId,
+ }),
+ },
+ ['applicationVariableId', 'userWorkspaceId'],
+ );
+ }
+
+ private async toEnvVariables({
+ workspaceId,
+ userWorkspaceId,
+ flatUserApplicationVariables,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string | undefined;
+ flatUserApplicationVariables: FlatApplicationVariable[];
+ }): Promise<Record<string, string>> {
+ if (
+ !isDefined(userWorkspaceId) ||
+ !isNonEmptyArray(flatUserApplicationVariables)
+ ) {
+ return {};
+ }
+
+ const userValues = await this.findUserValues({
+ workspaceId,
+ userWorkspaceId,
+ flatUserApplicationVariables,
+ });
+
+ return Object.fromEntries(
+ toUserApplicationVariableValues({
+ flatUserApplicationVariables,
+ userValues,
+ shouldMaskSecret: false,
+ getDisplayValue: ({ value, isSecret }) =>
+ this.applicationVariableService.getDisplayValue({
+ value,
+ workspaceId,
+ isSecret,
+ }),
+ }).map(({ key, value }) => [key, value]),
+ );
+ }
+
+ private async findUserValues({
+ workspaceId,
+ userWorkspaceId,
+ flatUserApplicationVariables,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ flatUserApplicationVariables: FlatApplicationVariable[];
+ }): Promise<
+ Pick<
+ UserApplicationVariableValueEntity,
+ 'applicationVariableId' | 'value'
+ >[]
+ > {
+ return this.userApplicationVariableValueRepository.find(workspaceId, {
+ select: { applicationVariableId: true, value: true },
+ where: {
+ userWorkspaceId,
+ applicationVariableId: In(
+ flatUserApplicationVariables.map(({ id }) => id),
+ ),
+ },
+ });
+ }
+
+ private async findApplicationIdOrThrow({
+ workspaceId,
+ applicationUniversalIdentifier,
+ }: {
+ workspaceId: string;
+ applicationUniversalIdentifier: string;
+ }): Promise<string> {
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+
+ const flatApplication = findActiveFlatApplicationByUniversalIdentifier(
+ flatApplicationMaps,
+ applicationUniversalIdentifier,
+ );
+
+ if (!isDefined(flatApplication)) {
+ throw new ApplicationException(
+ `Application ${applicationUniversalIdentifier} not found`,
+ ApplicationExceptionCode.APPLICATION_NOT_FOUND,
+ );
+ }
+
+ return flatApplication.id;
+ }
+
+ private async findFlatUserApplicationVariables({
+ workspaceId,
+ applicationId,
+ flatApplicationVariableMaps,
+ }: ApplicationVariableTarget & {
+ flatApplicationVariableMaps?: FlatApplicationVariableMaps;
+ }): Promise<FlatApplicationVariable[]> {
+ return (
+ await this.applicationVariableService.findFlatApplicationVariables({
+ workspaceId,
+ applicationId,
+ flatApplicationVariableMaps,
+ })
+ ).filter(({ scope }) => scope === 'USER');
+ }
+
+ private async findFlatUserApplicationVariableOrThrow({
+ workspaceId,
+ applicationId,
+ key,
+ }: ApplicationVariableTarget & {
+ key: string;
+ }): Promise<FlatApplicationVariable> {
+ const flatApplicationVariable = (
+ await this.applicationVariableService.findFlatApplicationVariables({
+ workspaceId,
+ applicationId,
+ })
+ ).find((flatApplicationVariable) => flatApplicationVariable.key === key);
+
+ if (!isDefined(flatApplicationVariable)) {
+ throw new ApplicationVariableEntityException(
+ `Application variable with key ${key} not found`,
+ ApplicationVariableEntityExceptionCode.APPLICATION_VARIABLE_NOT_FOUND,
+ );
+ }
+
+ if (flatApplicationVariable.scope !== 'USER') {
+ throw new ApplicationVariableEntityException(
+ `Application variable with key ${key} is not a user variable`,
+ ApplicationVariableEntityExceptionCode.INVALID_APPLICATION_VARIABLE_INPUT,
+ );
+ }
+
+ return flatApplicationVariable;
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/__tests__/to-user-application-variable-values.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/__tests__/to-user-application-variable-values.util.spec.ts
new file mode 100644
index 00000000000..06d1b89d4c9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/__tests__/to-user-application-variable-values.util.spec.ts
@@ -0,0 +1,101 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { toUserApplicationVariableValues } from 'src/engine/core-modules/application/application-variable/utils/to-user-application-variable-values.util';
+import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
+import { type FlatApplicationVariable } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable.type';
+
+const buildFlatUserApplicationVariable = ({
+ id,
+ key,
+ isSecret = false,
+ defaultValue = null,
+}: {
+ id: string;
+ key: string;
+ isSecret?: boolean;
+ defaultValue?: string | null;
+}) =>
+ ({
+ id,
+ key,
+ label: key,
+ description: '',
+ type: FieldMetadataType.TEXT,
+ options: null,
+ isSecret,
+ isRequired: false,
+ isDeprecated: false,
+ defaultValue,
+ }) satisfies Partial<FlatApplicationVariable>;
+
+const FLAT_USER_APPLICATION_VARIABLES = [
+ buildFlatUserApplicationVariable({
+ id: 'record-my-meetings-id',
+ key: 'RECORD_MY_MEETINGS',
+ defaultValue: 'off',
+ }),
+ buildFlatUserApplicationVariable({
+ id: 'language-id',
+ key: 'LANGUAGE',
+ defaultValue: 'en',
+ }),
+ buildFlatUserApplicationVariable({ id: 'nickname-id', key: 'NICKNAME' }),
+ buildFlatUserApplicationVariable({
+ id: 'personal-api-key-id',
+ key: 'PERSONAL_API_KEY',
+ isSecret: true,
+ }),
+];
+
+const USER_VALUES = [
+ {
+ applicationVariableId: 'record-my-meetings-id',
+ value: 'enc:on' as EncryptedString,
+ },
+ {
+ applicationVariableId: 'personal-api-key-id',
+ value: 'enc:key' as EncryptedString,
+ },
+];
+
+const getDisplayValue = ({
+ value,
+ isSecret,
+}: {
+ value: EncryptedString;
+ isSecret: boolean;
+}) => (isSecret ? `masked ${value}` : `plaintext of ${value}`);
+
+describe('toUserApplicationVariableValues', () => {
+ it('should use the member value, else the default, else an empty string', () => {
+ const values = toUserApplicationVariableValues({
+ flatUserApplicationVariables: FLAT_USER_APPLICATION_VARIABLES,
+ userValues: USER_VALUES,
+ shouldMaskSecret: false,
+ getDisplayValue,
+ });
+
+ expect(values.map(({ key, value }) => [key, value])).toEqual([
+ ['RECORD_MY_MEETINGS', 'plaintext of enc:on'],
+ ['LANGUAGE', 'en'],
+ ['NICKNAME', ''],
+ ['PERSONAL_API_KEY', 'plaintext of enc:key'],
+ ]);
+ });
+
+ it('should mask secrets only when asked to', () => {
+ const values = toUserApplicationVariableValues({
+ flatUserApplicationVariables: FLAT_USER_APPLICATION_VARIABLES,
+ userValues: USER_VALUES,
+ shouldMaskSecret: true,
+ getDisplayValue,
+ });
+
+ expect(values.map(({ key, value }) => [key, value])).toEqual([
+ ['RECORD_MY_MEETINGS', 'plaintext of enc:on'],
+ ['LANGUAGE', 'en'],
+ ['NICKNAME', ''],
+ ['PERSONAL_API_KEY', 'masked enc:key'],
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/to-user-application-variable-values.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/to-user-application-variable-values.util.ts
new file mode 100644
index 00000000000..2f3eb2ebcac
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/utils/to-user-application-variable-values.util.ts
@@ -0,0 +1,67 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UserApplicationVariableValueDTO } from 'src/engine/core-modules/application/application-variable/dtos/user-application-variable-value.dto';
+import { type UserApplicationVariableValueEntity } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.entity';
+import { type FlatApplicationVariable } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable.type';
+
+export const toUserApplicationVariableValues = ({
+ flatUserApplicationVariables,
+ userValues,
+ shouldMaskSecret,
+ getDisplayValue,
+}: {
+ flatUserApplicationVariables: Pick<
+ FlatApplicationVariable,
+ | 'id'
+ | 'key'
+ | 'label'
+ | 'description'
+ | 'type'
+ | 'options'
+ | 'isSecret'
+ | 'isRequired'
+ | 'isDeprecated'
+ | 'defaultValue'
+ >[];
+ userValues: Pick<
+ UserApplicationVariableValueEntity,
+ 'applicationVariableId' | 'value'
+ >[];
+ shouldMaskSecret: boolean;
+ getDisplayValue: (
+ userValue: Pick<UserApplicationVariableValueEntity, 'value'> & {
+ isSecret: boolean;
+ },
+ ) => string;
+}): UserApplicationVariableValueDTO[] => {
+ const userValueByApplicationVariableId = new Map(
+ userValues.map(({ applicationVariableId, value }) => [
+ applicationVariableId,
+ value,
+ ]),
+ );
+
+ return flatUserApplicationVariables.map((flatApplicationVariable) => {
+ const userValue = userValueByApplicationVariableId.get(
+ flatApplicationVariable.id,
+ );
+
+ return {
+ key: flatApplicationVariable.key,
+ label: flatApplicationVariable.label,
+ description: flatApplicationVariable.description,
+ type: flatApplicationVariable.type,
+ options: flatApplicationVariable.options,
+ isSecret: flatApplicationVariable.isSecret,
+ isRequired: flatApplicationVariable.isRequired,
+ isDeprecated: flatApplicationVariable.isDeprecated,
+ // Secrets have no default, so the fallback never needs masking.
+ value: isDefined(userValue)
+ ? getDisplayValue({
+ value: userValue,
+ isSecret: flatApplicationVariable.isSecret && shouldMaskSecret,
+ })
+ : (flatApplicationVariable.defaultValue ?? ''),
+ };
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 2923ce223a2..b2f91a10635 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -27,6 +27,7 @@ import {
import { isBillingExemptApplication } from 'src/engine/core-modules/application/application-marketplace/utils/is-billing-exempt-application.util';
import { ApplicationRegistrationVariableEntity } from 'src/engine/core-modules/application/application-registration-variable/application-registration-variable.entity';
import { ApplicationStopService } from 'src/engine/core-modules/application/application-stop/application-stop.service';
+import { UserApplicationVariableValueService } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.service';
import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
import { type FlatApplicationVariableMaps } from 'src/engine/metadata-modules/flat-application-variable/types/flat-application-variable-maps.type';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
@@ -41,7 +42,6 @@ import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs
import { parseApplicationLogLines } from 'src/engine/core-modules/event-logs/producers/application-log/parse-application-log-lines';
import { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
import { buildLogicFunctionExecutionUsage } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util';
-import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import {
@@ -53,6 +53,7 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -106,6 +107,7 @@ export class LogicFunctionExecutorService {
private readonly applicationTokenService: ApplicationTokenService,
private readonly secretEncryptionService: SecretEncryptionService,
private readonly applicationVariableService: ApplicationVariableEntityService,
+ private readonly userApplicationVariableValueService: UserApplicationVariableValueService,
private readonly subscriptionService: SubscriptionService,
private readonly eventLogLiveService: EventLogLiveService,
private readonly eventLogEmitterService: EventLogEmitterService,
@@ -438,10 +440,21 @@ export class LogicFunctionExecutorService {
applicationId: flatApplication.id,
flatApplicationVariableMaps,
});
+ const userVariables =
+ await this.userApplicationVariableValueService.getServerEnvVariables({
+ workspaceId,
+ applicationId: flatApplication.id,
+ flatApplicationVariableMaps,
+ userWorkspaceId:
+ hasTriggeringPerson && !isDefined(workspaceDeletionRequestTimestamp)
+ ? userWorkspaceId
+ : undefined,
+ });
return {
...serverVariables,
...workspaceVariables,
+ ...userVariables,
[DEFAULT_API_URL_NAME]: baseUrl ?? '',
// Falls back to the application so cron schedules and install hooks work with nobody triggering.
[DEFAULT_APP_ACCESS_TOKEN_NAME]: (
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts b/packages/twenty-server/src/engine/core-modules/user/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
similarity index 91%
rename from packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
rename to packages/twenty-server/src/engine/core-modules/user/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
index 5e9f19b7e22..3be8e939d82 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/user/utils/__tests__/resolve-workspace-member-id-for-user.util.spec.ts
@@ -1,4 +1,4 @@
-import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util';
const buildMaps = ({ deletedAt }: { deletedAt?: string } = {}) => ({
byId: { 'workspace-member-1': { deletedAt: deletedAt ?? null } },
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util.ts b/packages/twenty-server/src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util.ts
similarity index 100%
rename from packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util.ts
rename to packages/twenty-server/src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util.ts
diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
index a4ee049692a..2c078fa9d75 100644
--- a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
@@ -18,6 +18,7 @@ import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorato
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { ApplicationExceptionFilter } from 'src/engine/core-modules/application/application-exception-filter';
import { ApplicationTokenPairDTO } from 'src/engine/core-modules/application/application-oauth/dtos/application-token-pair.dto';
+import { UserApplicationVariableValueService } from 'src/engine/core-modules/application/application-variable/user-application-variable-value.service';
import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { canCallerReachApplication } from 'src/engine/core-modules/application/utils/can-caller-reach-application.util';
@@ -68,6 +69,7 @@ export class FrontComponentResolver {
@Inject(ApplicationTokenService)
private readonly applicationTokenService: ApplicationTokenService,
private readonly applicationVariableService: ApplicationVariableEntityService,
+ private readonly userApplicationVariableValueService: UserApplicationVariableValueService,
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
@@ -176,9 +178,10 @@ export class FrontComponentResolver {
})
: undefined,
isDefined(selectedFields.applicationVariables)
- ? this.applicationVariableService.getPublicEnvVariables({
+ ? this.getPublicApplicationVariables({
workspaceId: workspace.id,
applicationId: dto.applicationId,
+ userWorkspaceId,
})
: undefined,
]);
@@ -302,4 +305,28 @@ export class FrontComponentResolver {
return fromFlatFrontComponentToFrontComponentDto(flatFrontComponent);
}
+
+ private async getPublicApplicationVariables({
+ workspaceId,
+ applicationId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ userWorkspaceId: string;
+ }): Promise<Record<string, string>> {
+ const [workspaceVariables, userVariables] = await Promise.all([
+ this.applicationVariableService.getPublicEnvVariables({
+ workspaceId,
+ applicationId,
+ }),
+ this.userApplicationVariableValueService.getPublicEnvVariables({
+ workspaceId,
+ applicationId,
+ userWorkspaceId,
+ }),
+ ]);
+
+ return { ...workspaceVariables, ...userVariables };
+ }
}
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index b499f7b42fa..e2581c036bb 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -543,6 +543,8 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"UsageLimitResolver.usageQuotaScopeConsumption {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"UsageLimitResolver.usageQuotasWithConsumption {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"UsageResolver.getUsageAnalytics {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "UserApplicationVariableValueResolver.myUserApplicationVariables {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "UserApplicationVariableValueResolver.updateMyUserApplicationVariable {"applicationTarget":{"idKey":"applicationUniversalIdentifier","kind":"applicationUniversalIdentifier","requireApplicationRegistrationOwnership":false,"source":"graphqlArgs"},"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"UserResolver.currentUser {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":true}]}",
"UserResolver.deleteUser {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":true}]}",
"UserResolver.deleteUserFromWorkspace {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":true}]}",
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-user-application-variable-values.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-user-application-variable-values.integration-spec.ts.snap
new file mode 100644
index 00000000000..bfd1f37c491
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-user-application-variable-values.integration-spec.ts.snap
@@ -0,0 +1,57 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`User application variable values should fail should refuse a key the application does not declare 1`] = `
+{
+ "extensions": {
+ "code": "NOT_FOUND",
+ "subCode": "APPLICATION_VARIABLE_NOT_FOUND",
+ "userFriendlyMessage": "Application variable not found.",
+ },
+ "message": "Application variable with key UNDECLARED_VARIABLE not found",
+ "name": "NotFoundError",
+}
+`;
+
+exports[`User application variable values should fail should refuse an application that is not installed 1`] = `
+{
+ "extensions": {
+ "code": "NOT_FOUND",
+ "subCode": "APPLICATION_NOT_FOUND",
+ "userFriendlyMessage": "Application not found.",
+ },
+ "message": "Application 8f7c1e0a-4b2d-4c3e-9a1f-0d2e3c4b5a69 not found",
+ "name": "NotFoundError",
+}
+`;
+
+exports[`User application variable values should fail should refuse an application token writing a member value of its own application 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`User application variable values should fail should refuse to list every member value from a session 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "An error occurred.",
+ },
+ "message": "This endpoint requires an APPLICATION_ACCESS token.",
+}
+`;
+
+exports[`User application variable values should fail should refuse to set a member value on a workspace variable 1`] = `
+{
+ "extensions": {
+ "code": "BAD_USER_INPUT",
+ "subCode": "INVALID_APPLICATION_VARIABLE_INPUT",
+ "userFriendlyMessage": "Invalid application variable input.",
+ },
+ "message": "Application variable with key RECORD_ALL_MEETINGS is not a user variable",
+ "name": "UserInputError",
+}
+`;
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts
new file mode 100644
index 00000000000..8a86d3267f0
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-user-application-variable-values.integration-spec.ts
@@ -0,0 +1,134 @@
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { myUserApplicationVariables } from 'test/integration/metadata/suites/application/utils/my-user-application-variables.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateMyUserApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-my-user-application-variable.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+
+const NOT_INSTALLED_APPLICATION_UNIVERSAL_IDENTIFIER =
+ '8f7c1e0a-4b2d-4c3e-9a1f-0d2e3c4b5a69';
+
+describe('User application variable values should fail', () => {
+ let userVariableApplication: ApplicationWithVariable;
+ let workspaceVariableApplication: ApplicationWithVariable;
+ let janeApplicationToken: string;
+
+ beforeAll(async () => {
+ userVariableApplication = await setupApplicationWithVariable({
+ name: 'User Variable Application',
+ variableKey: 'RECORD_MY_MEETINGS',
+ variableScope: 'USER',
+ });
+ workspaceVariableApplication = await setupApplicationWithVariable({
+ name: 'Workspace Variable Application',
+ variableKey: 'RECORD_ALL_MEETINGS',
+ });
+
+ const janeApplicationTokenPair =
+ await generateAppleAdminApplicationTokenPair({
+ applicationId: userVariableApplication.id,
+ });
+
+ janeApplicationToken =
+ janeApplicationTokenPair.applicationAccessToken.token;
+ }, 120000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ userVariableApplication.universalIdentifier,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ workspaceVariableApplication.universalIdentifier,
+ });
+ });
+
+ it('should refuse to set a member value on a workspace variable', async () => {
+ const { errors } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier:
+ workspaceVariableApplication.universalIdentifier,
+ key: workspaceVariableApplication.variableKey,
+ value: 'mine',
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse a key the application does not declare', async () => {
+ const { errors } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier:
+ userVariableApplication.universalIdentifier,
+ key: 'UNDECLARED_VARIABLE',
+ value: 'mine',
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse an application that is not installed', async () => {
+ const { errors } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier:
+ NOT_INSTALLED_APPLICATION_UNIVERSAL_IDENTIFIER,
+ key: userVariableApplication.variableKey,
+ value: 'mine',
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse an application token writing a member value of its own application', async () => {
+ const { errors } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier:
+ userVariableApplication.universalIdentifier,
+ key: userVariableApplication.variableKey,
+ value: 'mine',
+ },
+ token: janeApplicationToken,
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse to list every member value from a session', async () => {
+ const { errors } = await myUserApplicationVariables({
+ input: {},
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse a member value on a workspace variable in the database', async () => {
+ await expect(
+ global.testDataSource.query(
+ `INSERT INTO "core"."userApplicationVariableValue"
+ ("workspaceId", "applicationVariableId", "userWorkspaceId", "value")
+ SELECT "workspaceId", "id", $1, 'enc:v2:mine'
+ FROM "core"."applicationVariable"
+ WHERE "applicationId" = $2 AND "key" = $3`,
+ [
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ workspaceVariableApplication.id,
+ workspaceVariableApplication.variableKey,
+ ],
+ ),
+ ).rejects.toThrow('violates foreign key constraint');
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-secrets.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-secrets.integration-spec.ts
new file mode 100644
index 00000000000..fb834d3fefa
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-secrets.integration-spec.ts
@@ -0,0 +1,177 @@
+import { myUserApplicationVariables } from 'test/integration/metadata/suites/application/utils/my-user-application-variables.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateMyUserApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-my-user-application-variable.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+
+import { SECRET_APPLICATION_VARIABLE_MASK } from 'src/engine/core-modules/application/application-variable/constants/secret-application-variable-mask.constant';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+describe('Secret user application variable values should succeed', () => {
+ let application: ApplicationWithVariable;
+ let applicationToken: string;
+ let janeApplicationToken: string;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithVariable({
+ name: 'Secret User Variable Application',
+ variableKey: 'API_KEY',
+ variableScope: 'USER',
+ isSecret: true,
+ });
+
+ const [applicationTokenPair, janeApplicationTokenPair] = await Promise.all([
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ generateAppleAdminApplicationTokenPair({
+ applicationId: application.id,
+ }),
+ ]);
+
+ applicationToken = applicationTokenPair.applicationAccessToken.token;
+ janeApplicationToken =
+ janeApplicationTokenPair.applicationAccessToken.token;
+ }, 120000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it('should leave an unset personal secret empty', async () => {
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ const jonyValues = data.myUserApplicationVariables.find(
+ ({ userWorkspaceId }) =>
+ userWorkspaceId === USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ );
+
+ expect(jonyValues?.variables).toEqual([
+ { key: application.variableKey, value: '' },
+ ]);
+ });
+
+ it('should encrypt a member secret at rest', async () => {
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: application.universalIdentifier,
+ key: application.variableKey,
+ value: 'jony-key',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const storedValues: { value: string }[] = await global.testDataSource.query(
+ `SELECT "userValue"."value"
+ FROM "core"."userApplicationVariableValue" "userValue"
+ JOIN "core"."applicationVariable" "variable"
+ ON "variable"."id" = "userValue"."applicationVariableId"
+ WHERE "variable"."applicationId" = $1`,
+ [application.id],
+ );
+
+ expect(storedValues).toHaveLength(1);
+ expect(storedValues[0].value).toMatch(/^enc:v2:/);
+ expect(storedValues[0].value).not.toContain('jony-key');
+ });
+
+ it('should mask the own secret for a token a person is behind', async () => {
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: application.universalIdentifier,
+ key: application.variableKey,
+ value: 'jane-key',
+ },
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: janeApplicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual([
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ variables: [
+ {
+ key: application.variableKey,
+ value: SECRET_APPLICATION_VARIABLE_MASK,
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('should give a token no person is behind the real secret of every member', async () => {
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual(
+ expect.arrayContaining([
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ variables: [{ key: application.variableKey, value: 'jane-key' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ variables: [{ key: application.variableKey, value: 'jony-key' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.PHIL,
+ variables: [{ key: application.variableKey, value: '' }],
+ },
+ ]),
+ );
+ });
+
+ it('should leave a cleared personal secret empty', async () => {
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: application.universalIdentifier,
+ key: application.variableKey,
+ value: '',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ const jonyValues = data.myUserApplicationVariables.find(
+ ({ userWorkspaceId }) =>
+ userWorkspaceId === USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ );
+
+ expect(jonyValues?.variables).toEqual([
+ { key: application.variableKey, value: '' },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-values.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-values.integration-spec.ts
new file mode 100644
index 00000000000..252ce230953
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-user-application-variable-values.integration-spec.ts
@@ -0,0 +1,288 @@
+import { myUserApplicationVariables } from 'test/integration/metadata/suites/application/utils/my-user-application-variables.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateMyUserApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-my-user-application-variable.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+describe('User application variable values should succeed', () => {
+ let application: ApplicationWithVariable;
+ let otherApplication: ApplicationWithVariable;
+ let defaultApplication: ApplicationWithVariable;
+ let applicationToken: string;
+ let defaultApplicationToken: string;
+ let janeApplicationToken: string;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithVariable({
+ name: 'User Variable Application',
+ variableKey: 'RECORD_MY_MEETINGS',
+ variableScope: 'USER',
+ });
+ otherApplication = await setupApplicationWithVariable({
+ name: 'Other User Variable Application',
+ variableKey: 'SHARE_MY_RECORDINGS',
+ variableScope: 'USER',
+ });
+ defaultApplication = await setupApplicationWithVariable({
+ name: 'Default User Variable Application',
+ variableKey: 'TRANSCRIBE_MY_MEETINGS',
+ variableScope: 'USER',
+ value: 'true',
+ });
+
+ const [
+ applicationTokenPair,
+ janeApplicationTokenPair,
+ defaultApplicationTokenPair,
+ ] = await Promise.all([
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ generateAppleAdminApplicationTokenPair({
+ applicationId: application.id,
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: defaultApplication.id,
+ }),
+ ]);
+
+ applicationToken = applicationTokenPair.applicationAccessToken.token;
+ defaultApplicationToken =
+ defaultApplicationTokenPair.applicationAccessToken.token;
+ janeApplicationToken =
+ janeApplicationTokenPair.applicationAccessToken.token;
+ }, 120000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: otherApplication.universalIdentifier,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: defaultApplication.universalIdentifier,
+ });
+ });
+
+ it('should give a member the declaration and no value until they set their own', async () => {
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ gqlFields: `
+ userWorkspaceId
+ variables {
+ key
+ label
+ description
+ type
+ options
+ isSecret
+ isRequired
+ isDeprecated
+ value
+ }
+ `,
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual(
+ expect.arrayContaining([
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
+ variables: [
+ {
+ key: application.variableKey,
+ label: '',
+ description: '',
+ type: 'TEXT',
+ options: null,
+ isSecret: false,
+ isRequired: false,
+ isDeprecated: false,
+ value: '',
+ },
+ ],
+ },
+ ]),
+ );
+ });
+
+ it('should let a member without the applications permission set their own value', async () => {
+ const { data: updateData } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: application.universalIdentifier,
+ key: application.variableKey,
+ value: 'jony',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ expect(updateData.updateMyUserApplicationVariable).toBe(true);
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ const jonyValues = data.myUserApplicationVariables.find(
+ ({ userWorkspaceId }) =>
+ userWorkspaceId === USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ );
+
+ expect(jonyValues?.variables).toEqual([
+ { key: application.variableKey, value: 'jony' },
+ ]);
+ });
+
+ it('should list only the own values for a token a person is behind', async () => {
+ const { data: updateData } = await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: application.universalIdentifier,
+ key: application.variableKey,
+ value: 'jane',
+ },
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ expect(updateData.updateMyUserApplicationVariable).toBe(true);
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: janeApplicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual([
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ variables: [{ key: application.variableKey, value: 'jane' }],
+ },
+ ]);
+ });
+
+ it('should list the values of every member for a token no person is behind', async () => {
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual(
+ expect.arrayContaining([
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ variables: [{ key: application.variableKey, value: 'jane' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ variables: [{ key: application.variableKey, value: 'jony' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.PHIL,
+ variables: [{ key: application.variableKey, value: '' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.TIM,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ variables: [{ key: application.variableKey, value: '' }],
+ },
+ {
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.SCOTT,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.SCOTT,
+ variables: [{ key: application.variableKey, value: '' }],
+ },
+ ]),
+ );
+ });
+
+ it('should leave the values of another application out of the list', async () => {
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: otherApplication.universalIdentifier,
+ key: otherApplication.variableKey,
+ value: 'jony-other',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: applicationToken,
+ expectToFail: false,
+ });
+
+ const jonyValues = data.myUserApplicationVariables.find(
+ ({ userWorkspaceId }) =>
+ userWorkspaceId === USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ );
+
+ expect(jonyValues?.variables).toEqual([
+ { key: application.variableKey, value: 'jony' },
+ ]);
+ });
+
+ it('should give a member the default until they set their own', async () => {
+ const { data: defaultData } = await myUserApplicationVariables({
+ input: {},
+ token: defaultApplicationToken,
+ expectToFail: false,
+ });
+
+ expect(defaultData.myUserApplicationVariables).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ variables: [{ key: defaultApplication.variableKey, value: 'true' }],
+ }),
+ ]),
+ );
+
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: defaultApplication.universalIdentifier,
+ key: defaultApplication.variableKey,
+ value: 'false',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const { data } = await myUserApplicationVariables({
+ input: {},
+ token: defaultApplicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.myUserApplicationVariables).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ variables: [{ key: defaultApplication.variableKey, value: 'false' }],
+ }),
+ expect.objectContaining({
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
+ variables: [{ key: defaultApplication.variableKey, value: 'true' }],
+ }),
+ ]),
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables-query-factory.util.ts
new file mode 100644
index 00000000000..860ad37a052
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables-query-factory.util.ts
@@ -0,0 +1,24 @@
+import gql from 'graphql-tag';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+
+const DEFAULT_MY_USER_APPLICATION_VARIABLES_GQL_FIELDS = `
+ userWorkspaceId
+ workspaceMemberId
+ variables {
+ key
+ value
+ }
+`;
+
+export const myUserApplicationVariablesQueryFactory = ({
+ gqlFields = DEFAULT_MY_USER_APPLICATION_VARIABLES_GQL_FIELDS,
+}: PerformMetadataQueryParams<Record<string, never>>) => ({
+ query: gql`
+ query MyUserApplicationVariables {
+ myUserApplicationVariables {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {},
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables.util.ts
new file mode 100644
index 00000000000..f7235dbc1dc
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/my-user-application-variables.util.ts
@@ -0,0 +1,42 @@
+import { myUserApplicationVariablesQueryFactory } from 'test/integration/metadata/suites/application/utils/my-user-application-variables-query-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+import { type WorkspaceMemberApplicationVariablesDTO } from 'src/engine/core-modules/application/application-variable/dtos/workspace-member-application-variables.dto';
+
+export const myUserApplicationVariables = async ({
+ input,
+ gqlFields,
+ expectToFail = false,
+ token,
+}: PerformMetadataQueryParams<Record<string, never>>): CommonResponseBody<{
+ myUserApplicationVariables: WorkspaceMemberApplicationVariablesDTO[];
+}> => {
+ const graphqlOperation = myUserApplicationVariablesQueryFactory({
+ input,
+ gqlFields,
+ });
+
+ const response = await makeMetadataApiRequest(graphqlOperation, token);
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage:
+ 'Listing user application variable values should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage:
+ 'Listing user application variable values has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-variable.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-variable.util.ts
index 852f1c83ec7..03711352fde 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-variable.util.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-variable.util.ts
@@ -2,8 +2,12 @@ import { buildBaseManifest } from 'test/integration/metadata/suites/application/
import { findOneApplication } from 'test/integration/metadata/suites/application/utils/find-one-application.util';
import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
-import { type ObjectPermissionManifest } from 'twenty-shared/application';
+import {
+ type ApplicationVariableScope,
+ type ObjectPermissionManifest,
+} from 'twenty-shared/application';
import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
import { v4 as uuidv4 } from 'uuid';
export type ApplicationWithVariable = {
@@ -13,18 +17,22 @@ export type ApplicationWithVariable = {
variableKey: string;
};
-// Syncs an application whose default role holds APPLICATIONS by default, as the
-// official apps with a settings component do, and declares one non-secret
-// variable. The flags are a parameter so a caller can give the application role
-// a workspace permission instead.
+// Application settings components need APPLICATIONS by default; tests can
+// override the permissions to exercise narrower access.
export const setupApplicationWithVariable = async ({
name,
variableKey,
+ variableScope,
+ isSecret = false,
+ value = variableScope === 'USER' ? undefined : 'initial',
permissionFlagUniversalIdentifiers = [SystemPermissionFlag.APPLICATIONS],
objectPermissions = [],
}: {
name: string;
variableKey: string;
+ variableScope?: ApplicationVariableScope;
+ isSecret?: boolean;
+ value?: string;
permissionFlagUniversalIdentifiers?: string[];
// An application-owned role can only be granted object permissions through
// its own manifest; upserting them afterwards is refused.
@@ -53,7 +61,9 @@ export const setupApplicationWithVariable = async ({
applicationVariables: {
[variableKey]: {
universalIdentifier: uuidv4(),
- value: 'initial',
+ scope: variableScope,
+ ...(isSecret ? { isSecret: true } : {}),
+ ...(isSecret || !isDefined(value) ? {} : { value }),
},
},
packageJsonChecksum: null,
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable-query-factory.util.ts
new file mode 100644
index 00000000000..b63bbd29fc8
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable-query-factory.util.ts
@@ -0,0 +1,31 @@
+import gql from 'graphql-tag';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+
+export type UpdateMyUserApplicationVariableFactoryInput = {
+ applicationUniversalIdentifier: string;
+ key: string;
+ value: string;
+};
+
+export const updateMyUserApplicationVariableQueryFactory = ({
+ input,
+}: PerformMetadataQueryParams<UpdateMyUserApplicationVariableFactoryInput>) => ({
+ query: gql`
+ mutation UpdateMyUserApplicationVariable(
+ $applicationUniversalIdentifier: String!
+ $key: String!
+ $value: String!
+ ) {
+ updateMyUserApplicationVariable(
+ applicationUniversalIdentifier: $applicationUniversalIdentifier
+ key: $key
+ value: $value
+ )
+ }
+ `,
+ variables: {
+ applicationUniversalIdentifier: input.applicationUniversalIdentifier,
+ key: input.key,
+ value: input.value,
+ },
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable.util.ts
new file mode 100644
index 00000000000..3a72eb94fb0
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-my-user-application-variable.util.ts
@@ -0,0 +1,41 @@
+import {
+ type UpdateMyUserApplicationVariableFactoryInput,
+ updateMyUserApplicationVariableQueryFactory,
+} from 'test/integration/metadata/suites/application/utils/update-my-user-application-variable-query-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+export const updateMyUserApplicationVariable = async ({
+ input,
+ expectToFail = false,
+ token,
+}: PerformMetadataQueryParams<UpdateMyUserApplicationVariableFactoryInput>): CommonResponseBody<{
+ updateMyUserApplicationVariable: boolean;
+}> => {
+ const graphqlOperation = updateMyUserApplicationVariableQueryFactory({
+ input,
+ });
+
+ const response = await makeMetadataApiRequest(graphqlOperation, token);
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage:
+ 'Updating my application variable should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage:
+ 'Updating my application variable has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};
diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-variables.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-variables.integration-spec.ts
index 5f0d83b1829..71c16bb04c9 100644
--- a/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-variables.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-variables.integration-spec.ts
@@ -2,6 +2,7 @@ import { buildBaseManifest } from 'test/integration/metadata/suites/application/
import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { updateMyUserApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-my-user-application-variable.util';
import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
import { findFrontComponent } from 'test/integration/metadata/suites/front-component/utils/find-front-component.util';
import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';
@@ -15,9 +16,11 @@ const FRONT_COMPONENT_ID = uuidv4();
const PUBLIC_VARIABLE_ID = uuidv4();
const SECRET_VARIABLE_ID = uuidv4();
const USER_VARIABLE_ID = uuidv4();
+const USER_SECRET_VARIABLE_ID = uuidv4();
const BUILT_COMPONENT_PATH = 'src/front-components/variables.mjs';
const PUBLIC_VARIABLE_VALUE = 'pk.public-access-token';
+const USER_VARIABLE_DEFAULT_VALUE = 'off';
const buildManifest = (): Manifest => {
const baseManifest = buildBaseManifest({
@@ -40,6 +43,12 @@ const buildManifest = (): Manifest => {
},
RECORD_MY_MEETINGS: {
universalIdentifier: USER_VARIABLE_ID,
+ value: USER_VARIABLE_DEFAULT_VALUE,
+ scope: 'USER',
+ },
+ PERSONAL_API_KEY: {
+ universalIdentifier: USER_SECRET_VARIABLE_ID,
+ isSecret: true,
scope: 'USER',
},
},
@@ -123,17 +132,51 @@ describe('Front component application variables', () => {
expect(publicVariable.value).not.toContain(PUBLIC_VARIABLE_VALUE);
});
- it('should expose non-secret workspace variables decrypted and exclude secret and user ones', async () => {
- const { data } = await findFrontComponent({
+ it('should expose non-secret variables with the viewing member values of user variables', async () => {
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: TEST_APP_ID,
+ key: 'RECORD_MY_MEETINGS',
+ value: 'on',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ await updateMyUserApplicationVariable({
+ input: {
+ applicationUniversalIdentifier: TEST_APP_ID,
+ key: 'PERSONAL_API_KEY',
+ value: 'jony-personal-key',
+ },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const { data: jonyData } = await findFrontComponent({
+ input: { id: frontComponentId },
+ gqlFields: `
+ id
+ applicationVariables
+ `,
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(jonyData.frontComponent.applicationVariables).toEqual({
+ PUBLIC_ACCESS_TOKEN: PUBLIC_VARIABLE_VALUE,
+ RECORD_MY_MEETINGS: 'on',
+ });
+
+ const { data: janeData } = await findFrontComponent({
input: { id: frontComponentId },
gqlFields: `
id
applicationVariables
`,
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
});
- expect(data.frontComponent.applicationVariables).toEqual({
+ expect(janeData.frontComponent.applicationVariables).toEqual({
PUBLIC_ACCESS_TOKEN: PUBLIC_VARIABLE_VALUE,
+ RECORD_MY_MEETINGS: USER_VARIABLE_DEFAULT_VALUE,
});
});
});